From f8b18ae8ffc5402126515f161a0ea6b6741a7492 Mon Sep 17 00:00:00 2001 From: buildmaster Date: Wed, 24 Jul 2024 01:52:01 +0000 Subject: [PATCH] Bumping versions --- .../client/ActuatorDisabledHealthTest.java | 12 +- .../ActuatorEnabledFailFastExceptionTest.java | 4 +- .../client/ActuatorEnabledHealthTest.java | 12 +- ...ctuatorEnabledNoFailFastExceptionTest.java | 4 +- ...esClientHealthIndicatorNotInsideTests.java | 2 +- ...esClientInfoContributorNotInsideTests.java | 2 +- .../client/KubernetesClientPodUtilsTests.java | 4 +- .../client/KubernetesClientUtilsTests.java | 2 +- .../ApiClientUserAgentDefaultHeader.java | 2 +- .../ApiClientUserAgentNonDefaultHeader.java | 2 +- ...bernetesClientConfigMapPropertySource.java | 5 +- .../KubernetesClientConfigMapsCache.java | 12 +- .../config/KubernetesClientSecretsCache.java | 11 +- ...KubernetesClientSecretsPropertySource.java | 5 +- ...ientEventBasedConfigMapChangeDetector.java | 8 +- ...ClientEventBasedSecretsChangeDetector.java | 9 +- ...ClientConfigDataLocationResolverTests.java | 12 +- ...ntConfigMapPropertySourceLocatorTests.java | 49 +- ...tesClientConfigMapPropertySourceTests.java | 55 +- ...ientConfigReloadAutoConfigurationTest.java | 58 +- .../KubernetesClientConfigUtilsTests.java | 2 +- ...ientSecretsPropertySourceLocatorTests.java | 12 +- ...netesClientSecretsPropertySourceTests.java | 28 +- ...igMapContextToSourceDataProviderTests.java | 233 +++++-- ...ecretContextToSourceDataProviderTests.java | 190 ++++-- ...igMapContextToSourceDataProviderTests.java | 90 ++- ...ecretContextToSourceDataProviderTests.java | 82 ++- ...ledConfigMapWithPrefixConfigDataTests.java | 6 +- .../LabeledConfigMapWithPrefixTests.java | 36 +- ...edConfigMapWithProfileConfigDataTests.java | 6 +- .../LabeledConfigMapWithProfileTests.java | 18 +- ...abeledSecretWithPrefixConfigDataTests.java | 6 +- .../LabeledSecretWithPrefixTests.java | 36 +- ...beledSecretWithProfileConfigDataTests.java | 6 +- .../LabeledSecretWithProfileTests.java | 18 +- ...medConfigMapWithPrefixConfigDataTests.java | 6 +- .../NamedConfigMapWithPrefixTests.java | 27 +- ...edConfigMapWithProfileConfigDataTests.java | 6 +- .../NamedConfigMapWithProfileTests.java | 27 +- .../NamedSecretWithPrefixConfigDataTests.java | 6 +- .../NamedSecretWithPrefixTests.java | 27 +- ...NamedSecretWithProfileConfigDataTests.java | 6 +- .../NamedSecretWithProfileTests.java | 27 +- ...gleSourceMultipleFilesConfigDataTests.java | 6 +- .../SingleSourceMultipleFilesTests.java | 36 +- .../ConfigDataRetryableSourcesOrderTests.java | 6 +- .../ConfigDataSourcesOrderTests.java | 6 +- .../sources_order/SourcesOrderTests.java | 27 +- ...bernetesClientSanitizeEnvEndpointStub.java | 19 +- ...dConfigMapWithPrefixConfigurationStub.java | 38 +- ...ConfigMapWithProfileConfigurationStub.java | 83 ++- ...eledSecretWithPrefixConfigurationStub.java | 42 +- ...ledSecretWithProfileConfigurationStub.java | 83 ++- ...dConfigMapWithPrefixConfigurationStub.java | 29 +- ...ConfigMapWithProfileConfigurationStub.java | 35 +- ...amedSecretWithPrefixConfigurationStub.java | 29 +- ...medSecretWithProfileConfigurationStub.java | 56 +- ...eSourceMultipleFilesConfigurationStub.java | 7 +- .../stubs/SourcesOrderConfigurationStub.java | 23 +- .../ConfigFailFastDisabled.java | 2 +- ...ConfigFailFastEnabledButRetryDisabled.java | 9 +- ...nfigMapEnableRetryWithoutFailFastTest.java | 8 +- ...igRetryDisabledButSecretsRetryEnabled.java | 11 +- .../configmap_retry/ConfigRetryEnabled.java | 40 +- ...ventBasedConfigMapChangeDetectorTests.java | 66 +- ...tEventBasedSecretsChangeDetectorTests.java | 73 +- ...lientSanitizeConfigpropsEndpointTests.java | 193 ++++-- ...ernetesClientSanitizeEnvEndpointTests.java | 197 ++++-- ...igDataFabric8ConfigpropsEndpointTests.java | 193 ++++-- ...ernetesClientSanitizeEnvEndpointTests.java | 197 ++++-- .../sanitize_secrets/ConfigDataSanitize.java | 6 +- ...SecretsEnableRetryWithoutFailFastTest.java | 8 +- .../SecretsFailFastDisabled.java | 2 +- ...ecretsFailFastEnabledButRetryDisabled.java | 11 +- ...etsRetryDisabledButConfigRetryEnabled.java | 11 +- .../secrets_retry/SecretsRetryEnabled.java | 40 +- ...onditionalOnBlockingOrReactiveEnabled.java | 2 +- ...nditionalOnSelectiveNamespacesMissing.java | 3 +- ...nditionalOnSelectiveNamespacesPresent.java | 3 +- .../K8sInstanceIdHostPodNameSupplier.java | 19 +- .../K8sPodLabelsAndAnnotationsSupplier.java | 2 +- ...ernetesClientConfigServerBootstrapper.java | 6 +- ...rSelectiveNamespacesAutoConfiguration.java | 4 +- .../KubernetesDiscoveryClientUtils.java | 21 +- .../KubernetesInformerDiscoveryClient.java | 45 +- .../catalog/KubernetesCatalogWatch.java | 2 +- .../KubernetesCatalogWatchContext.java | 6 +- .../KubernetesEndpointSlicesCatalogWatch.java | 22 +- .../KubernetesEndpointsCatalogWatch.java | 27 +- ...rnetesInformerReactiveDiscoveryClient.java | 4 +- ...K8sInstanceIdHostPodNameSupplierTests.java | 38 +- ...sPodLabelsAndAnnotationsSupplierTests.java | 16 +- ...esClientConfigServerBootstrapperTests.java | 73 +- ...ctiveNamespacesAutoConfigurationTests.java | 52 +- ...DiscoveryClientAutoConfigurationTests.java | 17 +- ...etesDiscoveryClientFilterMetadataTest.java | 20 +- .../KubernetesDiscoveryClientFilterTests.java | 18 +- ...veryClientServiceWithoutPortNameTests.java | 20 +- .../KubernetesDiscoveryClientTests.java | 146 ++-- .../KubernetesDiscoveryClientUtilsTests.java | 59 +- ...oConfigurationApplicationContextTests.java | 24 +- ...ubernetesInformerDiscoveryClientTests.java | 178 ++--- .../client/discovery/TestUtils.java | 60 +- ...oConfigurationApplicationContextTests.java | 8 +- ...rnetesCatalogWatchEndpointSlicesTests.java | 28 +- .../KubernetesCatalogWatchEndpointsTests.java | 22 +- ...atalogWatchEndpointSlicesSupportTests.java | 15 +- ...rnetesEndpointsAndEndpointSlicesTests.java | 23 +- ...oConfigurationApplicationContextTests.java | 30 +- ...DiscoveryClientAutoConfigurationTests.java | 17 +- ...sInformerReactiveDiscoveryClientTests.java | 81 +-- ...ClientLoadBalancerClientConfiguration.java | 7 +- ...KubernetesClientServiceInstanceMapper.java | 3 +- .../KubernetesClientServicesListSupplier.java | 12 +- ...netesClientServiceInstanceMapperTests.java | 25 +- ...rnetesClientServicesListSupplierTests.java | 53 +- .../client/loadbalancer/it/Util.java | 69 +- .../it/mode/pod/AllNamespacesTest.java | 48 +- .../it/mode/pod/SelectiveNamespacesTest.java | 76 ++- .../it/mode/pod/SpecificNamespaceTest.java | 50 +- .../it/mode/service/AllNamespacesTest.java | 60 +- .../mode/service/SelectiveNamespacesTest.java | 74 ++- .../mode/service/SpecificNamespaceTest.java | 48 +- ...netesCommonsSanitizeAutoConfiguration.java | 6 +- .../commons/KubernetesNamespaceProvider.java | 6 +- ...tryableConfigMapPropertySourceLocator.java | 18 +- ...RetryableSecretsPropertySourceLocator.java | 18 +- .../config/ConfigMapConfigProperties.java | 9 +- .../commons/config/ConfigUtils.java | 21 +- .../KubernetesBootstrapConfiguration.java | 8 +- .../KubernetesConfigDataLocationResolver.java | 11 +- .../config/KubernetesConfigDataResource.java | 5 +- .../KubernetesConfigServerBootstrapper.java | 15 +- .../commons/config/LabeledSourceData.java | 12 +- .../commons/config/NormalizedSource.java | 3 +- .../commons/config/PropertySourceUtils.java | 5 +- .../commons/config/RetryProperties.java | 1 - .../config/SecretsConfigProperties.java | 8 +- .../config/SecretsPropertySourceLocator.java | 9 +- .../config/SourceDataEntriesProcessor.java | 6 +- .../config/reload/ConfigReloadProperties.java | 2 +- .../config/reload/ConfigReloadUtil.java | 5 +- .../condition/EventReloadDetectionMode.java | 2 +- .../condition/PollingReloadDetectionMode.java | 2 +- .../discovery/DiscoveryClientUtils.java | 9 +- .../discovery/InstanceIdHostPodName.java | 1 + .../discovery/PodLabelsAndAnnotations.java | 1 + .../kubernetes/commons/discovery/Service.java | 1 + ...rnetesProfileEnvironmentPostProcessor.java | 7 +- .../KubernetesClientPropertiesTests.java | 250 +++---- ...bernetesCommonsAutoConfigurationTests.java | 7 +- ...CommonsSanitizeAutoConfigurationTests.java | 8 +- .../commons/LazilyInstantiateTest.java | 2 +- .../kubernetes/commons/SanitizeTests.java | 4 +- ...ConfigMapConfigPropertiesBindingTests.java | 111 ++-- .../config/ConfigReloadPropertiesTests.java | 39 +- .../config/ConfigUtilsProcessSourceTests.java | 10 +- .../commons/config/ConfigUtilsTests.java | 2 +- ...rnetesConfigDataLocationResolverTests.java | 14 +- .../SecretsConfigPropertiesBindingTests.java | 112 ++-- ...tEnabledWithDefaultRetryConfiguration.java | 2 +- .../bootstrap/ConfigFailFastEnabled.java | 2 +- ...tEnabledWithoutSpringRetryOnClasspath.java | 14 +- .../bootstrap/SecretsFailFastEnabled.java | 2 +- .../discovery/DiscoveryClientUtilsTests.java | 78 ++- ...ClientHealthIndicatorInitializerTests.java | 18 +- ...netesDiscoveryPropertiesMetadataTests.java | 24 +- .../KubernetesDiscoveryPropertiesTests.java | 115 ++-- .../KubernetesServiceInstanceTests.java | 2 +- .../ServicePortSecureResolverTest.java | 14 +- ...KubernetesLoadBalancerPropertiesTests.java | 40 +- ...esProfileEnvironmentPostProcessorTest.java | 9 +- ...oConfigurationApplicationContextTests.java | 9 +- ...bledProfileIncludedSecretsApiDisabled.java | 2 +- .../KubernetesEnvironmentRepositoryTests.java | 193 +++--- ...KubernetesPropertySourceSupplierTests.java | 56 +- ...ConfigDataConfigServerIntegrationTest.java | 2 +- .../it/ConfigServerIntegrationTest.java | 41 +- .../ConfigMapWatcherChangeDetector.java | 4 +- .../watcher/HttpRefreshTrigger.java | 17 +- .../configuration/watcher/RefreshTrigger.java | 3 +- ...edConfigMapWatcherChangeDetectorTests.java | 2 +- ...asedSecretsWatcherChangeDetectorTests.java | 2 +- ...asedConfigMapWatchChangeDetectorTests.java | 18 +- ...pBasedSecretsWatchChangeDetectorTests.java | 12 +- .../watcher/WatcherUtilTests.java | 12 +- .../DiscoveryServerController.java | 10 +- ...iscoveryCatalogWatcherControllerTests.java | 5 +- .../DiscoveryServerControllerTests.java | 8 +- ...veryServerIntegrationAppsEndpointTest.java | 44 +- ...ServerIntegrationAppsNameEndpointTest.java | 25 +- ...ServerIntegrationInstanceEndpointTest.java | 31 +- .../discovery/ConfigServerBootstrapper.java | 8 +- .../discovery/KubernetesCatalogWatch.java | 2 +- .../discovery/KubernetesDiscoveryClient.java | 4 +- ...netesDiscoveryClientAutoConfiguration.java | 2 +- .../KubernetesReactiveDiscoveryClient.java | 10 +- .../ConfigServerBootstrapperTests.java | 12 +- ...tesCatalogWatchAutoConfigurationTests.java | 8 +- .../KubernetesCatalogWatchTests.java | 16 +- ...rnetesDiscoveryAutoConfigurationTests.java | 13 +- ...DiscoveryClientAutoConfigurationTests.java | 80 +-- .../KubernetesDiscoveryClientTests.java | 6 +- ...ubernetesReactiveDiscoveryClientTests.java | 10 +- .../fabric8/Fabric8AutoConfiguration.java | 69 +- .../Fabric8HealthIndicatorDisabledTest.java | 12 +- .../Fabric8InsideHealthIndicatorTest.java | 47 +- .../Fabric8InsideInfoContributorTest.java | 36 +- .../Fabric8NotInsideHealthIndicatorTest.java | 15 +- .../Fabric8NotInsideInfoContributorTest.java | 11 +- .../fabric8/Fabric8UtilsMockTests.java | 2 +- ...8ProfileEnvironmentPostProcessorTests.java | 8 +- .../Fabric8ConfigMapPropertySource.java | 5 +- .../config/Fabric8ConfigMapsCache.java | 6 +- .../fabric8/config/Fabric8SecretsCache.java | 6 +- .../config/Fabric8SecretsPropertySource.java | 5 +- ...ric8EventBasedConfigMapChangeDetector.java | 6 +- ...abric8EventBasedSecretsChangeDetector.java | 6 +- ...nfigMapEnableRetryWithoutFailFastTest.java | 4 +- .../config/ConfigMapsFromFilePathsTests.java | 54 +- .../fabric8/config/ConfigMapsMixedTests.java | 37 +- .../fabric8/config/ConfigMapsTest.java | 58 +- .../fabric8/config/ConfigMapsTests.java | 20 +- ...ConfigMapsWithActiveProfilesNameTests.java | 42 +- .../ConfigMapsWithProfileExpressionTests.java | 20 +- ...gMapsWithProfilesNoActiveProfileTests.java | 30 +- .../config/ConfigMapsWithProfilesTests.java | 30 +- .../ConfigMapsWithoutProfilesTests.java | 30 +- .../kubernetes/fabric8/config/CoreTest.java | 15 +- ...BasedConfigurationChangeDetectorTests.java | 2 +- ...abric8ConfigDataLocationResolverTests.java | 8 +- ...nfigMapPropertySourceLocatorMockTests.java | 2 +- ...c8ConfigMapPropertySourceLocatorTests.java | 2 +- .../Fabric8ConfigMapPropertySourceTests.java | 2 +- .../config/Fabric8ConfigUtilsTests.java | 208 +++--- ...ric8SecretsPropertySourceLocatorTests.java | 2 +- ...Fabric8SecretsPropertySourceMockTests.java | 6 +- .../fabric8/config/HealthIndicatorTest.java | 12 +- .../config/KubernetesConfigTestBase.java | 4 +- ...igMapContextToSourceDataProviderTests.java | 206 ++++-- ...ecretContextToSourceDataProviderTests.java | 218 ++++-- .../fabric8/config/MissingActuatorTest.java | 6 +- .../config/MultipleConfigMapsTests.java | 21 +- .../fabric8/config/MultipleSecretsTests.java | 26 +- ...igMapContextToSourceDataProviderTests.java | 107 ++- ...ecretContextToSourceDataProviderTests.java | 114 +++- ...SecretsEnableRetryWithoutFailFastTest.java | 4 +- .../config/actuator/DisabledHealthTest.java | 12 +- .../config/actuator/EnabledHealthTest.java | 12 +- .../LabeledConfigMapWithPrefixTests.java | 47 +- .../LabeledConfigMapWithProfileTests.java | 29 +- .../LabeledSecretWithPrefixTests.java | 47 +- .../LabeledSecretWithProfileTests.java | 29 +- ...igRetryDisabledButSecretsRetryEnabled.java | 2 +- .../ConfigRetryEnabled.java | 32 +- ...ConfigFailFastEnabledButRetryDisabled.java | 4 +- .../NamedConfigMapWithPrefixTests.java | 34 +- .../NamedConfigMapWithProfileTests.java | 34 +- .../NamedSecretWithPrefixTests.java | 34 +- .../NamedSecretWithProfileTests.java | 34 +- .../ConfigReloadAutoConfigurationTest.java | 63 +- ...etsRetryDisabledButConfigRetryEnabled.java | 2 +- ...ecretsFailFastEnabledButRetryDisabled.java | 2 +- ...etsRetryDisabledButConfigRetryEnabled.java | 2 +- .../secrets_enabled/SecretsRetryEnabled.java | 20 +- .../RetryableSourcesOrderTests.java | 39 +- ...bric8SanitizeConfigpropsEndpointTests.java | 193 ++++-- ...tstrapFabric8SanitizeEnvEndpointTests.java | 197 ++++-- ...igDataFabric8ConfigpropsEndpointTests.java | 193 ++++-- ...igDataFabric8SanitizeEnvEndpointTests.java | 197 ++++-- .../Fabric8SecretsSanitize.java | 27 +- .../Fabric8SecretsPropertySourceTest.java | 9 +- .../SecretsWithLabelsTests.java | 16 +- .../SingleSourceMultipleFilesTests.java | 47 +- .../sources_order/SourcesOrderTests.java | 39 +- .../discovery/Fabric8CatalogWatchContext.java | 6 +- .../Fabric8ConfigServerBootstrapper.java | 4 +- .../Fabric8DiscoveryServicesAdapter.java | 14 +- .../Fabric8EndpointSliceV1CatalogWatch.java | 29 +- .../Fabric8EndpointsCatalogWatch.java | 11 +- .../Fabric8InstanceIdHostPodNameSupplier.java | 19 +- ...Fabric8KubernetesDiscoveryClientUtils.java | 48 +- ...abric8PodLabelsAndAnnotationsSupplier.java | 3 +- .../discovery/KubernetesCatalogWatch.java | 17 +- .../discovery/KubernetesDiscoveryClient.java | 5 +- .../KubernetesReactiveDiscoveryClient.java | 4 +- .../Fabric8CatalogWatchContextTests.java | 4 +- .../Fabric8ConfigServerBootstrapperTests.java | 38 +- .../Fabric8DiscoveryServicesAdapterTests.java | 13 +- ...abric8EndpointsAndEndpointSlicesTests.java | 28 +- ...ic8InstanceIdHostPodNameSupplierTests.java | 46 +- ...atalogWatchEndpointSlicesSupportTests.java | 13 +- ...veryClientServiceWithoutPortNameTests.java | 16 +- .../Fabric8KubernetesDiscoveryClientTest.java | 626 +++++++++++++----- ...Fabric8KubernetesDiscoveryClientTests.java | 82 ++- ...rnetesDiscoveryClientUtilsFilterTests.java | 14 +- ...c8KubernetesDiscoveryClientUtilsTests.java | 31 +- ...8PodLabelsAndAnnotationsSupplierTests.java | 23 +- ...CatalogServicesWatchConfigurationTest.java | 4 +- ...oConfigurationApplicationContextTests.java | 9 +- .../discovery/KubernetesCatalogWatchTest.java | 55 +- ...oConfigurationApplicationContextTests.java | 18 +- ...lientAutoConfigurationPropertiesTests.java | 5 +- ...DiscoveryClientAutoConfigurationTests.java | 2 +- ...etesDiscoveryClientFilterMetadataTest.java | 37 +- .../KubernetesDiscoveryClientFilterTest.java | 2 +- .../KubernetesDiscoveryClientUtilsTests.java | 20 +- ...oConfigurationApplicationContextTests.java | 21 +- ...DiscoveryClientAutoConfigurationTests.java | 19 +- ...ubernetesReactiveDiscoveryClientTests.java | 310 ++++++--- .../fabric8/client/istio/utils/MeshUtils.java | 2 +- .../leader/Fabric8LeaderRecordWatcher.java | 5 +- .../leader/Fabric8LeadershipController.java | 30 +- .../Fabric8LeaderAutoConfigurationTests.java | 10 +- .../Fabric8LeaderRecordWatcherTest.java | 6 +- .../Fabric8LeadershipControllerTest.java | 2 +- .../Fabric8PodReadinessWatcherTest.java | 2 +- .../fabric8/leader/LeaderContextTest.java | 2 +- .../fabric8/leader/LeaderInitiatorTest.java | 6 +- ...abric8LoadBalancerClientConfiguration.java | 5 +- .../Fabric8ServiceInstanceMapper.java | 3 +- .../Fabric8ServicesListSupplier.java | 13 +- ...ic8LoadBalancerAutoConfigurationTests.java | 33 +- .../Fabric8ServiceInstanceMapperTests.java | 54 +- .../Fabric8ServiceListSupplierTests.java | 21 +- ...c8ServicesListSupplierMockClientTests.java | 32 +- .../fabric8/loadbalancer/it/Util.java | 20 +- .../it/mode/pod/AllNamespacesTest.java | 50 +- .../it/mode/pod/SelectiveNamespacesTest.java | 58 +- .../it/mode/pod/SpecificNamespaceTest.java | 38 +- .../it/mode/service/AllNamespacesTest.java | 48 +- .../mode/service/SelectiveNamespacesTest.java | 44 +- .../mode/service/SpecificNamespaceTest.java | 28 +- .../catalog/watch/Fabric8CatalogWatchIT.java | 18 +- ...ic8CatalogWatchWithNamespacesDelegate.java | 12 +- .../Fabric8ApplicationDiscoveryListener.java | 2 +- .../Fabric8DiscoveryBoostrapDelegate.java | 9 +- .../Fabric8DiscoveryClientHealthDelegate.java | 95 +-- .../discovery/Fabric8DiscoveryDelegate.java | 18 +- .../Fabric8DiscoveryFilterDelegate.java | 35 +- .../Fabric8DiscoveryNamespaceDelegate.java | 16 +- .../Fabric8DiscoveryPodMetadataIT.java | 47 +- .../fabric8/client/istio/Fabric8IstioIT.java | 14 +- ...edPollingReloadConfigMapMountDelegate.java | 16 +- .../ConfigMapMountPollingReloadDelegate.java | 16 +- .../DataChangesInConfigMapReloadDelegate.java | 40 +- .../client/reload/Fabric8EventReloadIT.java | 110 ++- .../reload/SecretsEventsReloadDelegate.java | 42 +- .../fabric8/client/reload/TestUtil.java | 6 +- .../KubernetesClientCatalogWatchIT.java | 12 +- ...sClientCatalogWatchNamespacesDelegate.java | 15 +- .../watcher/ActuatorRefreshIT.java | 60 +- .../ActuatorRefreshMultipleNamespacesIT.java | 71 +- ...iscoveryClientFilterNamespaceDelegate.java | 67 +- .../discoveryclient/it/DiscoveryClientIT.java | 52 +- .../KubernetesClientDiscoveryClientIT.java | 141 ++-- ...rnetesClientDiscoveryFilterITDelegate.java | 35 +- ...rnetesClientDiscoveryHealthITDelegate.java | 185 ++++-- ...MultipleSelectiveNamespacesITDelegate.java | 50 +- ...sClientDiscoveryPodMetadataITDelegate.java | 21 +- ...sClientDiscoverySelectiveNamespacesIT.java | 55 +- .../ConfigurationWatcherMultipleAppsIT.java | 35 +- .../ConfigurationWatcherMultipleAppIT.java | 34 +- ...edPollingReloadConfigMapMountDelegate.java | 15 +- .../DataChangesInConfigMapReloadDelegate.java | 51 +- .../configmap/K8sClientConfigMapReloadIT.java | 95 ++- .../K8sClientConfigMapReloadITUtil.java | 6 +- .../PollingReloadConfigMapMountDelegate.java | 15 +- .../DataChangesInSecretsReloadDelegate.java | 39 +- .../secret/K8sClientSecretsReloadIT.java | 22 +- .../integration/tests/commons/Commons.java | 91 +-- .../integration/tests/commons/Images.java | 7 +- .../integration/tests/commons/K8SUtils.java | 99 ++- .../tests/commons/fabric8_client/Util.java | 147 ++-- .../tests/commons/native_client/Util.java | 77 ++- .../tests/discovery/TestsDiscovery.java | 24 +- 376 files changed, 8611 insertions(+), 4570 deletions(-) diff --git a/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/ActuatorDisabledHealthTest.java b/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/ActuatorDisabledHealthTest.java index a6675c2970..7cc51045f6 100644 --- a/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/ActuatorDisabledHealthTest.java +++ b/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/ActuatorDisabledHealthTest.java @@ -47,9 +47,15 @@ class ActuatorDisabledHealthTest { @Test void healthEndpointShouldNotContainKubernetes() { - this.webClient.get().uri("http://localhost:{port}/actuator/health", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("components.kubernetes").doesNotExist(); + this.webClient.get() + .uri("http://localhost:{port}/actuator/health", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("components.kubernetes") + .doesNotExist(); Assertions.assertNull(registry.getContributor("kubernetes"), "reactive kubernetes contributor must NOT be present when 'management.health.kubernetes.enabled=false'"); diff --git a/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/ActuatorEnabledFailFastExceptionTest.java b/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/ActuatorEnabledFailFastExceptionTest.java index b851245b05..1293c7f574 100644 --- a/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/ActuatorEnabledFailFastExceptionTest.java +++ b/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/ActuatorEnabledFailFastExceptionTest.java @@ -77,7 +77,7 @@ private static void mocks() { pathsMockedStatic = Mockito.mockStatic(Paths.class); envReaderMockedStatic.when(() -> EnvReader.getEnv(KubernetesClientPodUtils.KUBERNETES_SERVICE_HOST)) - .thenReturn("k8s-host"); + .thenReturn("k8s-host"); envReaderMockedStatic.when(() -> EnvReader.getEnv(KubernetesClientPodUtils.HOSTNAME)).thenReturn("host"); Path serviceAccountTokenPath = Mockito.mock(Path.class); @@ -104,7 +104,7 @@ KubernetesClientPodUtils kubernetesPodUtils() throws ApiException { mocks(); Mockito.when(coreV1Api.readNamespacedPod("host", "my-namespace", null)) - .thenThrow(new RuntimeException("just because")); + .thenThrow(new RuntimeException("just because")); return new KubernetesClientPodUtils(coreV1Api, "my-namespace", FAIL_FAST); } diff --git a/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/ActuatorEnabledHealthTest.java b/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/ActuatorEnabledHealthTest.java index df2a41e04d..37d8117aa2 100644 --- a/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/ActuatorEnabledHealthTest.java +++ b/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/ActuatorEnabledHealthTest.java @@ -44,9 +44,15 @@ class ActuatorEnabledHealthTest { @Test void healthEndpointShouldContainKubernetes() { - this.webClient.get().uri("http://localhost:{port}/actuator/health", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("components.kubernetes").exists(); + this.webClient.get() + .uri("http://localhost:{port}/actuator/health", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("components.kubernetes") + .exists(); Assertions.assertNotNull(registry.getContributor("kubernetes"), "reactive kubernetes contributor must be present when 'management.health.kubernetes.enabled=true'"); diff --git a/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/ActuatorEnabledNoFailFastExceptionTest.java b/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/ActuatorEnabledNoFailFastExceptionTest.java index f6bba80d3e..57c6db17b4 100644 --- a/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/ActuatorEnabledNoFailFastExceptionTest.java +++ b/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/ActuatorEnabledNoFailFastExceptionTest.java @@ -80,7 +80,7 @@ private static void mocks() { pathsMockedStatic = Mockito.mockStatic(Paths.class); envReaderMockedStatic.when(() -> EnvReader.getEnv(KubernetesClientPodUtils.KUBERNETES_SERVICE_HOST)) - .thenReturn("k8s-host"); + .thenReturn("k8s-host"); envReaderMockedStatic.when(() -> EnvReader.getEnv(KubernetesClientPodUtils.HOSTNAME)).thenReturn("host"); Path serviceAccountTokenPath = Mockito.mock(Path.class); @@ -107,7 +107,7 @@ KubernetesClientPodUtils kubernetesPodUtils() throws ApiException { mocks(); Mockito.when(coreV1Api.readNamespacedPod("host", "my-namespace", null)) - .thenThrow(new RuntimeException("just because")); + .thenThrow(new RuntimeException("just because")); return new KubernetesClientPodUtils(coreV1Api, "my-namespace", FAIL_FAST); } diff --git a/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/KubernetesClientHealthIndicatorNotInsideTests.java b/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/KubernetesClientHealthIndicatorNotInsideTests.java index ac29de59b3..969ce158dd 100644 --- a/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/KubernetesClientHealthIndicatorNotInsideTests.java +++ b/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/KubernetesClientHealthIndicatorNotInsideTests.java @@ -40,7 +40,7 @@ public class KubernetesClientHealthIndicatorNotInsideTests { @Test public void test() { assertThatThrownBy(() -> context.getBean(KubernetesClientHealthIndicator.class)) - .isInstanceOf(NoSuchBeanDefinitionException.class); + .isInstanceOf(NoSuchBeanDefinitionException.class); } } diff --git a/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/KubernetesClientInfoContributorNotInsideTests.java b/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/KubernetesClientInfoContributorNotInsideTests.java index ec6fac6b25..8406ff4989 100644 --- a/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/KubernetesClientInfoContributorNotInsideTests.java +++ b/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/KubernetesClientInfoContributorNotInsideTests.java @@ -40,7 +40,7 @@ public class KubernetesClientInfoContributorNotInsideTests { @Test public void test() { assertThatThrownBy(() -> context.getBean(KubernetesClientInfoContributor.class)) - .isInstanceOf(NoSuchBeanDefinitionException.class); + .isInstanceOf(NoSuchBeanDefinitionException.class); } } diff --git a/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/KubernetesClientPodUtilsTests.java b/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/KubernetesClientPodUtilsTests.java index e97b901d23..e6a245e725 100644 --- a/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/KubernetesClientPodUtilsTests.java +++ b/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/KubernetesClientPodUtilsTests.java @@ -84,8 +84,8 @@ void after() { @Test void constructorThrowsIllegalArgumentExceptionWhenKubeClientIsNull() { assertThatThrownBy(() -> new KubernetesClientPodUtils(null, "namespace", false)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Must provide an instance of KubernetesClient"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Must provide an instance of KubernetesClient"); } @Test diff --git a/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/KubernetesClientUtilsTests.java b/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/KubernetesClientUtilsTests.java index 8f11da75da..9a357b6c66 100644 --- a/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/KubernetesClientUtilsTests.java +++ b/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/KubernetesClientUtilsTests.java @@ -48,7 +48,7 @@ void testNamespaceFromProvider() { @Test void testNamespaceResolutionFailed() { assertThatThrownBy(() -> KubernetesClientUtils.getApplicationNamespace("", "target", null)) - .isInstanceOf(NamespaceResolutionFailedException.class); + .isInstanceOf(NamespaceResolutionFailedException.class); } } diff --git a/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/default_api/ApiClientUserAgentDefaultHeader.java b/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/default_api/ApiClientUserAgentDefaultHeader.java index 46ac865e9a..f888ead7da 100644 --- a/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/default_api/ApiClientUserAgentDefaultHeader.java +++ b/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/default_api/ApiClientUserAgentDefaultHeader.java @@ -53,7 +53,7 @@ void testApiClientUserAgentDefaultHeader() throws MalformedURLException { Request.Builder builder = new Request.Builder(); apiClient.processHeaderParams(Collections.emptyMap(), builder); assertThat(builder.url(new URL("http://example.com")).build().headers().get("User-Agent")) - .isEqualTo("Spring-Cloud-Kubernetes-Application"); + .isEqualTo("Spring-Cloud-Kubernetes-Application"); } } diff --git a/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/default_api/ApiClientUserAgentNonDefaultHeader.java b/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/default_api/ApiClientUserAgentNonDefaultHeader.java index 7c08fb6b73..792ff39ca0 100644 --- a/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/default_api/ApiClientUserAgentNonDefaultHeader.java +++ b/spring-cloud-kubernetes-client-autoconfig/src/test/java/org/springframework/cloud/kubernetes/client/default_api/ApiClientUserAgentNonDefaultHeader.java @@ -57,7 +57,7 @@ void testApiClientUserAgentDefaultHeader() throws MalformedURLException { Request.Builder builder = new Request.Builder(); apiClient.processHeaderParams(Collections.emptyMap(), builder); assertThat(builder.url(new URL("http://example.com")).build().headers().get("User-Agent")) - .isEqualTo("non-default"); + .isEqualTo("non-default"); } } diff --git a/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigMapPropertySource.java b/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigMapPropertySource.java index d66f16d582..1630899e57 100644 --- a/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigMapPropertySource.java +++ b/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigMapPropertySource.java @@ -43,8 +43,9 @@ public KubernetesClientConfigMapPropertySource(KubernetesClientConfigContext con private static SourceData getSourceData(KubernetesClientConfigContext context) { NormalizedSourceType type = context.normalizedSource().type(); - return Optional.ofNullable(STRATEGIES.get(type)).map(x -> x.apply(context)) - .orElseThrow(() -> new IllegalArgumentException("no strategy found for : " + type)); + return Optional.ofNullable(STRATEGIES.get(type)) + .map(x -> x.apply(context)) + .orElseThrow(() -> new IllegalArgumentException("no strategy found for : " + type)); } private static KubernetesClientContextToSourceData namedConfigMap() { diff --git a/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigMapsCache.java b/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigMapsCache.java index b373a5f007..01c2b708b7 100644 --- a/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigMapsCache.java +++ b/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigMapsCache.java @@ -55,8 +55,10 @@ static List byNamespace(CoreV1Api coreV1Api, String nam List result = CACHE.computeIfAbsent(namespace, x -> { try { b[0] = true; - return strippedConfigMaps(coreV1Api.listNamespacedConfigMap(namespace, null, null, null, null, null, - null, null, null, null, null, null).getItems()); + return strippedConfigMaps(coreV1Api + .listNamespacedConfigMap(namespace, null, null, null, null, null, null, null, null, null, null, + null) + .getItems()); } catch (ApiException apiException) { throw new RuntimeException(apiException.getResponseBody(), apiException); @@ -74,8 +76,10 @@ static List byNamespace(CoreV1Api coreV1Api, String nam } private static List strippedConfigMaps(List configMaps) { - return configMaps.stream().map(configMap -> new StrippedSourceContainer(configMap.getMetadata().getLabels(), - configMap.getMetadata().getName(), configMap.getData())).collect(Collectors.toList()); + return configMaps.stream() + .map(configMap -> new StrippedSourceContainer(configMap.getMetadata().getLabels(), + configMap.getMetadata().getName(), configMap.getData())) + .collect(Collectors.toList()); } } diff --git a/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientSecretsCache.java b/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientSecretsCache.java index 7544408647..75eb051bec 100644 --- a/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientSecretsCache.java +++ b/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientSecretsCache.java @@ -57,8 +57,9 @@ static List byNamespace(CoreV1Api coreV1Api, String nam List result = CACHE.computeIfAbsent(namespace, x -> { try { b[0] = true; - return strippedSecrets(coreV1Api.listNamespacedSecret(namespace, null, null, null, null, null, null, - null, null, null, null, null).getItems()); + return strippedSecrets(coreV1Api + .listNamespacedSecret(namespace, null, null, null, null, null, null, null, null, null, null, null) + .getItems()); } catch (ApiException apiException) { throw new RuntimeException(apiException.getResponseBody(), apiException); @@ -76,8 +77,10 @@ static List byNamespace(CoreV1Api coreV1Api, String nam } private static List strippedSecrets(List secrets) { - return secrets.stream().map(secret -> new StrippedSourceContainer(secret.getMetadata().getLabels(), - secret.getMetadata().getName(), transform(secret.getData()))).collect(Collectors.toList()); + return secrets.stream() + .map(secret -> new StrippedSourceContainer(secret.getMetadata().getLabels(), secret.getMetadata().getName(), + transform(secret.getData()))) + .collect(Collectors.toList()); } private static Map transform(Map in) { diff --git a/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientSecretsPropertySource.java b/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientSecretsPropertySource.java index bac7a39fe5..df328b9334 100644 --- a/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientSecretsPropertySource.java +++ b/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientSecretsPropertySource.java @@ -48,8 +48,9 @@ public KubernetesClientSecretsPropertySource(KubernetesClientConfigContext conte private static SourceData getSourceData(KubernetesClientConfigContext context) { NormalizedSourceType type = context.normalizedSource().type(); - return Optional.ofNullable(STRATEGIES.get(type)).map(x -> x.apply(context)) - .orElseThrow(() -> new IllegalArgumentException("no strategy found for : " + type)); + return Optional.ofNullable(STRATEGIES.get(type)) + .map(x -> x.apply(context)) + .orElseThrow(() -> new IllegalArgumentException("no strategy found for : " + type)); } private static KubernetesClientContextToSourceData namedSecret() { diff --git a/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/reload/KubernetesClientEventBasedConfigMapChangeDetector.java b/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/reload/KubernetesClientEventBasedConfigMapChangeDetector.java index 0581017f69..c153f83a06 100644 --- a/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/reload/KubernetesClientEventBasedConfigMapChangeDetector.java +++ b/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/reload/KubernetesClientEventBasedConfigMapChangeDetector.java @@ -124,11 +124,9 @@ void inform() { SharedInformerFactory factory = new SharedInformerFactory(apiClient); factories.add(factory); informer = factory - .sharedIndexInformerFor( - (CallGeneratorParams params) -> coreV1Api.listNamespacedConfigMapCall(namespace, null, null, - null, null, filter[0], null, params.resourceVersion, null, null, - params.timeoutSeconds, params.watch, null), - V1ConfigMap.class, V1ConfigMapList.class); + .sharedIndexInformerFor((CallGeneratorParams params) -> coreV1Api.listNamespacedConfigMapCall(namespace, + null, null, null, null, filter[0], null, params.resourceVersion, null, null, + params.timeoutSeconds, params.watch, null), V1ConfigMap.class, V1ConfigMapList.class); LOG.debug(() -> "added configmap informer for namespace : " + namespace + " with filter : " + filter[0]); diff --git a/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/reload/KubernetesClientEventBasedSecretsChangeDetector.java b/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/reload/KubernetesClientEventBasedSecretsChangeDetector.java index f97da12a2b..4cdcb90aac 100644 --- a/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/reload/KubernetesClientEventBasedSecretsChangeDetector.java +++ b/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/reload/KubernetesClientEventBasedSecretsChangeDetector.java @@ -126,11 +126,10 @@ void inform() { } SharedInformerFactory factory = new SharedInformerFactory(apiClient); factories.add(factory); - informer = factory.sharedIndexInformerFor( - (CallGeneratorParams params) -> coreV1Api.listNamespacedSecretCall(namespace, null, null, null, - null, filter[0], null, params.resourceVersion, null, null, params.timeoutSeconds, - params.watch, null), - V1Secret.class, V1SecretList.class); + informer = factory + .sharedIndexInformerFor((CallGeneratorParams params) -> coreV1Api.listNamespacedSecretCall(namespace, + null, null, null, null, filter[0], null, params.resourceVersion, null, null, + params.timeoutSeconds, params.watch, null), V1Secret.class, V1SecretList.class); LOG.debug(() -> "added secret informer for namespace : " + namespace + " with filter : " + filter[0]); diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigDataLocationResolverTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigDataLocationResolverTests.java index 8442cf5591..178ecda362 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigDataLocationResolverTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigDataLocationResolverTests.java @@ -52,7 +52,7 @@ class KubernetesClientConfigDataLocationResolverTests { private static final DeferredLogFactory FACTORY = Supplier::get; private static final ConfigDataLocationResolverContext RESOLVER_CONTEXT = Mockito - .mock(ConfigDataLocationResolverContext.class); + .mock(ConfigDataLocationResolverContext.class); private static final KubernetesClientConfigDataLocationResolver RESOLVER = new KubernetesClientConfigDataLocationResolver( FACTORY); @@ -125,7 +125,7 @@ void testBothPresent() { Assertions.assertTrue(context.isRegistered(SecretsPropertySourceLocator.class)); ConfigMapPropertySourceLocator configMapPropertySourceLocator = context - .get(ConfigMapPropertySourceLocator.class); + .get(ConfigMapPropertySourceLocator.class); Assertions.assertSame(KubernetesClientConfigMapPropertySourceLocator.class, configMapPropertySourceLocator.getClass()); @@ -169,7 +169,7 @@ void testBothPresentExplicitly(CapturedOutput capturedOutput) { Assertions.assertTrue(context.isRegistered(SecretsConfigProperties.class)); ConfigMapPropertySourceLocator configMapPropertySourceLocator = context - .get(ConfigMapPropertySourceLocator.class); + .get(ConfigMapPropertySourceLocator.class); Assertions.assertSame(KubernetesClientConfigMapPropertySourceLocator.class, configMapPropertySourceLocator.getClass()); @@ -178,8 +178,8 @@ void testBothPresentExplicitly(CapturedOutput capturedOutput) { secretsPropertySourceLocator.getClass()); Assertions.assertTrue(capturedOutput.getOut() - .contains("Could not create the Kubernetes ApiClient in a cluster environment, because connection port " - + "was not provided.")); + .contains("Could not create the Kubernetes ApiClient in a cluster environment, because connection port " + + "was not provided.")); } /* @@ -222,7 +222,7 @@ void testBothPresentAndRetryEnabled() { Assertions.assertTrue(context.isRegistered(SecretsPropertySourceLocator.class)); ConfigMapPropertySourceLocator configMapPropertySourceLocator = context - .get(ConfigMapPropertySourceLocator.class); + .get(ConfigMapPropertySourceLocator.class); Assertions.assertSame(ConfigDataRetryableConfigMapPropertySourceLocator.class, configMapPropertySourceLocator.getClass()); diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigMapPropertySourceLocatorTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigMapPropertySourceLocatorTests.java index 0ec6e336a3..2c11c54146 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigMapPropertySourceLocatorTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigMapPropertySourceLocatorTests.java @@ -57,14 +57,15 @@ class KubernetesClientConfigMapPropertySourceLocatorTests { private static final V1ConfigMapList PROPERTIES_CONFIGMAP_LIST = new V1ConfigMapList() - .addItemsItem( - new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("bootstrap-640").withNamespace("default") - .withResourceVersion("1").build()) - .addToData("application.properties", - "spring.cloud.kubernetes.configuration.watcher.refreshDelay=0\n" - + "logging.level.org.springframework.cloud.kubernetes=TRACE") - .build()); + .addItemsItem(new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("bootstrap-640") + .withNamespace("default") + .withResourceVersion("1") + .build()) + .addToData("application.properties", + "spring.cloud.kubernetes.configuration.watcher.refreshDelay=0\n" + + "logging.level.org.springframework.cloud.kubernetes=TRACE") + .build()); private static WireMockServer wireMockServer; @@ -96,22 +97,23 @@ public void afterEach() { void locateWithoutSources() { CoreV1Api api = new CoreV1Api(); stubFor(get("/api/v1/namespaces/default/configmaps") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(PROPERTIES_CONFIGMAP_LIST)))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(PROPERTIES_CONFIGMAP_LIST)))); ConfigMapConfigProperties configMapConfigProperties = new ConfigMapConfigProperties(true, List.of(), List.of(), Map.of(), true, "bootstrap-640", null, false, false, false, RetryProperties.DEFAULT); MockEnvironment mockEnvironment = new MockEnvironment(); mockEnvironment.setProperty("spring.cloud.kubernetes.client.namespace", "default"); PropertySource propertySource = new KubernetesClientConfigMapPropertySourceLocator(api, - configMapConfigProperties, new KubernetesNamespaceProvider(mockEnvironment)).locate(ENV); + configMapConfigProperties, new KubernetesNamespaceProvider(mockEnvironment)) + .locate(ENV); assertThat(propertySource.containsProperty("spring.cloud.kubernetes.configuration.watcher.refreshDelay")) - .isTrue(); + .isTrue(); } @Test void locateWithSources() { CoreV1Api api = new CoreV1Api(); stubFor(get("/api/v1/namespaces/default/configmaps") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(PROPERTIES_CONFIGMAP_LIST)))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(PROPERTIES_CONFIGMAP_LIST)))); ConfigMapConfigProperties.Source source = new ConfigMapConfigProperties.Source("bootstrap-640", "default", Collections.emptyMap(), null, null, null); @@ -119,9 +121,10 @@ void locateWithSources() { List.of(source), Map.of(), true, "fake-name", null, false, false, false, RetryProperties.DEFAULT); PropertySource propertySource = new KubernetesClientConfigMapPropertySourceLocator(api, - configMapConfigProperties, new KubernetesNamespaceProvider(new MockEnvironment())).locate(ENV); + configMapConfigProperties, new KubernetesNamespaceProvider(new MockEnvironment())) + .locate(ENV); assertThat(propertySource.containsProperty("spring.cloud.kubernetes.configuration.watcher.refreshDelay")) - .isTrue(); + .isTrue(); } /** @@ -135,14 +138,14 @@ void locateWithSources() { void testLocateWithoutNamespaceConstructor() { CoreV1Api api = new CoreV1Api(); stubFor(get("/api/v1/namespaces/default/configmaps") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(PROPERTIES_CONFIGMAP_LIST)))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(PROPERTIES_CONFIGMAP_LIST)))); ConfigMapConfigProperties configMapConfigProperties = new ConfigMapConfigProperties(true, List.of(), List.of(), Map.of(), true, "bootstrap-640", null, false, false, false, RetryProperties.DEFAULT); assertThatThrownBy(() -> new KubernetesClientConfigMapPropertySourceLocator(api, configMapConfigProperties, - new KubernetesNamespaceProvider(new MockEnvironment())).locate(ENV)) - .isInstanceOf(NamespaceResolutionFailedException.class); + new KubernetesNamespaceProvider(new MockEnvironment())) + .locate(ENV)).isInstanceOf(NamespaceResolutionFailedException.class); } /** @@ -156,19 +159,19 @@ void testLocateWithoutNamespaceConstructor() { void testLocateWithoutNamespace() { CoreV1Api api = new CoreV1Api(); stubFor(get("/api/v1/namespaces/default/configmaps") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(PROPERTIES_CONFIGMAP_LIST)))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(PROPERTIES_CONFIGMAP_LIST)))); ConfigMapConfigProperties configMapConfigProperties = new ConfigMapConfigProperties(true, List.of(), List.of(), Map.of(), true, "bootstrap-640", null, false, false, false, RetryProperties.DEFAULT); assertThatThrownBy(() -> new KubernetesClientConfigMapPropertySourceLocator(api, configMapConfigProperties, - new KubernetesNamespaceProvider(ENV)).locate(ENV)) - .isInstanceOf(NamespaceResolutionFailedException.class); + new KubernetesNamespaceProvider(ENV)) + .locate(ENV)).isInstanceOf(NamespaceResolutionFailedException.class); } @Test public void locateShouldThrowExceptionOnFailureWhenFailFastIsEnabled() { CoreV1Api api = new CoreV1Api(); stubFor(get("/api/v1/namespaces/default/configmaps") - .willReturn(aResponse().withStatus(500).withBody("Internal Server Error"))); + .willReturn(aResponse().withStatus(500).withBody("Internal Server Error"))); ConfigMapConfigProperties configMapConfigProperties = new ConfigMapConfigProperties(true, List.of(), List.of(), Map.of(), true, "bootstrap-640", "default", false, false, true, RetryProperties.DEFAULT); @@ -177,14 +180,14 @@ public void locateShouldThrowExceptionOnFailureWhenFailFastIsEnabled() { configMapConfigProperties, new KubernetesNamespaceProvider(new MockEnvironment())); assertThatThrownBy(() -> locator.locate(new MockEnvironment())).isInstanceOf(IllegalStateException.class) - .hasMessage("Internal Server Error"); + .hasMessage("Internal Server Error"); } @Test public void locateShouldNotThrowExceptionOnFailureWhenFailFastIsDisabled() { CoreV1Api api = new CoreV1Api(); stubFor(get("/api/v1/namespaces/default/configmaps") - .willReturn(aResponse().withStatus(500).withBody("Internal Server Error"))); + .willReturn(aResponse().withStatus(500).withBody("Internal Server Error"))); ConfigMapConfigProperties configMapConfigProperties = new ConfigMapConfigProperties(true, List.of(), List.of(), Map.of(), true, "bootstrap-640", "default", false, false, false, RetryProperties.DEFAULT); diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigMapPropertySourceTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigMapPropertySourceTests.java index 95abc2dcfa..e5eb152a61 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigMapPropertySourceTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigMapPropertySourceTests.java @@ -54,22 +54,24 @@ class KubernetesClientConfigMapPropertySourceTests { private static final V1ConfigMapList PROPERTIES_CONFIGMAP_LIST = new V1ConfigMapList() - .addItemsItem( - new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("bootstrap-640").withNamespace("default") - .withResourceVersion("1").build()) - .addToData("application.properties", - "spring.cloud.kubernetes.configuration.watcher.refreshDelay=0\n" - + "logging.level.org.springframework.cloud.kubernetes=TRACE") - .build()); + .addItemsItem(new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("bootstrap-640") + .withNamespace("default") + .withResourceVersion("1") + .build()) + .addToData("application.properties", + "spring.cloud.kubernetes.configuration.watcher.refreshDelay=0\n" + + "logging.level.org.springframework.cloud.kubernetes=TRACE") + .build()); private static final V1ConfigMapList YAML_CONFIGMAP_LIST = new V1ConfigMapList() - .addItemsItem(new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("bootstrap-641").withNamespace("default") - .withResourceVersion("1").build()) - .addToData("application.yaml", - "dummy:\n property:\n string2: \"a\"\n int2: 1\n bool2: true\n") - .build()); + .addItemsItem(new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("bootstrap-641") + .withNamespace("default") + .withResourceVersion("1") + .build()) + .addToData("application.yaml", "dummy:\n property:\n string2: \"a\"\n int2: 1\n bool2: true\n") + .build()); private static WireMockServer wireMockServer; @@ -100,7 +102,7 @@ public void afterEach() { public void propertiesFile() { CoreV1Api api = new CoreV1Api(); stubFor(get("/api/v1/namespaces/default/configmaps") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(PROPERTIES_CONFIGMAP_LIST)))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(PROPERTIES_CONFIGMAP_LIST)))); NormalizedSource source = new NamedConfigMapNormalizedSource("bootstrap-640", "default", false, true); KubernetesClientConfigContext context = new KubernetesClientConfigContext(api, source, "default", @@ -109,9 +111,9 @@ public void propertiesFile() { verify(getRequestedFor(urlEqualTo("/api/v1/namespaces/default/configmaps"))); assertThat(propertySource.containsProperty("spring.cloud.kubernetes.configuration.watcher.refreshDelay")) - .isTrue(); + .isTrue(); assertThat(propertySource.getProperty("spring.cloud.kubernetes.configuration.watcher.refreshDelay")) - .isEqualTo("0"); + .isEqualTo("0"); assertThat(propertySource.containsProperty("logging.level.org.springframework.cloud.kubernetes")).isTrue(); assertThat(propertySource.getProperty("logging.level.org.springframework.cloud.kubernetes")).isEqualTo("TRACE"); @@ -121,7 +123,7 @@ public void propertiesFile() { public void yamlFile() { CoreV1Api api = new CoreV1Api(); stubFor(get("/api/v1/namespaces/default/configmaps") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(YAML_CONFIGMAP_LIST)))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(YAML_CONFIGMAP_LIST)))); NormalizedSource source = new NamedConfigMapNormalizedSource("bootstrap-641", "default", false, true); KubernetesClientConfigContext context = new KubernetesClientConfigContext(api, source, "default", @@ -142,7 +144,7 @@ public void yamlFile() { public void propertiesFileWithPrefix() { CoreV1Api api = new CoreV1Api(); stubFor(get("/api/v1/namespaces/default/configmaps") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(PROPERTIES_CONFIGMAP_LIST)))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(PROPERTIES_CONFIGMAP_LIST)))); ConfigUtils.Prefix prefix = ConfigUtils.findPrefix("prefix", false, false, null); NormalizedSource source = new NamedConfigMapNormalizedSource("bootstrap-640", "default", false, prefix, true); @@ -152,13 +154,13 @@ public void propertiesFileWithPrefix() { verify(getRequestedFor(urlEqualTo("/api/v1/namespaces/default/configmaps"))); assertThat(propertySource.containsProperty("prefix.spring.cloud.kubernetes.configuration.watcher.refreshDelay")) - .isTrue(); + .isTrue(); assertThat(propertySource.getProperty("prefix.spring.cloud.kubernetes.configuration.watcher.refreshDelay")) - .isEqualTo("0"); + .isEqualTo("0"); assertThat(propertySource.containsProperty("prefix.logging.level.org.springframework.cloud.kubernetes")) - .isTrue(); + .isTrue(); assertThat(propertySource.getProperty("prefix.logging.level.org.springframework.cloud.kubernetes")) - .isEqualTo("TRACE"); + .isEqualTo("TRACE"); } @Test @@ -175,7 +177,7 @@ void constructorWithNamespaceMustNotFail() { @Test public void constructorShouldThrowExceptionOnFailureWhenFailFastIsEnabled() { stubFor(get("/api/v1/namespaces/default/configmaps") - .willReturn(aResponse().withStatus(500).withBody("Internal Server Error"))); + .willReturn(aResponse().withStatus(500).withBody("Internal Server Error"))); ConfigUtils.Prefix prefix = ConfigUtils.findPrefix("prefix", false, false, null); NormalizedSource source = new NamedConfigMapNormalizedSource("my-config", "default", true, prefix, true); @@ -183,14 +185,15 @@ public void constructorShouldThrowExceptionOnFailureWhenFailFastIsEnabled() { new MockEnvironment()); assertThatThrownBy(() -> new KubernetesClientConfigMapPropertySource(context)) - .isInstanceOf(IllegalStateException.class).hasMessage("Internal Server Error"); + .isInstanceOf(IllegalStateException.class) + .hasMessage("Internal Server Error"); verify(getRequestedFor(urlEqualTo("/api/v1/namespaces/default/configmaps"))); } @Test public void constructorShouldNotThrowExceptionOnFailureWhenFailFastIsDisabled() { stubFor(get("/api/v1/namespaces/default/configmaps") - .willReturn(aResponse().withStatus(500).withBody("Internal Server Error"))); + .willReturn(aResponse().withStatus(500).withBody("Internal Server Error"))); ConfigUtils.Prefix prefix = ConfigUtils.findPrefix("prefix", false, false, null); NormalizedSource source = new NamedConfigMapNormalizedSource("my-config", "default", false, prefix, true); diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigReloadAutoConfigurationTest.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigReloadAutoConfigurationTest.java index 3e017b2080..f0bfc7fafb 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigReloadAutoConfigurationTest.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigReloadAutoConfigurationTest.java @@ -89,7 +89,9 @@ protected void setup(String... env) { ConfigurationPropertiesBindingPostProcessor.class, ConfigReloadPropertiesAutoConfiguration.class, ConfigurationPropertiesRebinderAutoConfiguration.class, KubernetesClientBootstrapConfiguration.class, KubernetesBootstrapConfiguration.class, KubernetesClientConfigReloadAutoConfiguration.class) - .web(org.springframework.boot.WebApplicationType.NONE).properties(envArray).run(); + .web(org.springframework.boot.WebApplicationType.NONE) + .properties(envArray) + .run(); } @BeforeAll @@ -111,10 +113,11 @@ void afterEach() { void beforeEach() { V1ConfigMapList TEST_CONFIGMAP = new V1ConfigMapList().addItemsItem(new V1ConfigMapBuilder().withMetadata( new V1ObjectMetaBuilder().withName("test-cm").withNamespace("default").withResourceVersion("1").build()) - .addToData("app.name", "test").build()); + .addToData("app.name", "test") + .build()); WireMock.stubFor(get(urlMatching("^/api/v1/namespaces/default/configmaps.*")) - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(TEST_CONFIGMAP)))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(TEST_CONFIGMAP)))); } // 1. watchers @@ -174,8 +177,11 @@ void reloadEventEnabledMonitoringConfigMapsEnabledByDefault() { setup("spring.cloud.kubernetes.reload.enabled=true", "spring.main.cloud-platform=KUBERNETES"); Map map = context.getBeansOfType(ConfigurationChangeDetector.class); Assertions.assertEquals(map.size(), 1); - Assertions.assertTrue(map.values().iterator().next().getClass() - .isAssignableFrom(KubernetesClientEventBasedConfigMapChangeDetector.class)); + Assertions.assertTrue(map.values() + .iterator() + .next() + .getClass() + .isAssignableFrom(KubernetesClientEventBasedConfigMapChangeDetector.class)); } /** @@ -195,8 +201,11 @@ void reloadEventEnabledMonitoringConfigMapsEnabled() { "spring.main.cloud-platform=KUBERNETES"); Map map = context.getBeansOfType(ConfigurationChangeDetector.class); Assertions.assertEquals(map.size(), 1); - Assertions.assertTrue(map.values().iterator().next().getClass() - .isAssignableFrom(KubernetesClientEventBasedConfigMapChangeDetector.class)); + Assertions.assertTrue(map.values() + .iterator() + .next() + .getClass() + .isAssignableFrom(KubernetesClientEventBasedConfigMapChangeDetector.class)); } /** @@ -278,8 +287,11 @@ void reloadEventEnabledMonitoringConfigMapsDisabledMonitoringSecretsEnabled() { "spring.cloud.kubernetes.reload.mode=event"); Map map = context.getBeansOfType(ConfigurationChangeDetector.class); Assertions.assertEquals(map.size(), 1); - Assertions.assertTrue(map.values().iterator().next().getClass() - .isAssignableFrom(KubernetesClientEventBasedSecretsChangeDetector.class)); + Assertions.assertTrue(map.values() + .iterator() + .next() + .getClass() + .isAssignableFrom(KubernetesClientEventBasedSecretsChangeDetector.class)); } /** @@ -302,8 +314,8 @@ void reloadPollingEnabledMonitoringConfigMapsDisabledMonitoringSecretsEnabled() "spring.cloud.kubernetes.reload.mode=polling"); Map map = context.getBeansOfType(ConfigurationChangeDetector.class); Assertions.assertEquals(map.size(), 1); - Assertions.assertTrue( - map.values().iterator().next().getClass().isAssignableFrom(PollingSecretsChangeDetector.class)); + Assertions + .assertTrue(map.values().iterator().next().getClass().isAssignableFrom(PollingSecretsChangeDetector.class)); } /** @@ -326,8 +338,10 @@ void reloadEventEnabledMonitoringConfigMapsEnabledMonitoringSecretsEnabled() { "spring.cloud.kubernetes.reload.mode=event"); Map map = context.getBeansOfType(ConfigurationChangeDetector.class); Assertions.assertEquals(map.size(), 2); - List result = map.values().stream() - .sorted(Comparator.comparing(x -> x.getClass().getName())).toList(); + List result = map.values() + .stream() + .sorted(Comparator.comparing(x -> x.getClass().getName())) + .toList(); Assertions.assertEquals(result.get(0).getClass(), KubernetesClientEventBasedConfigMapChangeDetector.class); Assertions.assertEquals(result.get(1).getClass(), KubernetesClientEventBasedSecretsChangeDetector.class); } @@ -352,8 +366,10 @@ void reloadPollingEnabledMonitoringConfigMapsEnabledMonitoringSecretsEnabled() { "spring.cloud.kubernetes.reload.mode=polling"); Map map = context.getBeansOfType(ConfigurationChangeDetector.class); Assertions.assertEquals(map.size(), 2); - List result = map.values().stream() - .sorted(Comparator.comparing(x -> x.getClass().getName())).toList(); + List result = map.values() + .stream() + .sorted(Comparator.comparing(x -> x.getClass().getName())) + .toList(); Assertions.assertEquals(result.get(0).getClass(), PollingConfigMapChangeDetector.class); Assertions.assertEquals(result.get(1).getClass(), PollingSecretsChangeDetector.class); } @@ -419,8 +435,10 @@ void reloadEventEnabledMonitoringConfigMapsEnabledMonitoringSecretsDisabled() { "spring.cloud.kubernetes.reload.monitoring-secrets=false"); Map map = context.getBeansOfType(ConfigurationChangeDetector.class); Assertions.assertEquals(map.size(), 1); - List result = map.values().stream() - .sorted(Comparator.comparing(x -> x.getClass().getName())).toList(); + List result = map.values() + .stream() + .sorted(Comparator.comparing(x -> x.getClass().getName())) + .toList(); Assertions.assertEquals(result.get(0).getClass(), KubernetesClientEventBasedConfigMapChangeDetector.class); } @@ -443,8 +461,10 @@ void reloadPollingEnabledMonitoringConfigMapsEnabledMonitoringSecretsDisabled() "spring.cloud.kubernetes.reload.monitoring-secrets=false"); Map map = context.getBeansOfType(ConfigurationChangeDetector.class); Assertions.assertEquals(map.size(), 1); - List result = map.values().stream() - .sorted(Comparator.comparing(x -> x.getClass().getName())).toList(); + List result = map.values() + .stream() + .sorted(Comparator.comparing(x -> x.getClass().getName())) + .toList(); Assertions.assertEquals(result.get(0).getClass(), PollingConfigMapChangeDetector.class); } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigUtilsTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigUtilsTests.java index f874bad16c..b2cdfee6e9 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigUtilsTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigUtilsTests.java @@ -37,7 +37,7 @@ void testNamespacesFromProperties() { ConfigReloadProperties.ReloadStrategy.REFRESH, ConfigReloadProperties.ReloadDetectionMode.EVENT, Duration.ofMillis(15000), Set.of("non-default"), false, Duration.ofSeconds(2)); Set namespaces = KubernetesClientConfigUtils - .namespaces(new KubernetesNamespaceProvider(new MockEnvironment()), properties, "configmap"); + .namespaces(new KubernetesNamespaceProvider(new MockEnvironment()), properties, "configmap"); Assertions.assertEquals(1, namespaces.size()); Assertions.assertEquals(namespaces.iterator().next(), "non-default"); } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientSecretsPropertySourceLocatorTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientSecretsPropertySourceLocatorTests.java index 841dfa79f1..b9ecb61cc0 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientSecretsPropertySourceLocatorTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientSecretsPropertySourceLocatorTests.java @@ -118,7 +118,8 @@ void getLocateWithSources() { List.of(source1, source2), true, "app", "default", false, true, false, RetryProperties.DEFAULT); PropertySource propertySource = new KubernetesClientSecretsPropertySourceLocator(api, - new KubernetesNamespaceProvider(new MockEnvironment()), secretsConfigProperties).locate(ENV); + new KubernetesNamespaceProvider(new MockEnvironment()), secretsConfigProperties) + .locate(ENV); assertThat(propertySource.containsProperty("password")).isTrue(); assertThat(propertySource.getProperty("password")).isEqualTo("p455w0rd"); } @@ -131,7 +132,8 @@ void getLocateWithOutSources() { List.of(), true, "db-secret", "default", false, true, false, RetryProperties.DEFAULT); PropertySource propertySource = new KubernetesClientSecretsPropertySourceLocator(api, - new KubernetesNamespaceProvider(new MockEnvironment()), secretsConfigProperties).locate(ENV); + new KubernetesNamespaceProvider(new MockEnvironment()), secretsConfigProperties) + .locate(ENV); assertThat(propertySource.containsProperty("password")).isTrue(); assertThat(propertySource.getProperty("password")).isEqualTo("p455w0rd"); } @@ -152,8 +154,8 @@ void testLocateWithoutNamespaceConstructor() { List.of(), true, "db-secret", "", false, true, false, RetryProperties.DEFAULT); assertThatThrownBy(() -> new KubernetesClientSecretsPropertySourceLocator(api, - new KubernetesNamespaceProvider(new MockEnvironment()), secretsConfigProperties).locate(ENV)) - .isInstanceOf(NamespaceResolutionFailedException.class); + new KubernetesNamespaceProvider(new MockEnvironment()), secretsConfigProperties) + .locate(ENV)).isInstanceOf(NamespaceResolutionFailedException.class); } @Test @@ -168,7 +170,7 @@ void locateShouldThrowExceptionOnFailureWhenFailFastIsEnabled() { new KubernetesNamespaceProvider(new MockEnvironment()), secretsConfigProperties); assertThatThrownBy(() -> locator.locate(new MockEnvironment())).isInstanceOf(IllegalStateException.class) - .hasMessage("Internal Server Error"); + .hasMessage("Internal Server Error"); } @Test diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientSecretsPropertySourceTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientSecretsPropertySourceTests.java index d3ebd5ad29..4cc2b8d231 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientSecretsPropertySourceTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientSecretsPropertySourceTests.java @@ -59,15 +59,24 @@ class KubernetesClientSecretsPropertySourceTests { private static final String API = "/api/v1/namespaces/default/secrets"; - private static final V1SecretList SECRET_LIST = new V1SecretListBuilder().addToItems(new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("db-secret").withResourceVersion("0") - .withNamespace("default").build()) - .addToData("password", "p455w0rd".getBytes()).addToData("username", "user".getBytes()).build()).build(); + private static final V1SecretList SECRET_LIST = new V1SecretListBuilder() + .addToItems( + new V1SecretBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("db-secret") + .withResourceVersion("0") + .withNamespace("default") + .build()) + .addToData("password", "p455w0rd".getBytes()) + .addToData("username", "user".getBytes()) + .build()) + .build(); private static final V1SecretList EMPTY_DATA_SECRET_LIST = new V1SecretListBuilder() - .addToItems(new V1SecretBuilder().withMetadata(new V1ObjectMetaBuilder().withName("db-secret") - .withResourceVersion("0").withNamespace("default").build()).build()) - .build(); + .addToItems(new V1SecretBuilder().withMetadata(new V1ObjectMetaBuilder().withName("db-secret") + .withResourceVersion("0") + .withNamespace("default") + .build()).build()) + .build(); private static final String LIST_API_WITH_LABEL = "/api/v1/namespaces/default/secrets"; @@ -124,7 +133,7 @@ void afterEach() { void emptyDataSecretTest() { CoreV1Api api = new CoreV1Api(); stubFor(get(API) - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(EMPTY_DATA_SECRET_LIST)))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(EMPTY_DATA_SECRET_LIST)))); NormalizedSource source = new NamedSecretNormalizedSource("db-secret", "default", false, false); KubernetesClientConfigContext context = new KubernetesClientConfigContext(api, source, "default", @@ -177,7 +186,8 @@ void constructorShouldThrowExceptionOnFailureWhenFailFastIsEnabled() { new MockEnvironment()); assertThatThrownBy(() -> new KubernetesClientSecretsPropertySource(context)) - .isInstanceOf(IllegalStateException.class).hasMessage("Internal Server Error"); + .isInstanceOf(IllegalStateException.class) + .hasMessage("Internal Server Error"); verify(getRequestedFor(urlEqualTo(API))); } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/LabeledConfigMapContextToSourceDataProviderTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/LabeledConfigMapContextToSourceDataProviderTests.java index 653755b400..44840858e0 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/LabeledConfigMapContextToSourceDataProviderTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/LabeledConfigMapContextToSourceDataProviderTests.java @@ -97,8 +97,13 @@ void afterEach() { @Test void singleConfigMapMatchAgainstLabels() { - V1ConfigMap one = new V1ConfigMapBuilder().withMetadata(new V1ObjectMetaBuilder().withName("test-configmap") - .withLabels(LABELS).withNamespace(NAMESPACE).build()).addToData("name", "value").build(); + V1ConfigMap one = new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("test-configmap") + .withLabels(LABELS) + .withNamespace(NAMESPACE) + .build()) + .addToData("name", "value") + .build(); V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(one); stubCall(configMapList); @@ -123,18 +128,33 @@ void singleConfigMapMatchAgainstLabels() { @Test void twoConfigMapsMatchAgainstLabels() { - V1ConfigMap redOne = new V1ConfigMapBuilder().withMetadata(new V1ObjectMetaBuilder().withName("red-configmap") - .withLabels(RED_LABEL).withNamespace(NAMESPACE).build()).addToData("colorOne", "really-red").build(); - - V1ConfigMap redTwo = new V1ConfigMapBuilder().withMetadata(new V1ObjectMetaBuilder() - .withName("red-configmap-again").withLabels(RED_LABEL).withNamespace(NAMESPACE).build()) - .addToData("colorTwo", "really-red-again").build(); - - V1ConfigMap blue = new V1ConfigMapBuilder().withMetadata(new V1ObjectMetaBuilder().withName("blue-configmap") - .withLabels(BLUE_LABEL).withNamespace(NAMESPACE).build()).addToData("color", "blue").build(); - - V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(redOne).addItemsItem(redTwo) - .addItemsItem(blue); + V1ConfigMap redOne = new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("red-configmap") + .withLabels(RED_LABEL) + .withNamespace(NAMESPACE) + .build()) + .addToData("colorOne", "really-red") + .build(); + + V1ConfigMap redTwo = new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("red-configmap-again") + .withLabels(RED_LABEL) + .withNamespace(NAMESPACE) + .build()) + .addToData("colorTwo", "really-red-again") + .build(); + + V1ConfigMap blue = new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("blue-configmap") + .withLabels(BLUE_LABEL) + .withNamespace(NAMESPACE) + .build()) + .addToData("color", "blue") + .build(); + + V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(redOne) + .addItemsItem(redTwo) + .addItemsItem(blue); stubCall(configMapList); CoreV1Api api = new CoreV1Api(); @@ -159,8 +179,13 @@ void twoConfigMapsMatchAgainstLabels() { @Test void configMapNoMatch() { - V1ConfigMap one = new V1ConfigMapBuilder().withMetadata(new V1ObjectMetaBuilder().withName("pink-configmap") - .withLabels(PINK_LABEL).withNamespace(NAMESPACE).build()).addToData("color", "pink").build(); + V1ConfigMap one = new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("pink-configmap") + .withLabels(PINK_LABEL) + .withNamespace(NAMESPACE) + .build()) + .addToData("color", "pink") + .build(); V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(one); stubCall(configMapList); @@ -186,8 +211,13 @@ void configMapNoMatch() { */ @Test void namespaceMatch() { - V1ConfigMap one = new V1ConfigMapBuilder().withMetadata(new V1ObjectMetaBuilder().withName("test-configmap") - .withLabels(LABELS).withNamespace(NAMESPACE).build()).addToData("name", "value").build(); + V1ConfigMap one = new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("test-configmap") + .withLabels(LABELS) + .withNamespace(NAMESPACE) + .build()) + .addToData("name", "value") + .build(); V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(one); stubCall(configMapList); @@ -213,8 +243,13 @@ void namespaceMatch() { */ @Test void testWithPrefix() { - V1ConfigMap one = new V1ConfigMapBuilder().withMetadata(new V1ObjectMetaBuilder().withName("blue-configmap") - .withLabels(BLUE_LABEL).withNamespace(NAMESPACE).build()).addToData("what-color", "blue-color").build(); + V1ConfigMap one = new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("blue-configmap") + .withLabels(BLUE_LABEL) + .withNamespace(NAMESPACE) + .build()) + .addToData("what-color", "blue-color") + .build(); V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(one); stubCall(configMapList); @@ -245,12 +280,21 @@ void testWithPrefix() { @Test void testTwoConfigmapsWithPrefix() { - V1ConfigMap one = new V1ConfigMapBuilder().withMetadata(new V1ObjectMetaBuilder().withName("blue-configmap") - .withLabels(BLUE_LABEL).withNamespace(NAMESPACE).build()).addToData("first", "blue").build(); + V1ConfigMap one = new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("blue-configmap") + .withLabels(BLUE_LABEL) + .withNamespace(NAMESPACE) + .build()) + .addToData("first", "blue") + .build(); - V1ConfigMap two = new V1ConfigMapBuilder().withMetadata(new V1ObjectMetaBuilder() - .withName("another-blue-configmap").withLabels(BLUE_LABEL).withNamespace(NAMESPACE).build()) - .addToData("second", "blue").build(); + V1ConfigMap two = new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("another-blue-configmap") + .withLabels(BLUE_LABEL) + .withNamespace(NAMESPACE) + .build()) + .addToData("second", "blue") + .build(); V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(one).addItemsItem(two); @@ -291,12 +335,18 @@ void testTwoConfigmapsWithPrefix() { @Test void searchWithLabelsNoConfigmapsFound() { - V1ConfigMap one = new V1ConfigMapBuilder().withMetadata(new V1ObjectMetaBuilder().withName("color-configmap") - .withLabels(BLUE_LABEL).withNamespace(NAMESPACE).build()).addToData("one", "1").build(); + V1ConfigMap one = new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("color-configmap") + .withLabels(BLUE_LABEL) + .withNamespace(NAMESPACE) + .build()) + .addToData("one", "1") + .build(); V1ConfigMap two = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("color-config-k8s").withNamespace(NAMESPACE).build()) - .addToData("two", "2").build(); + .withMetadata(new V1ObjectMetaBuilder().withName("color-config-k8s").withNamespace(NAMESPACE).build()) + .addToData("two", "2") + .build(); V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(one).addItemsItem(two); @@ -324,12 +374,18 @@ void searchWithLabelsNoConfigmapsFound() { @Test void searchWithLabelsOneConfigMapFound() { - V1ConfigMap one = new V1ConfigMapBuilder().withMetadata(new V1ObjectMetaBuilder().withName("color-configmap") - .withLabels(BLUE_LABEL).withNamespace(NAMESPACE).build()).addToData("one", "1").build(); + V1ConfigMap one = new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("color-configmap") + .withLabels(BLUE_LABEL) + .withNamespace(NAMESPACE) + .build()) + .addToData("one", "1") + .build(); V1ConfigMap two = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("shape-configmap").withNamespace(NAMESPACE).build()) - .addToData("two", "2").build(); + .withMetadata(new V1ObjectMetaBuilder().withName("shape-configmap").withNamespace(NAMESPACE).build()) + .addToData("two", "2") + .build(); V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(one).addItemsItem(two); @@ -359,12 +415,21 @@ void searchWithLabelsOneConfigMapFound() { @Test void searchWithLabelsOneConfigMapFoundAndOneFromProfileFound() { - V1ConfigMap one = new V1ConfigMapBuilder().withMetadata(new V1ObjectMetaBuilder().withName("color-configmap") - .withLabels(BLUE_LABEL).withNamespace(NAMESPACE).build()).addToData("one", "1").build(); + V1ConfigMap one = new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("color-configmap") + .withLabels(BLUE_LABEL) + .withNamespace(NAMESPACE) + .build()) + .addToData("one", "1") + .build(); - V1ConfigMap two = new V1ConfigMapBuilder().withMetadata(new V1ObjectMetaBuilder() - .withName("color-configmap-k8s").withLabels(RED_LABEL).withNamespace(NAMESPACE).build()) - .addToData("two", "2").build(); + V1ConfigMap two = new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("color-configmap-k8s") + .withLabels(RED_LABEL) + .withNamespace(NAMESPACE) + .build()) + .addToData("two", "2") + .build(); V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(one).addItemsItem(two); @@ -399,29 +464,51 @@ void searchWithLabelsOneConfigMapFoundAndOneFromProfileFound() { @Test void searchWithLabelsTwoConfigMapsFoundAndOneFromProfileFound() { - V1ConfigMap colorConfigMap = new V1ConfigMapBuilder().withMetadata(new V1ObjectMetaBuilder() - .withName("color-configmap").withLabels(BLUE_LABEL).withNamespace(NAMESPACE).build()) - .addToData("one", "1").build(); + V1ConfigMap colorConfigMap = new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("color-configmap") + .withLabels(BLUE_LABEL) + .withNamespace(NAMESPACE) + .build()) + .addToData("one", "1") + .build(); V1ConfigMap shapeConfigmap = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("shape-configmap") - .withLabels(Map.of("color", "blue", "shape", "round")).withNamespace(NAMESPACE).build()) - .addToData("two", "2").build(); - - V1ConfigMap noFit = new V1ConfigMapBuilder().withMetadata(new V1ObjectMetaBuilder().withName("no-fit") - .withLabels(Map.of("tag", "no-fit")).withNamespace(NAMESPACE).build()).addToData("three", "3").build(); - - V1ConfigMap colorConfigmapK8s = new V1ConfigMapBuilder().withMetadata(new V1ObjectMetaBuilder() - .withName("color-configmap-k8s").withLabels(RED_LABEL).withNamespace(NAMESPACE).build()) - .addToData("four", "4").build(); + .withMetadata(new V1ObjectMetaBuilder().withName("shape-configmap") + .withLabels(Map.of("color", "blue", "shape", "round")) + .withNamespace(NAMESPACE) + .build()) + .addToData("two", "2") + .build(); + + V1ConfigMap noFit = new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("no-fit") + .withLabels(Map.of("tag", "no-fit")) + .withNamespace(NAMESPACE) + .build()) + .addToData("three", "3") + .build(); + + V1ConfigMap colorConfigmapK8s = new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("color-configmap-k8s") + .withLabels(RED_LABEL) + .withNamespace(NAMESPACE) + .build()) + .addToData("four", "4") + .build(); V1ConfigMap shapeConfigmapK8s = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("shape-configmap-k8s") - .withLabels(Map.of("shape", "triangle")).withNamespace(NAMESPACE).build()) - .addToData("five", "5").build(); - - V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(colorConfigMap).addItemsItem(shapeConfigmap) - .addItemsItem(noFit).addItemsItem(colorConfigmapK8s).addItemsItem(shapeConfigmapK8s); + .withMetadata(new V1ObjectMetaBuilder().withName("shape-configmap-k8s") + .withLabels(Map.of("shape", "triangle")) + .withNamespace(NAMESPACE) + .build()) + .addToData("five", "5") + .build(); + + V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(colorConfigMap) + .addItemsItem(shapeConfigmap) + .addItemsItem(noFit) + .addItemsItem(colorConfigmapK8s) + .addItemsItem(shapeConfigmapK8s); stubCall(configMapList); CoreV1Api api = new CoreV1Api(); @@ -437,13 +524,13 @@ void searchWithLabelsTwoConfigMapsFoundAndOneFromProfileFound() { Assertions.assertEquals(sourceData.sourceData().size(), 4); Assertions.assertEquals(sourceData.sourceData() - .get("color-configmap.color-configmap-k8s.shape-configmap.shape-configmap-k8s.one"), "1"); + .get("color-configmap.color-configmap-k8s.shape-configmap.shape-configmap-k8s.one"), "1"); Assertions.assertEquals(sourceData.sourceData() - .get("color-configmap.color-configmap-k8s.shape-configmap.shape-configmap-k8s.two"), "2"); + .get("color-configmap.color-configmap-k8s.shape-configmap.shape-configmap-k8s.two"), "2"); Assertions.assertEquals(sourceData.sourceData() - .get("color-configmap.color-configmap-k8s.shape-configmap.shape-configmap-k8s.four"), "4"); + .get("color-configmap.color-configmap-k8s.shape-configmap.shape-configmap-k8s.four"), "4"); Assertions.assertEquals(sourceData.sourceData() - .get("color-configmap.color-configmap-k8s.shape-configmap.shape-configmap-k8s.five"), "5"); + .get("color-configmap.color-configmap-k8s.shape-configmap.shape-configmap-k8s.five"), "5"); Assertions.assertEquals(sourceData.sourceName(), "configmap.color-configmap.color-configmap-k8s.shape-configmap.shape-configmap-k8s.default"); @@ -461,13 +548,21 @@ void searchWithLabelsTwoConfigMapsFoundAndOneFromProfileFound() { */ @Test void cache(CapturedOutput output) { - V1ConfigMap red = new V1ConfigMapBuilder().withMetadata(new V1ObjectMetaBuilder() - .withLabels(Map.of("color", "red")).withNamespace(NAMESPACE).withName("red-configmap").build()) - .addToData("color", "red").build(); - - V1ConfigMap green = new V1ConfigMapBuilder().withMetadata(new V1ObjectMetaBuilder() - .withLabels(Map.of("color", "green")).withNamespace(NAMESPACE).withName("green-configmap").build()) - .addToData("color", "green").build(); + V1ConfigMap red = new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("color", "red")) + .withNamespace(NAMESPACE) + .withName("red-configmap") + .build()) + .addToData("color", "red") + .build(); + + V1ConfigMap green = new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("color", "green")) + .withNamespace(NAMESPACE) + .withName("green-configmap") + .build()) + .addToData("color", "green") + .build(); V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(red).addItemsItem(green); @@ -508,7 +603,7 @@ void cache(CapturedOutput output) { private void stubCall(V1ConfigMapList list) { stubFor(get("/api/v1/namespaces/default/configmaps") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(list)))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(list)))); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/LabeledSecretContextToSourceDataProviderTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/LabeledSecretContextToSourceDataProviderTests.java index 804afeee3d..9a666509ce 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/LabeledSecretContextToSourceDataProviderTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/LabeledSecretContextToSourceDataProviderTests.java @@ -94,9 +94,12 @@ void afterEach() { void noMatch() { V1Secret red = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withLabels(Collections.singletonMap("color", "red")) - .withNamespace(NAMESPACE).withName("red-secret").build()) - .addToData("color", Base64.getEncoder().encode("really-red".getBytes())).build(); + .withMetadata(new V1ObjectMetaBuilder().withLabels(Collections.singletonMap("color", "red")) + .withNamespace(NAMESPACE) + .withName("red-secret") + .build()) + .addToData("color", Base64.getEncoder().encode("really-red".getBytes())) + .build(); V1SecretList secretList = new V1SecretList().addItemsItem(red); stubCall(secretList); @@ -125,7 +128,8 @@ void singleSecretMatchAgainstLabels() { V1Secret red = new V1SecretBuilder().withMetadata( new V1ObjectMetaBuilder().withLabels(LABELS).withNamespace(NAMESPACE).withName("test-secret").build()) - .addToData("color", "really-red".getBytes()).build(); + .addToData("color", "really-red".getBytes()) + .build(); V1SecretList secretList = new V1SecretList().addItemsItem(red); stubCall(secretList); @@ -151,11 +155,13 @@ void twoSecretsMatchAgainstLabels() { V1Secret one = new V1SecretBuilder().withMetadata( new V1ObjectMetaBuilder().withLabels(RED_LABEL).withNamespace(NAMESPACE).withName("color-one").build()) - .addToData("colorOne", "really-red-one".getBytes()).build(); + .addToData("colorOne", "really-red-one".getBytes()) + .build(); V1Secret two = new V1SecretBuilder().withMetadata( new V1ObjectMetaBuilder().withLabels(RED_LABEL).withNamespace(NAMESPACE).withName("color-two").build()) - .addToData("colorTwo", "really-red-two".getBytes()).build(); + .addToData("colorTwo", "really-red-two".getBytes()) + .build(); V1SecretList secretList = new V1SecretList().addItemsItem(one).addItemsItem(two); stubCall(secretList); @@ -179,7 +185,8 @@ void twoSecretsMatchAgainstLabels() { void namespaceMatch() { V1Secret one = new V1SecretBuilder().withMetadata( new V1ObjectMetaBuilder().withLabels(LABELS).withNamespace(NAMESPACE).withName("test-secret").build()) - .addToData("color", "really-red".getBytes()).build(); + .addToData("color", "really-red".getBytes()) + .build(); V1SecretList secretList = new V1SecretList().addItemsItem(one); stubCall(secretList); @@ -205,9 +212,13 @@ void namespaceMatch() { @Test void testWithPrefix() { - V1Secret one = new V1SecretBuilder().withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("color", "blue")) - .withNamespace(NAMESPACE).withName("blue-secret").build()) - .addToData("what-color", "blue-color".getBytes()).build(); + V1Secret one = new V1SecretBuilder() + .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("color", "blue")) + .withNamespace(NAMESPACE) + .withName("blue-secret") + .build()) + .addToData("what-color", "blue-color".getBytes()) + .build(); V1SecretList secretList = new V1SecretList().addItemsItem(one); stubCall(secretList); @@ -238,13 +249,21 @@ void testWithPrefix() { @Test void testTwoSecretsWithPrefix() { - V1Secret one = new V1SecretBuilder().withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("color", "blue")) - .withNamespace(NAMESPACE).withName("blue-secret").build()).addToData("first", "blue".getBytes()) - .build(); - - V1Secret two = new V1SecretBuilder().withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("color", "blue")) - .withNamespace(NAMESPACE).withName("another-blue-secret").build()) - .addToData("second", "blue".getBytes()).build(); + V1Secret one = new V1SecretBuilder() + .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("color", "blue")) + .withNamespace(NAMESPACE) + .withName("blue-secret") + .build()) + .addToData("first", "blue".getBytes()) + .build(); + + V1Secret two = new V1SecretBuilder() + .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("color", "blue")) + .withNamespace(NAMESPACE) + .withName("another-blue-secret") + .build()) + .addToData("second", "blue".getBytes()) + .build(); V1SecretList secretList = new V1SecretList().addItemsItem(one).addItemsItem(two); @@ -289,13 +308,21 @@ void testTwoSecretsWithPrefix() { @Test void searchWithLabelsOneSecretFound() { - V1Secret colorSecret = new V1SecretBuilder().withMetadata(new V1ObjectMetaBuilder() - .withLabels(Map.of("color", "blue")).withNamespace(NAMESPACE).withName("color-secret").build()) - .addToData("one", "1".getBytes()).build(); + V1Secret colorSecret = new V1SecretBuilder() + .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("color", "blue")) + .withNamespace(NAMESPACE) + .withName("color-secret") + .build()) + .addToData("one", "1".getBytes()) + .build(); - V1Secret shapeSecret = new V1SecretBuilder().withMetadata(new V1ObjectMetaBuilder() - .withLabels(Map.of("shape", "round")).withNamespace(NAMESPACE).withName("shape-secret").build()) - .addToData("two", "2".getBytes()).build(); + V1Secret shapeSecret = new V1SecretBuilder() + .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("shape", "round")) + .withNamespace(NAMESPACE) + .withName("shape-secret") + .build()) + .addToData("two", "2".getBytes()) + .build(); V1SecretList secretList = new V1SecretList().addItemsItem(colorSecret).addItemsItem(shapeSecret); @@ -325,13 +352,21 @@ void searchWithLabelsOneSecretFound() { @Test void searchWithLabelsOneSecretFoundAndOneFromProfileFound() { - V1Secret colorSecret = new V1SecretBuilder().withMetadata(new V1ObjectMetaBuilder() - .withLabels(Map.of("color", "blue")).withNamespace(NAMESPACE).withName("color-secret").build()) - .addToData("one", "1".getBytes()).build(); + V1Secret colorSecret = new V1SecretBuilder() + .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("color", "blue")) + .withNamespace(NAMESPACE) + .withName("color-secret") + .build()) + .addToData("one", "1".getBytes()) + .build(); - V1Secret shapeSecret = new V1SecretBuilder().withMetadata(new V1ObjectMetaBuilder() - .withLabels(Map.of("color", "red")).withNamespace(NAMESPACE).withName("color-secret-k8s").build()) - .addToData("two", "2".getBytes()).build(); + V1Secret shapeSecret = new V1SecretBuilder() + .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("color", "red")) + .withNamespace(NAMESPACE) + .withName("color-secret-k8s") + .build()) + .addToData("two", "2".getBytes()) + .build(); V1SecretList secretList = new V1SecretList().addItemsItem(colorSecret).addItemsItem(shapeSecret); @@ -366,29 +401,51 @@ void searchWithLabelsOneSecretFoundAndOneFromProfileFound() { @Test void searchWithLabelsTwoSecretsFoundAndOneFromProfileFound() { - V1Secret colorSecret = new V1SecretBuilder().withMetadata(new V1ObjectMetaBuilder() - .withLabels(Map.of("color", "blue")).withNamespace(NAMESPACE).withName("color-secret").build()) - .addToData("one", "1".getBytes()).build(); + V1Secret colorSecret = new V1SecretBuilder() + .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("color", "blue")) + .withNamespace(NAMESPACE) + .withName("color-secret") + .build()) + .addToData("one", "1".getBytes()) + .build(); V1Secret shapeSecret = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("color", "blue", "shape", "round")) - .withNamespace(NAMESPACE).withName("shape-secret").build()) - .addToData("two", "2".getBytes()).build(); - - V1Secret noFit = new V1SecretBuilder().withMetadata(new V1ObjectMetaBuilder() - .withLabels(Map.of("tag", "no-fit")).withNamespace(NAMESPACE).withName("no-fit").build()) - .addToData("three", "3".getBytes()).build(); - - V1Secret colorSecretK8s = new V1SecretBuilder().withMetadata(new V1ObjectMetaBuilder() - .withLabels(Map.of("color", "red")).withNamespace(NAMESPACE).withName("color-secret-k8s").build()) - .addToData("four", "4".getBytes()).build(); - - V1Secret shapeSecretK8s = new V1SecretBuilder().withMetadata(new V1ObjectMetaBuilder() - .withLabels(Map.of("shape", "triangle")).withNamespace(NAMESPACE).withName("shape-secret-k8s").build()) - .addToData("five", "5".getBytes()).build(); - - V1SecretList secretList = new V1SecretList().addItemsItem(colorSecret).addItemsItem(shapeSecret) - .addItemsItem(noFit).addItemsItem(colorSecretK8s).addItemsItem(shapeSecretK8s); + .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("color", "blue", "shape", "round")) + .withNamespace(NAMESPACE) + .withName("shape-secret") + .build()) + .addToData("two", "2".getBytes()) + .build(); + + V1Secret noFit = new V1SecretBuilder() + .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("tag", "no-fit")) + .withNamespace(NAMESPACE) + .withName("no-fit") + .build()) + .addToData("three", "3".getBytes()) + .build(); + + V1Secret colorSecretK8s = new V1SecretBuilder() + .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("color", "red")) + .withNamespace(NAMESPACE) + .withName("color-secret-k8s") + .build()) + .addToData("four", "4".getBytes()) + .build(); + + V1Secret shapeSecretK8s = new V1SecretBuilder() + .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("shape", "triangle")) + .withNamespace(NAMESPACE) + .withName("shape-secret-k8s") + .build()) + .addToData("five", "5".getBytes()) + .build(); + + V1SecretList secretList = new V1SecretList().addItemsItem(colorSecret) + .addItemsItem(shapeSecret) + .addItemsItem(noFit) + .addItemsItem(colorSecretK8s) + .addItemsItem(shapeSecretK8s); stubCall(secretList); CoreV1Api api = new CoreV1Api(); @@ -422,9 +479,13 @@ void searchWithLabelsTwoSecretsFoundAndOneFromProfileFound() { */ @Test void testYaml() { - V1Secret colorSecret = new V1SecretBuilder().withMetadata(new V1ObjectMetaBuilder() - .withLabels(Map.of("color", "blue")).withNamespace(NAMESPACE).withName("color-secret").build()) - .addToData("test.yaml", "color: blue".getBytes()).build(); + V1Secret colorSecret = new V1SecretBuilder() + .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("color", "blue")) + .withNamespace(NAMESPACE) + .withName("color-secret") + .build()) + .addToData("test.yaml", "color: blue".getBytes()) + .build(); V1SecretList secretList = new V1SecretList().addItemsItem(colorSecret); @@ -455,12 +516,21 @@ void testYaml() { */ @Test void cache(CapturedOutput output) { - V1Secret red = new V1SecretBuilder().withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("color", "red")) - .withNamespace(NAMESPACE).withName("red").build()).addToData("color", "red".getBytes()).build(); - - V1Secret green = new V1SecretBuilder().withMetadata(new V1ObjectMetaBuilder() - .withLabels(Map.of("color", "green")).withNamespace(NAMESPACE).withName("green").build()) - .addToData("color", "green".getBytes()).build(); + V1Secret red = new V1SecretBuilder() + .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("color", "red")) + .withNamespace(NAMESPACE) + .withName("red") + .build()) + .addToData("color", "red".getBytes()) + .build(); + + V1Secret green = new V1SecretBuilder() + .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("color", "green")) + .withNamespace(NAMESPACE) + .withName("green") + .build()) + .addToData("color", "green".getBytes()) + .build(); V1SecretList secretList = new V1SecretList().addItemsItem(red).addItemsItem(green); @@ -501,7 +571,7 @@ void cache(CapturedOutput output) { private void stubCall(V1SecretList list) { stubFor(get("/api/v1/namespaces/default/secrets") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(list)))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(list)))); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/NamedConfigMapContextToSourceDataProviderTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/NamedConfigMapContextToSourceDataProviderTests.java index e59684de1d..dcdbda388e 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/NamedConfigMapContextToSourceDataProviderTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/NamedConfigMapContextToSourceDataProviderTests.java @@ -94,8 +94,9 @@ void afterEach() { @Test void noMatch() { V1ConfigMap redConfigMap = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName(RED_CONFIG_MAP_NAME).withNamespace(NAMESPACE).build()) - .addToData(COLOR_REALLY_RED).build(); + .withMetadata(new V1ObjectMetaBuilder().withName(RED_CONFIG_MAP_NAME).withNamespace(NAMESPACE).build()) + .addToData(COLOR_REALLY_RED) + .build(); V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(redConfigMap); stubCall(configMapList); @@ -123,8 +124,9 @@ void noMatch() { void match() { V1ConfigMap configMap = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName(RED_CONFIG_MAP_NAME).withNamespace(NAMESPACE).build()) - .addToData(COLOR_REALLY_RED).build(); + .withMetadata(new V1ObjectMetaBuilder().withName(RED_CONFIG_MAP_NAME).withNamespace(NAMESPACE).build()) + .addToData(COLOR_REALLY_RED) + .build(); V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(configMap); stubCall(configMapList); @@ -153,12 +155,14 @@ void match() { void matchIncludeSingleProfile() { V1ConfigMap red = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName(RED_CONFIG_MAP_NAME).withNamespace(NAMESPACE).build()) - .addToData(COLOR_REALLY_RED).build(); + .withMetadata(new V1ObjectMetaBuilder().withName(RED_CONFIG_MAP_NAME).withNamespace(NAMESPACE).build()) + .addToData(COLOR_REALLY_RED) + .build(); V1ConfigMap redWithProfile = new V1ConfigMapBuilder().withMetadata( new V1ObjectMetaBuilder().withName(RED_WITH_PROFILE_CONFIG_MAP_NAME).withNamespace(NAMESPACE).build()) - .addToData(TASTE_MANGO).build(); + .addToData(TASTE_MANGO) + .build(); V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(red).addItemsItem(redWithProfile); stubCall(configMapList); @@ -193,12 +197,14 @@ void matchIncludeSingleProfile() { void matchIncludeSingleProfileWithPrefix() { V1ConfigMap red = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName(RED_CONFIG_MAP_NAME).withNamespace(NAMESPACE).build()) - .addToData(COLOR_REALLY_RED).build(); + .withMetadata(new V1ObjectMetaBuilder().withName(RED_CONFIG_MAP_NAME).withNamespace(NAMESPACE).build()) + .addToData(COLOR_REALLY_RED) + .build(); V1ConfigMap redWithTaste = new V1ConfigMapBuilder().withMetadata( new V1ObjectMetaBuilder().withName(RED_WITH_PROFILE_CONFIG_MAP_NAME).withNamespace(NAMESPACE).build()) - .addToData(TASTE_MANGO).build(); + .addToData(TASTE_MANGO) + .build(); V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(red).addItemsItem(redWithTaste); stubCall(configMapList); @@ -233,20 +239,28 @@ void matchIncludeSingleProfileWithPrefix() { void matchIncludeTwoProfilesWithPrefix() { V1ConfigMap red = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName(RED_CONFIG_MAP_NAME).withNamespace(NAMESPACE).build()) - .addToData(COLOR_REALLY_RED).build(); + .withMetadata(new V1ObjectMetaBuilder().withName(RED_CONFIG_MAP_NAME).withNamespace(NAMESPACE).build()) + .addToData(COLOR_REALLY_RED) + .build(); V1ConfigMap redWithTaste = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName(RED_CONFIG_MAP_NAME + "-with-taste") - .withNamespace(NAMESPACE).withResourceVersion("1").build()) - .addToData(TASTE_MANGO).build(); - - V1ConfigMap redWithShape = new V1ConfigMapBuilder().withMetadata(new V1ObjectMetaBuilder() - .withName(RED_CONFIG_MAP_NAME + "-with-shape").withNamespace(NAMESPACE).build()) - .addToData("shape", "round").build(); - - V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(red).addItemsItem(redWithTaste) - .addItemsItem(redWithShape); + .withMetadata(new V1ObjectMetaBuilder().withName(RED_CONFIG_MAP_NAME + "-with-taste") + .withNamespace(NAMESPACE) + .withResourceVersion("1") + .build()) + .addToData(TASTE_MANGO) + .build(); + + V1ConfigMap redWithShape = new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName(RED_CONFIG_MAP_NAME + "-with-shape") + .withNamespace(NAMESPACE) + .build()) + .addToData("shape", "round") + .build(); + + V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(red) + .addItemsItem(redWithTaste) + .addItemsItem(redWithShape); stubCall(configMapList); CoreV1Api api = new CoreV1Api(); @@ -279,8 +293,9 @@ void matchIncludeTwoProfilesWithPrefix() { void matchWithName() { V1ConfigMap red = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("application").withNamespace(NAMESPACE).build()) - .addToData("color", "red").build(); + .withMetadata(new V1ObjectMetaBuilder().withName("application").withNamespace(NAMESPACE).build()) + .addToData("color", "red") + .build(); V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(red); stubCall(configMapList); @@ -309,8 +324,9 @@ void matchWithName() { void namespaceMatch() { V1ConfigMap configMap = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName(RED_CONFIG_MAP_NAME).withNamespace(NAMESPACE).build()) - .addToData(COLOR_REALLY_RED).build(); + .withMetadata(new V1ObjectMetaBuilder().withName(RED_CONFIG_MAP_NAME).withNamespace(NAMESPACE).build()) + .addToData(COLOR_REALLY_RED) + .build(); V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(configMap); stubCall(configMapList); @@ -336,8 +352,9 @@ void namespaceMatch() { @Test void testSingleYaml() { V1ConfigMap singleYaml = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName(RED_CONFIG_MAP_NAME).withNamespace(NAMESPACE).build()) - .addToData("single.yaml", "key: value").build(); + .withMetadata(new V1ObjectMetaBuilder().withName(RED_CONFIG_MAP_NAME).withNamespace(NAMESPACE).build()) + .addToData("single.yaml", "key: value") + .build(); V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(singleYaml); stubCall(configMapList); @@ -365,8 +382,9 @@ void testSingleYaml() { @Test void testCorrectNameWithProfile() { V1ConfigMap one = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("one").withNamespace(NAMESPACE).build()) - .addToData("key", "value").build(); + .withMetadata(new V1ObjectMetaBuilder().withName("one").withNamespace(NAMESPACE).build()) + .addToData("key", "value") + .build(); V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(one); stubCall(configMapList); @@ -397,12 +415,14 @@ void testCorrectNameWithProfile() { @Test void cache(CapturedOutput output) { V1ConfigMap red = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("red").withNamespace(NAMESPACE).build()) - .addToData("color", "red").build(); + .withMetadata(new V1ObjectMetaBuilder().withName("red").withNamespace(NAMESPACE).build()) + .addToData("color", "red") + .build(); V1ConfigMap green = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("green").withNamespace(NAMESPACE).build()) - .addToData("color", "green").build(); + .withMetadata(new V1ObjectMetaBuilder().withName("green").withNamespace(NAMESPACE).build()) + .addToData("color", "green") + .build(); V1ConfigMapList configMapList = new V1ConfigMapList().addItemsItem(red).addItemsItem(green); @@ -442,7 +462,7 @@ void cache(CapturedOutput output) { private void stubCall(V1ConfigMapList list) { stubFor(get("/api/v1/namespaces/default/configmaps") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(list)))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(list)))); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/NamedSecretContextToSourceDataProviderTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/NamedSecretContextToSourceDataProviderTests.java index 75e0322e98..e78b2426d4 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/NamedSecretContextToSourceDataProviderTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/NamedSecretContextToSourceDataProviderTests.java @@ -84,8 +84,9 @@ void afterEach() { void singleSecretMatchAgainstLabels() { V1Secret red = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("red").build()) - .addToData(COLOR_REALLY_RED).build(); + .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("red").build()) + .addToData(COLOR_REALLY_RED) + .build(); V1SecretList secretList = new V1SecretList().addItemsItem(red); stubCall(secretList); CoreV1Api api = new CoreV1Api(); @@ -111,16 +112,19 @@ void singleSecretMatchAgainstLabels() { void twoSecretMatchAgainstLabels() { V1Secret red = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("red").build()) - .addToData(COLOR_REALLY_RED).build(); + .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("red").build()) + .addToData(COLOR_REALLY_RED) + .build(); V1Secret blue = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("blue").build()) - .addToData(COLOR_REALLY_RED).build(); + .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("blue").build()) + .addToData(COLOR_REALLY_RED) + .build(); V1Secret pink = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("pink").build()) - .addToData(COLOR_REALLY_RED).build(); + .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("pink").build()) + .addToData(COLOR_REALLY_RED) + .build(); V1SecretList secretList = new V1SecretListBuilder().addToItems(red).addToItems(blue).addToItems(pink).build(); @@ -148,8 +152,9 @@ void twoSecretMatchAgainstLabels() { void testSecretNoMatch() { V1Secret secret = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("red").build()) - .addToData(COLOR_REALLY_RED).build(); + .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("red").build()) + .addToData(COLOR_REALLY_RED) + .build(); V1SecretList secretList = new V1SecretList().addItemsItem(secret); stubCall(secretList); @@ -178,8 +183,9 @@ void testSecretNoMatch() { void namespaceMatch() { V1Secret secret = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("red").build()) - .addToData(COLOR_REALLY_RED).build(); + .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("red").build()) + .addToData(COLOR_REALLY_RED) + .build(); V1SecretList secretList = new V1SecretList().addItemsItem(secret); stubCall(secretList); @@ -205,12 +211,14 @@ void namespaceMatch() { void matchIncludeSingleProfile() { V1Secret red = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("red").build()) - .addToData(COLOR_REALLY_RED).build(); + .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("red").build()) + .addToData(COLOR_REALLY_RED) + .build(); V1Secret mango = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("red-with-profile").build()) - .addToData("taste", "mango".getBytes()).build(); + .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("red-with-profile").build()) + .addToData("taste", "mango".getBytes()) + .build(); V1SecretList secretList = new V1SecretList().addItemsItem(red).addItemsItem(mango); @@ -243,12 +251,14 @@ void matchIncludeSingleProfile() { void matchIncludeSingleProfileWithPrefix() { V1Secret red = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("red").build()) - .addToData(COLOR_REALLY_RED).build(); + .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("red").build()) + .addToData(COLOR_REALLY_RED) + .build(); V1Secret mango = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("red-with-taste").build()) - .addToData("taste", "mango".getBytes()).build(); + .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("red-with-taste").build()) + .addToData("taste", "mango".getBytes()) + .build(); V1SecretList secretList = new V1SecretList().addItemsItem(red).addItemsItem(mango); @@ -280,16 +290,19 @@ void matchIncludeSingleProfileWithPrefix() { void matchIncludeTwoProfilesWithPrefix() { V1Secret red = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("red").build()) - .addToData(COLOR_REALLY_RED).build(); + .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("red").build()) + .addToData(COLOR_REALLY_RED) + .build(); V1Secret mango = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("red-with-taste").build()) - .addToData("taste", "mango".getBytes()).build(); + .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("red-with-taste").build()) + .addToData("taste", "mango".getBytes()) + .build(); V1Secret shape = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("red-with-shape").build()) - .addToData("shape", "round".getBytes()).build(); + .withMetadata(new V1ObjectMetaBuilder().withNamespace(NAMESPACE).withName("red-with-shape").build()) + .addToData("shape", "round".getBytes()) + .build(); V1SecretList secretList = new V1SecretList().addItemsItem(red).addItemsItem(mango).addItemsItem(shape); @@ -321,8 +334,9 @@ void matchIncludeTwoProfilesWithPrefix() { @Test void testSingleYaml() { V1Secret singleYaml = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("single-yaml").withNamespace(NAMESPACE).build()) - .addToData("single.yaml", "key: value".getBytes()).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("single-yaml").withNamespace(NAMESPACE).build()) + .addToData("single.yaml", "key: value".getBytes()) + .build(); V1SecretList secretList = new V1SecretList().addItemsItem(singleYaml); stubCall(secretList); @@ -351,12 +365,14 @@ void testSingleYaml() { @Test void cache(CapturedOutput output) { V1Secret red = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("red").withNamespace(NAMESPACE).build()) - .addToData("color", "red".getBytes()).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("red").withNamespace(NAMESPACE).build()) + .addToData("color", "red".getBytes()) + .build(); V1Secret green = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("green").withNamespace(NAMESPACE).build()) - .addToData("color", "green".getBytes()).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("green").withNamespace(NAMESPACE).build()) + .addToData("color", "green".getBytes()) + .build(); V1SecretList configMapList = new V1SecretList().addItemsItem(red).addItemsItem(green); @@ -396,7 +412,7 @@ void cache(CapturedOutput output) { private void stubCall(V1SecretList list) { stubFor(get("/api/v1/namespaces/default/secrets") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(list)))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(list)))); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_config_map_with_prefix/LabeledConfigMapWithPrefixConfigDataTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_config_map_with_prefix/LabeledConfigMapWithPrefixConfigDataTests.java index 3af64c5210..fbdcd64c66 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_config_map_with_prefix/LabeledConfigMapWithPrefixConfigDataTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_config_map_with_prefix/LabeledConfigMapWithPrefixConfigDataTests.java @@ -50,10 +50,10 @@ static void wireMock() { WireMock.configureFor("localhost", server.port()); clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); clientUtilsMock - .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("spring-k8s"); + .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn("spring-k8s"); stubData(); } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_config_map_with_prefix/LabeledConfigMapWithPrefixTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_config_map_with_prefix/LabeledConfigMapWithPrefixTests.java index b2bd7da8ad..474876e23b 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_config_map_with_prefix/LabeledConfigMapWithPrefixTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_config_map_with_prefix/LabeledConfigMapWithPrefixTests.java @@ -57,8 +57,13 @@ static void afterAll() { */ @Test void testOne() { - this.webClient.get().uri("/labeled-configmap/prefix/one").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("one")); + this.webClient.get() + .uri("/labeled-configmap/prefix/one") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("one")); } /** @@ -72,8 +77,13 @@ void testOne() { */ @Test void testTwo() { - this.webClient.get().uri("/labeled-configmap/prefix/two").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("two")); + this.webClient.get() + .uri("/labeled-configmap/prefix/two") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("two")); } /** @@ -89,8 +99,13 @@ void testTwo() { */ @Test void testThree() { - this.webClient.get().uri("/labeled-configmap/prefix/three").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("three")); + this.webClient.get() + .uri("/labeled-configmap/prefix/three") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("three")); } /** @@ -106,8 +121,13 @@ void testThree() { */ @Test void testFour() { - this.webClient.get().uri("/labeled-configmap/prefix/four").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("four")); + this.webClient.get() + .uri("/labeled-configmap/prefix/four") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("four")); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_config_map_with_profile/LabeledConfigMapWithProfileConfigDataTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_config_map_with_profile/LabeledConfigMapWithProfileConfigDataTests.java index df53725772..d9a2816fa2 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_config_map_with_profile/LabeledConfigMapWithProfileConfigDataTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_config_map_with_profile/LabeledConfigMapWithProfileConfigDataTests.java @@ -52,10 +52,10 @@ static void wireMock() { WireMock.configureFor("localhost", server.port()); clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); clientUtilsMock - .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("spring-k8s"); + .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn("spring-k8s"); stubData(); } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_config_map_with_profile/LabeledConfigMapWithProfileTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_config_map_with_profile/LabeledConfigMapWithProfileTests.java index a382d020f0..cc4b6798b2 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_config_map_with_profile/LabeledConfigMapWithProfileTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_config_map_with_profile/LabeledConfigMapWithProfileTests.java @@ -55,8 +55,13 @@ static void afterAll() { */ @Test void testBlue() { - this.webClient.get().uri("/labeled-configmap/profile/blue").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("1")); + this.webClient.get() + .uri("/labeled-configmap/profile/blue") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("1")); } /** @@ -69,8 +74,13 @@ void testBlue() { */ @Test void testGreen() { - this.webClient.get().uri("/labeled-configmap/profile/green").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("2#6#7#eight-ish")); + this.webClient.get() + .uri("/labeled-configmap/profile/green") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("2#6#7#eight-ish")); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_secret_with_prefix/LabeledSecretWithPrefixConfigDataTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_secret_with_prefix/LabeledSecretWithPrefixConfigDataTests.java index ce0c8dc358..48279be64e 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_secret_with_prefix/LabeledSecretWithPrefixConfigDataTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_secret_with_prefix/LabeledSecretWithPrefixConfigDataTests.java @@ -49,10 +49,10 @@ static void wireMock() { WireMock.configureFor("localhost", server.port()); clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); clientUtilsMock - .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("spring-k8s"); + .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn("spring-k8s"); stubData(); } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_secret_with_prefix/LabeledSecretWithPrefixTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_secret_with_prefix/LabeledSecretWithPrefixTests.java index 8577c1d72f..42152a8f4d 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_secret_with_prefix/LabeledSecretWithPrefixTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_secret_with_prefix/LabeledSecretWithPrefixTests.java @@ -57,8 +57,13 @@ static void afterAll() { */ @Test void testOne() { - this.webClient.get().uri("/labeled-secret/prefix/one").exchange().expectStatus().isOk().expectBody(String.class) - .value(Matchers.equalTo("one")); + this.webClient.get() + .uri("/labeled-secret/prefix/one") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("one")); } /** @@ -72,8 +77,13 @@ void testOne() { */ @Test void testTwo() { - this.webClient.get().uri("/labeled-secret/prefix/two").exchange().expectStatus().isOk().expectBody(String.class) - .value(Matchers.equalTo("two")); + this.webClient.get() + .uri("/labeled-secret/prefix/two") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("two")); } /** @@ -89,8 +99,13 @@ void testTwo() { */ @Test void testThree() { - this.webClient.get().uri("/labeled-secret/prefix/three").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("three")); + this.webClient.get() + .uri("/labeled-secret/prefix/three") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("three")); } /** @@ -106,8 +121,13 @@ void testThree() { */ @Test void testFour() { - this.webClient.get().uri("/labeled-secret/prefix/four").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("four")); + this.webClient.get() + .uri("/labeled-secret/prefix/four") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("four")); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_secret_with_profile/LabeledSecretWithProfileConfigDataTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_secret_with_profile/LabeledSecretWithProfileConfigDataTests.java index 50e17abb45..e856a2b4d2 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_secret_with_profile/LabeledSecretWithProfileConfigDataTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_secret_with_profile/LabeledSecretWithProfileConfigDataTests.java @@ -51,10 +51,10 @@ static void wireMock() { WireMock.configureFor("localhost", server.port()); clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); clientUtilsMock - .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("spring-k8s"); + .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn("spring-k8s"); stubData(); } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_secret_with_profile/LabeledSecretWithProfileTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_secret_with_profile/LabeledSecretWithProfileTests.java index 9244434bbb..b66dab4a1c 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_secret_with_profile/LabeledSecretWithProfileTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/labeled_secret_with_profile/LabeledSecretWithProfileTests.java @@ -67,8 +67,13 @@ static void afterAll() { */ @Test void testBlue() { - this.webClient.get().uri("/labeled-secret/profile/blue").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("1")); + this.webClient.get() + .uri("/labeled-secret/profile/blue") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("1")); } /** @@ -81,8 +86,13 @@ void testBlue() { */ @Test void testGreen() { - this.webClient.get().uri("/labeled-secret/profile/green").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("2#6#7#eight-ish")); + this.webClient.get() + .uri("/labeled-secret/profile/green") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("2#6#7#eight-ish")); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_config_map_with_prefix/NamedConfigMapWithPrefixConfigDataTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_config_map_with_prefix/NamedConfigMapWithPrefixConfigDataTests.java index 62ea60ef8b..6afede8890 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_config_map_with_prefix/NamedConfigMapWithPrefixConfigDataTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_config_map_with_prefix/NamedConfigMapWithPrefixConfigDataTests.java @@ -49,10 +49,10 @@ static void wireMock() { WireMock.configureFor("localhost", server.port()); clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); clientUtilsMock - .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("spring-k8s"); + .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn("spring-k8s"); stubData(); } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_config_map_with_prefix/NamedConfigMapWithPrefixTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_config_map_with_prefix/NamedConfigMapWithPrefixTests.java index 71d4359ea1..378698dba5 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_config_map_with_prefix/NamedConfigMapWithPrefixTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_config_map_with_prefix/NamedConfigMapWithPrefixTests.java @@ -57,8 +57,13 @@ static void afterAll() { */ @Test void testOne() { - this.webClient.get().uri("/named-configmap/prefix/one").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("one")); + this.webClient.get() + .uri("/named-configmap/prefix/one") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("one")); } /** @@ -72,8 +77,13 @@ void testOne() { */ @Test void testTwo() { - this.webClient.get().uri("/named-configmap/prefix/two").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("two")); + this.webClient.get() + .uri("/named-configmap/prefix/two") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("two")); } /** @@ -87,8 +97,13 @@ void testTwo() { */ @Test void testThree() { - this.webClient.get().uri("/named-configmap/prefix/three").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("three")); + this.webClient.get() + .uri("/named-configmap/prefix/three") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("three")); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_config_map_with_profile/NamedConfigMapWithProfileConfigDataTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_config_map_with_profile/NamedConfigMapWithProfileConfigDataTests.java index 449aa6a28e..123e4122e5 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_config_map_with_profile/NamedConfigMapWithProfileConfigDataTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_config_map_with_profile/NamedConfigMapWithProfileConfigDataTests.java @@ -52,10 +52,10 @@ public static void wireMock() { WireMock.configureFor("localhost", server.port()); clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); clientUtilsMock - .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("spring-k8s"); + .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn("spring-k8s"); stubData(); } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_config_map_with_profile/NamedConfigMapWithProfileTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_config_map_with_profile/NamedConfigMapWithProfileTests.java index 21a86346ac..0afb13f645 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_config_map_with_profile/NamedConfigMapWithProfileTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_config_map_with_profile/NamedConfigMapWithProfileTests.java @@ -59,8 +59,13 @@ static void afterAll() { */ @Test void testOne() { - this.webClient.get().uri("/named-configmap/profile/one").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("one-from-k8s")); + this.webClient.get() + .uri("/named-configmap/profile/one") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("one-from-k8s")); } /** @@ -77,8 +82,13 @@ void testOne() { */ @Test void testTwo() { - this.webClient.get().uri("/named-configmap/profile/two").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("two")); + this.webClient.get() + .uri("/named-configmap/profile/two") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("two")); } /** @@ -94,8 +104,13 @@ void testTwo() { */ @Test void testThree() { - this.webClient.get().uri("/named-configmap/profile/three").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("three-from-k8s")); + this.webClient.get() + .uri("/named-configmap/profile/three") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("three-from-k8s")); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_secret_with_prefix/NamedSecretWithPrefixConfigDataTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_secret_with_prefix/NamedSecretWithPrefixConfigDataTests.java index de518cf1ed..5d3e1885e5 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_secret_with_prefix/NamedSecretWithPrefixConfigDataTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_secret_with_prefix/NamedSecretWithPrefixConfigDataTests.java @@ -50,10 +50,10 @@ static void wireMock() { WireMock.configureFor("localhost", server.port()); clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); clientUtilsMock - .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("spring-k8s"); + .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn("spring-k8s"); stubData(); } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_secret_with_prefix/NamedSecretWithPrefixTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_secret_with_prefix/NamedSecretWithPrefixTests.java index 68c0de45c1..f9a4c956b7 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_secret_with_prefix/NamedSecretWithPrefixTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_secret_with_prefix/NamedSecretWithPrefixTests.java @@ -57,8 +57,13 @@ static void afterAll() { */ @Test void testOne() { - this.webClient.get().uri("/named-secret/prefix/one").exchange().expectStatus().isOk().expectBody(String.class) - .value(Matchers.equalTo("one")); + this.webClient.get() + .uri("/named-secret/prefix/one") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("one")); } /** @@ -72,8 +77,13 @@ void testOne() { */ @Test void testTwo() { - this.webClient.get().uri("/named-secret/prefix/two").exchange().expectStatus().isOk().expectBody(String.class) - .value(Matchers.equalTo("two")); + this.webClient.get() + .uri("/named-secret/prefix/two") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("two")); } /** @@ -87,8 +97,13 @@ void testTwo() { */ @Test void testThree() { - this.webClient.get().uri("/named-secret/prefix/three").exchange().expectStatus().isOk().expectBody(String.class) - .value(Matchers.equalTo("three")); + this.webClient.get() + .uri("/named-secret/prefix/three") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("three")); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_secret_with_profile/NamedSecretWithProfileConfigDataTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_secret_with_profile/NamedSecretWithProfileConfigDataTests.java index 3b036954f2..a625f35181 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_secret_with_profile/NamedSecretWithProfileConfigDataTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_secret_with_profile/NamedSecretWithProfileConfigDataTests.java @@ -52,10 +52,10 @@ static void wireMock() { WireMock.configureFor("localhost", server.port()); clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); clientUtilsMock - .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("spring-k8s"); + .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn("spring-k8s"); stubData(); } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_secret_with_profile/NamedSecretWithProfileTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_secret_with_profile/NamedSecretWithProfileTests.java index 631a2db87a..df6d0e95c8 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_secret_with_profile/NamedSecretWithProfileTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/named_secret_with_profile/NamedSecretWithProfileTests.java @@ -59,8 +59,13 @@ static void afterAll() { */ @Test void testOne() { - this.webClient.get().uri("/named-secret/profile/one").exchange().expectStatus().isOk().expectBody(String.class) - .value(Matchers.equalTo("one-from-k8s")); + this.webClient.get() + .uri("/named-secret/profile/one") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("one-from-k8s")); } /** @@ -77,8 +82,13 @@ void testOne() { */ @Test void testTwo() { - this.webClient.get().uri("/named-secret/profile/two").exchange().expectStatus().isOk().expectBody(String.class) - .value(Matchers.equalTo("two")); + this.webClient.get() + .uri("/named-secret/profile/two") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("two")); } /** @@ -94,8 +104,13 @@ void testTwo() { */ @Test void testThree() { - this.webClient.get().uri("/named-secret/profile/three").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("three-from-k8s")); + this.webClient.get() + .uri("/named-secret/profile/three") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("three-from-k8s")); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/single_source_multiple_files/SingleSourceMultipleFilesConfigDataTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/single_source_multiple_files/SingleSourceMultipleFilesConfigDataTests.java index 64fa102f89..d36bfe52ce 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/single_source_multiple_files/SingleSourceMultipleFilesConfigDataTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/single_source_multiple_files/SingleSourceMultipleFilesConfigDataTests.java @@ -50,10 +50,10 @@ static void wireMock() { WireMock.configureFor("localhost", server.port()); clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); clientUtilsMock - .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("spring-k8s"); + .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn("spring-k8s"); stubData(); } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/single_source_multiple_files/SingleSourceMultipleFilesTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/single_source_multiple_files/SingleSourceMultipleFilesTests.java index 4dd41e9ab0..d9e2c597dd 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/single_source_multiple_files/SingleSourceMultipleFilesTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/single_source_multiple_files/SingleSourceMultipleFilesTests.java @@ -57,8 +57,13 @@ static void afterAll() { */ @Test void color() { - this.webClient.get().uri("/single_source-multiple-files/color").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("raw:green###ripe:yellow")); + this.webClient.get() + .uri("/single_source-multiple-files/color") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("raw:green###ripe:yellow")); } /** @@ -68,8 +73,13 @@ void color() { */ @Test void name() { - this.webClient.get().uri("/single_source-multiple-files/name").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("banana")); + this.webClient.get() + .uri("/single_source-multiple-files/name") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("banana")); } /** @@ -80,8 +90,13 @@ void name() { */ @Test void shape() { - this.webClient.get().uri("/single_source-multiple-files/shape").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.nullValue()); + this.webClient.get() + .uri("/single_source-multiple-files/shape") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.nullValue()); } /** @@ -91,8 +106,13 @@ void shape() { */ @Test void type() { - this.webClient.get().uri("/single_source-multiple-files/type").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("yummy")); + this.webClient.get() + .uri("/single_source-multiple-files/type") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("yummy")); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/sources_order/ConfigDataRetryableSourcesOrderTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/sources_order/ConfigDataRetryableSourcesOrderTests.java index 59e075dd89..f96a3be2e6 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/sources_order/ConfigDataRetryableSourcesOrderTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/sources_order/ConfigDataRetryableSourcesOrderTests.java @@ -57,10 +57,10 @@ static void wireMock() { WireMock.configureFor("localhost", server.port()); clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); clientUtilsMock - .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("spring-k8s"); + .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn("spring-k8s"); stubConfigMapData(); stubSecretsData(); } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/sources_order/ConfigDataSourcesOrderTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/sources_order/ConfigDataSourcesOrderTests.java index 7b32c3ef98..ceb17fa0bf 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/sources_order/ConfigDataSourcesOrderTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/sources_order/ConfigDataSourcesOrderTests.java @@ -51,10 +51,10 @@ static void wireMock() { WireMock.configureFor("localhost", server.port()); clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); clientUtilsMock - .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("spring-k8s"); + .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn("spring-k8s"); stubConfigMapData(); stubSecretsData(); } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/sources_order/SourcesOrderTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/sources_order/SourcesOrderTests.java index a32ede6fa0..3f43f594ee 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/sources_order/SourcesOrderTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/applications/sources_order/SourcesOrderTests.java @@ -67,13 +67,28 @@ static void afterAll() { */ @Test void test() { - this.webClient.get().uri("/one").exchange().expectStatus().isOk().expectBody(String.class) - .value(Matchers.equalTo("one")); - this.webClient.get().uri("/two").exchange().expectStatus().isOk().expectBody(String.class) - .value(Matchers.equalTo("two")); + this.webClient.get() + .uri("/one") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("one")); + this.webClient.get() + .uri("/two") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("two")); - this.webClient.get().uri("/key").exchange().expectStatus().isOk().expectBody(String.class) - .value(Matchers.equalTo("from-configmap")); + this.webClient.get() + .uri("/key") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("from-configmap")); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/BootstrapKubernetesClientSanitizeEnvEndpointStub.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/BootstrapKubernetesClientSanitizeEnvEndpointStub.java index 872120e04b..0e33e3607f 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/BootstrapKubernetesClientSanitizeEnvEndpointStub.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/BootstrapKubernetesClientSanitizeEnvEndpointStub.java @@ -69,16 +69,19 @@ public ApiClient apiClient(WireMockServer wireMockServer) { public static void stubData() { V1ConfigMap one = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("sanitize-configmap").withNamespace("test").build()) - .addToData(Map.of("sanitize.sanitizeConfigMapName", "sanitizeConfigMapValue")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("sanitize-configmap").withNamespace("test").build()) + .addToData(Map.of("sanitize.sanitizeConfigMapName", "sanitizeConfigMapValue")) + .build(); V1Secret secretOne = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("sanitize-secret").withNamespace("test").build()) - .addToData(Map.of("sanitize.sanitizeSecretName", "sanitizeSecretValue".getBytes())).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("sanitize-secret").withNamespace("test").build()) + .addToData(Map.of("sanitize.sanitizeSecretName", "sanitizeSecretValue".getBytes())) + .build(); V1Secret secretTwo = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("sanitize-secret-two").withNamespace("test").build()) - .addToData(Map.of("sanitize.sanitizeSecretNameTwo", "sanitizeSecretValueTwo".getBytes())).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("sanitize-secret-two").withNamespace("test").build()) + .addToData(Map.of("sanitize.sanitizeSecretNameTwo", "sanitizeSecretValueTwo".getBytes())) + .build(); // the actual stub for CoreV1Api calls V1ConfigMapList configMapList = new V1ConfigMapList(); @@ -89,10 +92,10 @@ public static void stubData() { secretList.addItemsItem(secretTwo); WireMock.stubFor(WireMock.get("/api/v1/namespaces/test/configmaps") - .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(configMapList)))); + .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(configMapList)))); WireMock.stubFor(WireMock.get("/api/v1/namespaces/test/secrets") - .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(secretList)))); + .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(secretList)))); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/LabeledConfigMapWithPrefixConfigurationStub.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/LabeledConfigMapWithPrefixConfigurationStub.java index cce9bdd9c1..12b6015cc9 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/LabeledConfigMapWithPrefixConfigurationStub.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/LabeledConfigMapWithPrefixConfigurationStub.java @@ -67,24 +67,36 @@ public ApiClient apiClient(WireMockServer wireMockServer) { public static void stubData() { V1ConfigMap one = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("configmap-one").withNamespace("spring-k8s") - .withLabels(Map.of("letter", "a")).build()) - .addToData(Collections.singletonMap("one.property", "one")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("configmap-one") + .withNamespace("spring-k8s") + .withLabels(Map.of("letter", "a")) + .build()) + .addToData(Collections.singletonMap("one.property", "one")) + .build(); V1ConfigMap two = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("configmap-two").withNamespace("spring-k8s") - .withLabels(Map.of("letter", "b")).build()) - .addToData(Collections.singletonMap("property", "two")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("configmap-two") + .withNamespace("spring-k8s") + .withLabels(Map.of("letter", "b")) + .build()) + .addToData(Collections.singletonMap("property", "two")) + .build(); V1ConfigMap three = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("configmap-three").withNamespace("spring-k8s") - .withLabels(Map.of("letter", "c")).build()) - .addToData(Collections.singletonMap("property", "three")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("configmap-three") + .withNamespace("spring-k8s") + .withLabels(Map.of("letter", "c")) + .build()) + .addToData(Collections.singletonMap("property", "three")) + .build(); V1ConfigMap four = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("configmap-four").withNamespace("spring-k8s") - .withLabels(Map.of("letter", "d")).build()) - .addToData(Collections.singletonMap("property", "four")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("configmap-four") + .withNamespace("spring-k8s") + .withLabels(Map.of("letter", "d")) + .build()) + .addToData(Collections.singletonMap("property", "four")) + .build(); // the actual stub for CoreV1Api calls V1ConfigMapList configMapList = new V1ConfigMapList(); @@ -94,7 +106,7 @@ public static void stubData() { configMapList.addItemsItem(four); WireMock.stubFor(WireMock.get("/api/v1/namespaces/spring-k8s/configmaps") - .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(configMapList)))); + .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(configMapList)))); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/LabeledConfigMapWithProfileConfigurationStub.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/LabeledConfigMapWithProfileConfigurationStub.java index a0a2025bd5..8e1ed61203 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/LabeledConfigMapWithProfileConfigurationStub.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/LabeledConfigMapWithProfileConfigurationStub.java @@ -84,56 +84,83 @@ public static void stubData() { // is found by labels V1ConfigMap colorConfigMap = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("color-configmap").withNamespace("spring-k8s") - .withLabels(Map.of("color", "blue")).build()) - .addToData(Collections.singletonMap("one", "1")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("color-configmap") + .withNamespace("spring-k8s") + .withLabels(Map.of("color", "blue")) + .build()) + .addToData(Collections.singletonMap("one", "1")) + .build(); // is not taken, since "profileSpecificSources=false" for the above V1ConfigMap colorConfigMapK8s = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("color-configmap-k8s").withNamespace("spring-k8s") - .withLabels(Map.of("color", "not-blue")).build()) - .addToData(Collections.singletonMap("five", "5")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("color-configmap-k8s") + .withNamespace("spring-k8s") + .withLabels(Map.of("color", "not-blue")) + .build()) + .addToData(Collections.singletonMap("five", "5")) + .build(); // is found by labels V1ConfigMap greenConfigMap = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("green-configmap").withNamespace("spring-k8s") - .withLabels(Map.of("color", "green")).build()) - .addToData(Collections.singletonMap("two", "2")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("green-configmap") + .withNamespace("spring-k8s") + .withLabels(Map.of("color", "green")) + .build()) + .addToData(Collections.singletonMap("two", "2")) + .build(); V1ConfigMap greenConfigMapK8s = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("green-configmap-k8s").withNamespace("spring-k8s") - .withLabels(Map.of("color", "green-k8s")).build()) - .addToData(Collections.singletonMap("six", "6")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("green-configmap-k8s") + .withNamespace("spring-k8s") + .withLabels(Map.of("color", "green-k8s")) + .build()) + .addToData(Collections.singletonMap("six", "6")) + .build(); // is taken because prod profile is active and "profileSpecificSources=true" V1ConfigMap greenConfigMapProd = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("green-configmap-prod").withNamespace("spring-k8s") - .withLabels(Map.of("color", "green-prod")).build()) - .addToData(Collections.singletonMap("seven", "7")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("green-configmap-prod") + .withNamespace("spring-k8s") + .withLabels(Map.of("color", "green-prod")) + .build()) + .addToData(Collections.singletonMap("seven", "7")) + .build(); // not taken V1ConfigMap redConfigMap = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("red-configmap").withNamespace("spring-k8s") - .withLabels(Map.of("color", "red")).build()) - .addToData(Collections.singletonMap("three", "3")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("red-configmap") + .withNamespace("spring-k8s") + .withLabels(Map.of("color", "red")) + .build()) + .addToData(Collections.singletonMap("three", "3")) + .build(); // not taken V1ConfigMap yellowConfigMap = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("yellow-configmap").withNamespace("spring-k8s") - .withLabels(Map.of("color", "yellow")).build()) - .addToData(Collections.singletonMap("four", "4")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("yellow-configmap") + .withNamespace("spring-k8s") + .withLabels(Map.of("color", "yellow")) + .build()) + .addToData(Collections.singletonMap("four", "4")) + .build(); // is found by labels V1ConfigMap greenPurpleConfigMap = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("green-purple-configmap").withNamespace("spring-k8s") - .withLabels(Map.of("color", "green", "shape", "round")).build()) - .addToData(Collections.singletonMap("eight", "8")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("green-purple-configmap") + .withNamespace("spring-k8s") + .withLabels(Map.of("color", "green", "shape", "round")) + .build()) + .addToData(Collections.singletonMap("eight", "8")) + .build(); // is taken and thus overrides the above V1ConfigMap greenPurpleConfigMapK8s = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("green-purple-configmap-k8s") - .withNamespace("spring-k8s").withLabels(Map.of("color", "black")).build()) - .addToData(Collections.singletonMap("eight", "eight-ish")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("green-purple-configmap-k8s") + .withNamespace("spring-k8s") + .withLabels(Map.of("color", "black")) + .build()) + .addToData(Collections.singletonMap("eight", "eight-ish")) + .build(); // the actual stub for CoreV1Api calls V1ConfigMapList configMaps = new V1ConfigMapList(); @@ -148,7 +175,7 @@ public static void stubData() { configMaps.addItemsItem(greenPurpleConfigMapK8s); WireMock.stubFor(WireMock.get("/api/v1/namespaces/spring-k8s/configmaps") - .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(configMaps)))); + .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(configMaps)))); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/LabeledSecretWithPrefixConfigurationStub.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/LabeledSecretWithPrefixConfigurationStub.java index f5008b7363..1297e05bb4 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/LabeledSecretWithPrefixConfigurationStub.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/LabeledSecretWithPrefixConfigurationStub.java @@ -66,24 +66,40 @@ public ApiClient apiClient(WireMockServer wireMockServer) { public static void stubData() { V1Secret one = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("secret-one").withNamespace("spring-k8s") - .withLabels(Map.of("letter", "a")).withResourceVersion("1").build()) - .addToData(Collections.singletonMap("one.property", "one".getBytes())).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("secret-one") + .withNamespace("spring-k8s") + .withLabels(Map.of("letter", "a")) + .withResourceVersion("1") + .build()) + .addToData(Collections.singletonMap("one.property", "one".getBytes())) + .build(); V1Secret two = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("secret-two").withNamespace("spring-k8s") - .withLabels(Map.of("letter", "b")).withResourceVersion("1").build()) - .addToData(Collections.singletonMap("property", "two".getBytes())).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("secret-two") + .withNamespace("spring-k8s") + .withLabels(Map.of("letter", "b")) + .withResourceVersion("1") + .build()) + .addToData(Collections.singletonMap("property", "two".getBytes())) + .build(); V1Secret three = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("secret-three").withNamespace("spring-k8s") - .withLabels(Map.of("letter", "c")).withResourceVersion("1").build()) - .addToData(Collections.singletonMap("property", "three".getBytes())).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("secret-three") + .withNamespace("spring-k8s") + .withLabels(Map.of("letter", "c")) + .withResourceVersion("1") + .build()) + .addToData(Collections.singletonMap("property", "three".getBytes())) + .build(); V1Secret four = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("secret-four").withNamespace("spring-k8s") - .withLabels(Map.of("letter", "d")).withResourceVersion("1").build()) - .addToData(Collections.singletonMap("property", "four".getBytes())).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("secret-four") + .withNamespace("spring-k8s") + .withLabels(Map.of("letter", "d")) + .withResourceVersion("1") + .build()) + .addToData(Collections.singletonMap("property", "four".getBytes())) + .build(); // the actual stub for CoreV1Api calls V1SecretList secrets = new V1SecretList(); @@ -93,7 +109,7 @@ public static void stubData() { secrets.addItemsItem(four); WireMock.stubFor(WireMock.get("/api/v1/namespaces/spring-k8s/secrets") - .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(secrets)))); + .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(secrets)))); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/LabeledSecretWithProfileConfigurationStub.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/LabeledSecretWithProfileConfigurationStub.java index 34b5632ef8..c59ca39f1c 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/LabeledSecretWithProfileConfigurationStub.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/LabeledSecretWithProfileConfigurationStub.java @@ -85,56 +85,83 @@ public static void stubData() { // is found by labels V1Secret colorSecret = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("color-secret").withNamespace("spring-k8s") - .withLabels(Map.of("color", "blue")).build()) - .addToData(Collections.singletonMap("one", "1".getBytes(StandardCharsets.UTF_8))).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("color-secret") + .withNamespace("spring-k8s") + .withLabels(Map.of("color", "blue")) + .build()) + .addToData(Collections.singletonMap("one", "1".getBytes(StandardCharsets.UTF_8))) + .build(); // is not taken, since "profileSpecificSources=false" for the above V1Secret colorSecretK8s = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("color-secret-k8s").withNamespace("spring-k8s") - .withLabels(Map.of("color", "not-blue")).build()) - .addToData(Collections.singletonMap("five", "5".getBytes(StandardCharsets.UTF_8))).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("color-secret-k8s") + .withNamespace("spring-k8s") + .withLabels(Map.of("color", "not-blue")) + .build()) + .addToData(Collections.singletonMap("five", "5".getBytes(StandardCharsets.UTF_8))) + .build(); // is found by labels V1Secret greenSecret = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("green-secret").withNamespace("spring-k8s") - .withLabels(Map.of("color", "green")).build()) - .addToData(Collections.singletonMap("two", "2".getBytes(StandardCharsets.UTF_8))).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("green-secret") + .withNamespace("spring-k8s") + .withLabels(Map.of("color", "green")) + .build()) + .addToData(Collections.singletonMap("two", "2".getBytes(StandardCharsets.UTF_8))) + .build(); V1Secret greenSecretK8s = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("green-secret-k8s").withNamespace("spring-k8s") - .withLabels(Map.of("color", "green-k8s")).build()) - .addToData(Collections.singletonMap("six", "6".getBytes(StandardCharsets.UTF_8))).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("green-secret-k8s") + .withNamespace("spring-k8s") + .withLabels(Map.of("color", "green-k8s")) + .build()) + .addToData(Collections.singletonMap("six", "6".getBytes(StandardCharsets.UTF_8))) + .build(); // is taken because prod profile is active and "profileSpecificSources=true" V1Secret shapeSecretProd = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("green-secret-prod").withNamespace("spring-k8s") - .withLabels(Map.of("color", "green-prod")).build()) - .addToData(Collections.singletonMap("seven", "7".getBytes(StandardCharsets.UTF_8))).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("green-secret-prod") + .withNamespace("spring-k8s") + .withLabels(Map.of("color", "green-prod")) + .build()) + .addToData(Collections.singletonMap("seven", "7".getBytes(StandardCharsets.UTF_8))) + .build(); // not taken V1Secret redSecret = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("red-secret").withNamespace("spring-k8s") - .withLabels(Map.of("color", "not-red")).build()) - .addToData(Collections.singletonMap("three", "3".getBytes(StandardCharsets.UTF_8))).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("red-secret") + .withNamespace("spring-k8s") + .withLabels(Map.of("color", "not-red")) + .build()) + .addToData(Collections.singletonMap("three", "3".getBytes(StandardCharsets.UTF_8))) + .build(); // not taken V1Secret yellowSecret = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("yellow-secret").withNamespace("spring-k8s") - .withLabels(Map.of("color", "not-yellow")).build()) - .addToData(Collections.singletonMap("four", "4".getBytes(StandardCharsets.UTF_8))).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("yellow-secret") + .withNamespace("spring-k8s") + .withLabels(Map.of("color", "not-yellow")) + .build()) + .addToData(Collections.singletonMap("four", "4".getBytes(StandardCharsets.UTF_8))) + .build(); // is found by labels V1Secret greenPurpleSecret = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("green-purple-secret").withNamespace("spring-k8s") - .withLabels(Map.of("color", "green", "shape", "round")).build()) - .addToData(Collections.singletonMap("eight", "8".getBytes(StandardCharsets.UTF_8))).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("green-purple-secret") + .withNamespace("spring-k8s") + .withLabels(Map.of("color", "green", "shape", "round")) + .build()) + .addToData(Collections.singletonMap("eight", "8".getBytes(StandardCharsets.UTF_8))) + .build(); // is taken and thus overrides the above V1Secret greenPurpleSecretK8s = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("green-purple-secret-k8s").withNamespace("spring-k8s") - .withLabels(Map.of("color", "black")).build()) - .addToData(Collections.singletonMap("eight", "eight-ish".getBytes(StandardCharsets.UTF_8))).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("green-purple-secret-k8s") + .withNamespace("spring-k8s") + .withLabels(Map.of("color", "black")) + .build()) + .addToData(Collections.singletonMap("eight", "eight-ish".getBytes(StandardCharsets.UTF_8))) + .build(); // the actual stub for CoreV1Api calls V1SecretList secrets = new V1SecretList(); @@ -149,7 +176,7 @@ public static void stubData() { secrets.addItemsItem(greenPurpleSecretK8s); WireMock.stubFor(WireMock.get("/api/v1/namespaces/spring-k8s/secrets") - .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(secrets)))); + .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(secrets)))); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/NamedConfigMapWithPrefixConfigurationStub.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/NamedConfigMapWithPrefixConfigurationStub.java index aafb86d4a3..7749e8dfc9 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/NamedConfigMapWithPrefixConfigurationStub.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/NamedConfigMapWithPrefixConfigurationStub.java @@ -66,26 +66,35 @@ public ApiClient apiClient(WireMockServer wireMockServer) { public static void stubData() { V1ConfigMap one = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("config-map-one").withNamespace("spring-k8s") - .withResourceVersion("1").build()) - .addToData(Collections.singletonMap("one.property", "one")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("config-map-one") + .withNamespace("spring-k8s") + .withResourceVersion("1") + .build()) + .addToData(Collections.singletonMap("one.property", "one")) + .build(); V1ConfigMap two = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("config-map-two").withNamespace("spring-k8s") - .withResourceVersion("1").build()) - .addToData(Collections.singletonMap("property", "two")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("config-map-two") + .withNamespace("spring-k8s") + .withResourceVersion("1") + .build()) + .addToData(Collections.singletonMap("property", "two")) + .build(); V1ConfigMap three = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("config-map-three").withNamespace("spring-k8s") - .withResourceVersion("1").build()) - .addToData(Collections.singletonMap("property", "three")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("config-map-three") + .withNamespace("spring-k8s") + .withResourceVersion("1") + .build()) + .addToData(Collections.singletonMap("property", "three")) + .build(); V1ConfigMapList allConfigMaps = new V1ConfigMapList(); allConfigMaps.setItems(Arrays.asList(one, two, three)); // the actual stub for CoreV1Api calls WireMock.stubFor(WireMock.get("/api/v1/namespaces/spring-k8s/configmaps") - .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(allConfigMaps)))); + .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(allConfigMaps)))); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/NamedConfigMapWithProfileConfigurationStub.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/NamedConfigMapWithProfileConfigurationStub.java index fdf2ad6d6b..ddb508c9ab 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/NamedConfigMapWithProfileConfigurationStub.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/NamedConfigMapWithProfileConfigurationStub.java @@ -72,38 +72,41 @@ public static void stubData() { // overridden by the ones from "oneFromK8s". // We have a test that asserts this. V1ConfigMap one = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("configmap-one").withNamespace("spring-k8s").build()) - .addToData(Collections.singletonMap("one.property", "one")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("configmap-one").withNamespace("spring-k8s").build()) + .addToData(Collections.singletonMap("one.property", "one")) + .build(); V1ConfigMap oneFromK8s = new V1ConfigMapBuilder() - .withMetadata( - new V1ObjectMetaBuilder().withName("configmap-one-k8s").withNamespace("spring-k8s").build()) - .addToData(Collections.singletonMap("one.property", "one-from-k8s")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("configmap-one-k8s").withNamespace("spring-k8s").build()) + .addToData(Collections.singletonMap("one.property", "one-from-k8s")) + .build(); V1ConfigMap two = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("configmap-two").withNamespace("spring-k8s").build()) - .addToData(Collections.singletonMap("property", "two")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("configmap-two").withNamespace("spring-k8s").build()) + .addToData(Collections.singletonMap("property", "two")) + .build(); V1ConfigMap twoFromK8s = new V1ConfigMapBuilder() - .withMetadata( - new V1ObjectMetaBuilder().withName("configmap-two-k8s").withNamespace("spring-k8s").build()) - .addToData(Collections.singletonMap("property", "two-from-k8s")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("configmap-two-k8s").withNamespace("spring-k8s").build()) + .addToData(Collections.singletonMap("property", "two-from-k8s")) + .build(); V1ConfigMap three = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("configmap-three").withNamespace("spring-k8s").build()) - .addToData(Collections.singletonMap("property", "three")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("configmap-three").withNamespace("spring-k8s").build()) + .addToData(Collections.singletonMap("property", "three")) + .build(); V1ConfigMap threeFromK8s = new V1ConfigMapBuilder() - .withMetadata( - new V1ObjectMetaBuilder().withName("configmap-three-k8s").withNamespace("spring-k8s").build()) - .addToData(Collections.singletonMap("property", "three-from-k8s")).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("configmap-three-k8s").withNamespace("spring-k8s").build()) + .addToData(Collections.singletonMap("property", "three-from-k8s")) + .build(); V1ConfigMapList allConfigMaps = new V1ConfigMapList(); allConfigMaps.setItems(Arrays.asList(one, oneFromK8s, two, twoFromK8s, three, threeFromK8s)); // the actual stub for CoreV1Api calls WireMock.stubFor(WireMock.get("/api/v1/namespaces/spring-k8s/configmaps") - .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(allConfigMaps)))); + .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(allConfigMaps)))); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/NamedSecretWithPrefixConfigurationStub.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/NamedSecretWithPrefixConfigurationStub.java index a6e41f64d8..35273eb394 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/NamedSecretWithPrefixConfigurationStub.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/NamedSecretWithPrefixConfigurationStub.java @@ -65,26 +65,35 @@ public ApiClient apiClient(WireMockServer wireMockServer) { public static void stubData() { V1Secret one = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("secret-one").withNamespace("spring-k8s") - .withResourceVersion("1").build()) - .addToData(Collections.singletonMap("one.property", "one".getBytes())).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("secret-one") + .withNamespace("spring-k8s") + .withResourceVersion("1") + .build()) + .addToData(Collections.singletonMap("one.property", "one".getBytes())) + .build(); V1Secret two = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("secret-two").withNamespace("spring-k8s") - .withResourceVersion("1").build()) - .addToData(Collections.singletonMap("property", "two".getBytes())).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("secret-two") + .withNamespace("spring-k8s") + .withResourceVersion("1") + .build()) + .addToData(Collections.singletonMap("property", "two".getBytes())) + .build(); V1Secret three = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("secret-three").withNamespace("spring-k8s") - .withResourceVersion("1").build()) - .addToData(Collections.singletonMap("property", "three".getBytes())).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("secret-three") + .withNamespace("spring-k8s") + .withResourceVersion("1") + .build()) + .addToData(Collections.singletonMap("property", "three".getBytes())) + .build(); V1SecretList allSecrets = new V1SecretList(); allSecrets.setItems(Arrays.asList(one, two, three)); // the actual stub for CoreV1Api calls WireMock.stubFor(WireMock.get("/api/v1/namespaces/spring-k8s/secrets") - .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(allSecrets)))); + .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(allSecrets)))); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/NamedSecretWithProfileConfigurationStub.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/NamedSecretWithProfileConfigurationStub.java index 3630a5f798..5d61ab6c59 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/NamedSecretWithProfileConfigurationStub.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/NamedSecretWithProfileConfigurationStub.java @@ -71,41 +71,59 @@ public static void stubData() { // overridden by the ones from "oneWithProfile". // We have a test that asserts this. V1Secret one = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("secret-one").withNamespace("spring-k8s") - .withResourceVersion("1").build()) - .addToData(Collections.singletonMap("one.property", "one".getBytes())).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("secret-one") + .withNamespace("spring-k8s") + .withResourceVersion("1") + .build()) + .addToData(Collections.singletonMap("one.property", "one".getBytes())) + .build(); V1Secret oneWithProfile = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("secret-one-k8s").withNamespace("spring-k8s") - .withResourceVersion("1").build()) - .addToData(Collections.singletonMap("one.property", "one-from-k8s".getBytes())).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("secret-one-k8s") + .withNamespace("spring-k8s") + .withResourceVersion("1") + .build()) + .addToData(Collections.singletonMap("one.property", "one-from-k8s".getBytes())) + .build(); V1Secret two = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("secret-two").withNamespace("spring-k8s") - .withResourceVersion("1").build()) - .addToData(Collections.singletonMap("property", "two".getBytes())).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("secret-two") + .withNamespace("spring-k8s") + .withResourceVersion("1") + .build()) + .addToData(Collections.singletonMap("property", "two".getBytes())) + .build(); V1Secret twoWithProfile = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("secret-two-k8s").withNamespace("spring-k8s") - .withResourceVersion("1").build()) - .addToData(Collections.singletonMap("property", "two-from-k8s".getBytes())).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("secret-two-k8s") + .withNamespace("spring-k8s") + .withResourceVersion("1") + .build()) + .addToData(Collections.singletonMap("property", "two-from-k8s".getBytes())) + .build(); V1Secret three = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("secret-three").withNamespace("spring-k8s") - .withResourceVersion("1").build()) - .addToData(Collections.singletonMap("property", "three".getBytes())).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("secret-three") + .withNamespace("spring-k8s") + .withResourceVersion("1") + .build()) + .addToData(Collections.singletonMap("property", "three".getBytes())) + .build(); V1Secret threeFromProfile = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("secret-three-k8s").withNamespace("spring-k8s") - .withResourceVersion("1").build()) - .addToData(Collections.singletonMap("property", "three-from-k8s".getBytes())).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("secret-three-k8s") + .withNamespace("spring-k8s") + .withResourceVersion("1") + .build()) + .addToData(Collections.singletonMap("property", "three-from-k8s".getBytes())) + .build(); V1SecretList allSecrets = new V1SecretList(); allSecrets.setItems(Arrays.asList(one, oneWithProfile, two, twoWithProfile, three, threeFromProfile)); // the actual stub for CoreV1Api calls WireMock.stubFor(WireMock.get("/api/v1/namespaces/spring-k8s/secrets") - .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(allSecrets)))); + .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(allSecrets)))); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/SingleSourceMultipleFilesConfigurationStub.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/SingleSourceMultipleFilesConfigurationStub.java index c62d8a0164..69c275a04e 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/SingleSourceMultipleFilesConfigurationStub.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/SingleSourceMultipleFilesConfigurationStub.java @@ -74,15 +74,16 @@ public static void stubData() { one.put("fruit-shape.properties", "shape.when.raw=small-sphere\nshape.when.ripe=bigger-sphere"); V1ConfigMap configMap = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("my-configmap").withNamespace("spring-k8s").build()) - .addToData(one).build(); + .withMetadata(new V1ObjectMetaBuilder().withName("my-configmap").withNamespace("spring-k8s").build()) + .addToData(one) + .build(); V1ConfigMapList allConfigMaps = new V1ConfigMapList(); allConfigMaps.addItemsItem(configMap); // the actual stub for CoreV1Api calls WireMock.stubFor(WireMock.get("/api/v1/namespaces/spring-k8s/configmaps") - .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(allConfigMaps)))); + .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(allConfigMaps)))); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/SourcesOrderConfigurationStub.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/SourcesOrderConfigurationStub.java index 8f04ab4487..3a9873ec72 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/SourcesOrderConfigurationStub.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/bootstrap/stubs/SourcesOrderConfigurationStub.java @@ -70,16 +70,20 @@ public static void stubConfigMapData() { configMapData.put("my.key", "from-configmap"); configMapData.put("my.two", "two"); - V1ConfigMap myConfigMap = new V1ConfigMapBuilder().withMetadata(new V1ObjectMetaBuilder() - .withName("my-configmap").withNamespace("spring-k8s").withResourceVersion("1").build()) - .addToData(configMapData).build(); + V1ConfigMap myConfigMap = new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("my-configmap") + .withNamespace("spring-k8s") + .withResourceVersion("1") + .build()) + .addToData(configMapData) + .build(); V1ConfigMapList allConfigMaps = new V1ConfigMapList(); allConfigMaps.setItems(Collections.singletonList(myConfigMap)); // the actual stub for CoreV1Api calls WireMock.stubFor(WireMock.get("/api/v1/namespaces/spring-k8s/configmaps") - .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(allConfigMaps)))); + .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(allConfigMaps)))); } public static void stubSecretsData() { @@ -88,15 +92,20 @@ public static void stubSecretsData() { secretData.put("my.key", "from-secret".getBytes(StandardCharsets.UTF_8)); secretData.put("my.one", "one".getBytes(StandardCharsets.UTF_8)); - V1Secret mySecret = new V1SecretBuilder().withMetadata(new V1ObjectMetaBuilder().withName("my-secret") - .withNamespace("spring-k8s").withResourceVersion("1").build()).addToData(secretData).build(); + V1Secret mySecret = new V1SecretBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("my-secret") + .withNamespace("spring-k8s") + .withResourceVersion("1") + .build()) + .addToData(secretData) + .build(); V1SecretList allConfigMaps = new V1SecretList(); allConfigMaps.setItems(Collections.singletonList(mySecret)); // the actual stub for CoreV1Api calls WireMock.stubFor(WireMock.get("/api/v1/namespaces/spring-k8s/secrets") - .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(allConfigMaps)))); + .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(allConfigMaps)))); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/configmap_retry/ConfigFailFastDisabled.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/configmap_retry/ConfigFailFastDisabled.java index ddb6ecef7b..d47e9caee7 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/configmap_retry/ConfigFailFastDisabled.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/configmap_retry/ConfigFailFastDisabled.java @@ -62,7 +62,7 @@ static void setup() { clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build()); stubConfigMapAndSecretsDefaults(); } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/configmap_retry/ConfigFailFastEnabledButRetryDisabled.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/configmap_retry/ConfigFailFastEnabledButRetryDisabled.java index ebea1330bd..4237d9df72 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/configmap_retry/ConfigFailFastEnabledButRetryDisabled.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/configmap_retry/ConfigFailFastEnabledButRetryDisabled.java @@ -65,10 +65,10 @@ static void setup() { clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build()); clientUtilsMock - .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("default"); + .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn("default"); stubConfigMapAndSecretsDefaults(); } @@ -102,7 +102,8 @@ void locateShouldFailWithoutRetrying() { assertThat(context.containsBean("kubernetesConfigRetryInterceptor")).isFalse(); assertThatThrownBy(() -> propertySourceLocator.locate(new MockEnvironment())) - .isInstanceOf(IllegalStateException.class).hasMessage("Internal Server Error"); + .isInstanceOf(IllegalStateException.class) + .hasMessage("Internal Server Error"); // verify that propertySourceLocator.locate is called only once verify(propertySourceLocator, times(1)).locate(any()); diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/configmap_retry/ConfigMapEnableRetryWithoutFailFastTest.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/configmap_retry/ConfigMapEnableRetryWithoutFailFastTest.java index ffac804563..d2cff5b8df 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/configmap_retry/ConfigMapEnableRetryWithoutFailFastTest.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/configmap_retry/ConfigMapEnableRetryWithoutFailFastTest.java @@ -79,7 +79,7 @@ public static void setup() { clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build()); stubConfigMapAndSecretsDefaults(); } @@ -87,7 +87,7 @@ private static void stubConfigMapAndSecretsDefaults() { // return empty config map / secret list to not fail context creation stubFor(get(API).willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(new V1ConfigMapList())))); stubFor(get(SECRETS_API) - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(new V1SecretList())))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(new V1SecretList())))); } @AfterAll @@ -108,7 +108,9 @@ protected void setup(String... env) { ConfigurationPropertiesRebinderAutoConfiguration.class, KubernetesClientBootstrapConfiguration.class, KubernetesClientRetryBootstrapConfiguration.class, KubernetesBootstrapConfiguration.class, KubernetesClientConfigReloadAutoConfiguration.class) - .web(org.springframework.boot.WebApplicationType.NONE).properties(envArray).run(); + .web(org.springframework.boot.WebApplicationType.NONE) + .properties(envArray) + .run(); } @AfterEach diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/configmap_retry/ConfigRetryDisabledButSecretsRetryEnabled.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/configmap_retry/ConfigRetryDisabledButSecretsRetryEnabled.java index f5fbe2036f..191fd726c9 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/configmap_retry/ConfigRetryDisabledButSecretsRetryEnabled.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/configmap_retry/ConfigRetryDisabledButSecretsRetryEnabled.java @@ -67,10 +67,10 @@ static void setup() { clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build()); clientUtilsMock - .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("default"); + .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn("default"); stubConfigMapAndSecretsDefaults(); } @@ -78,7 +78,7 @@ private static void stubConfigMapAndSecretsDefaults() { // return empty config map / secret list to not fail context creation stubFor(get(API).willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(new V1ConfigMapList())))); stubFor(get(SECRETS_API) - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(new V1SecretList())))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(new V1SecretList())))); } @AfterAll @@ -114,7 +114,8 @@ void locateShouldFailWithoutRetrying() { // TODO not in bootstrap // assertThat(context.containsBean("kubernetesConfigRetryInterceptor")).isTrue(); assertThatThrownBy(() -> propertySourceLocator.locate(new MockEnvironment())) - .isInstanceOf(IllegalStateException.class).hasMessage("Internal Server Error"); + .isInstanceOf(IllegalStateException.class) + .hasMessage("Internal Server Error"); // verify that propertySourceLocator.locate is called only once verify(propertySourceLocator, times(1)).locate(any()); diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/configmap_retry/ConfigRetryEnabled.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/configmap_retry/ConfigRetryEnabled.java index c638853f33..0fb14bd07f 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/configmap_retry/ConfigRetryEnabled.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/configmap_retry/ConfigRetryEnabled.java @@ -71,10 +71,10 @@ static void setup() { clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build()); clientUtilsMock - .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("default"); + .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn("default"); stubConfigMapAndSecretsDefaults(); } @@ -106,12 +106,12 @@ void locateShouldNotRetryWhenThereIsNoFailure() { data.put("some.number", "0"); V1ConfigMapList configMapList = new V1ConfigMapList() - .addItemsItem(new V1ConfigMap().metadata(new V1ObjectMeta().name("application")).data(data)); + .addItemsItem(new V1ConfigMap().metadata(new V1ObjectMeta().name("application")).data(data)); stubFor(get(API).willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(configMapList)))); PropertySource propertySource = Assertions - .assertDoesNotThrow(() -> propertySourceLocator.locate(new MockEnvironment())); + .assertDoesNotThrow(() -> propertySourceLocator.locate(new MockEnvironment())); // verify locate is called only once WireMock.verify(1, getRequestedFor(urlEqualTo(API))); @@ -129,24 +129,31 @@ void locateShouldRetryAndRecover() { data.put("some.number", "0"); V1ConfigMapList configMapList = new V1ConfigMapList() - .addItemsItem(new V1ConfigMap().metadata(new V1ObjectMeta().name("application")).data(data)); + .addItemsItem(new V1ConfigMap().metadata(new V1ObjectMeta().name("application")).data(data)); // fail 3 times - stubFor(get(API).inScenario("Retry and Recover").whenScenarioStateIs(STARTED) - .willReturn(aResponse().withStatus(500)).willSetStateTo("Failed once")); + stubFor(get(API).inScenario("Retry and Recover") + .whenScenarioStateIs(STARTED) + .willReturn(aResponse().withStatus(500)) + .willSetStateTo("Failed once")); - stubFor(get(API).inScenario("Retry and Recover").whenScenarioStateIs("Failed once") - .willReturn(aResponse().withStatus(500)).willSetStateTo("Failed twice")); + stubFor(get(API).inScenario("Retry and Recover") + .whenScenarioStateIs("Failed once") + .willReturn(aResponse().withStatus(500)) + .willSetStateTo("Failed twice")); - stubFor(get(API).inScenario("Retry and Recover").whenScenarioStateIs("Failed twice") - .willReturn(aResponse().withStatus(500)).willSetStateTo("Failed thrice")); + stubFor(get(API).inScenario("Retry and Recover") + .whenScenarioStateIs("Failed twice") + .willReturn(aResponse().withStatus(500)) + .willSetStateTo("Failed thrice")); // then succeed - stubFor(get(API).inScenario("Retry and Recover").whenScenarioStateIs("Failed thrice") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(configMapList)))); + stubFor(get(API).inScenario("Retry and Recover") + .whenScenarioStateIs("Failed thrice") + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(configMapList)))); PropertySource propertySource = Assertions - .assertDoesNotThrow(() -> propertySourceLocator.locate(new MockEnvironment())); + .assertDoesNotThrow(() -> propertySourceLocator.locate(new MockEnvironment())); // verify the request was retried 4 times, 5 total request WireMock.verify(5, getRequestedFor(urlEqualTo(API))); @@ -163,7 +170,8 @@ void locateShouldRetryAndFail() { stubFor(get(API).willReturn(aResponse().withStatus(500).withBody("Internal Server Error"))); assertThatThrownBy(() -> propertySourceLocator.locate(new MockEnvironment())) - .isInstanceOf(IllegalStateException.class).hasMessage("Internal Server Error"); + .isInstanceOf(IllegalStateException.class) + .hasMessage("Internal Server Error"); // verify the request was retried 5 times WireMock.verify(5, getRequestedFor(urlEqualTo(API))); diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/reload/KubernetesClientEventBasedConfigMapChangeDetectorTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/reload/KubernetesClientEventBasedConfigMapChangeDetectorTests.java index f4d3449c6c..5a86dbdbf0 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/reload/KubernetesClientEventBasedConfigMapChangeDetectorTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/reload/KubernetesClientEventBasedConfigMapChangeDetectorTests.java @@ -95,7 +95,7 @@ public void afterEach() { void watch() { GsonBuilder builder = new GsonBuilder(); builder.excludeFieldsWithModifiers(Modifier.STATIC, Modifier.TRANSIENT, Modifier.VOLATILE) - .registerTypeAdapter(OffsetDateTime.class, new GsonOffsetDateTimeAdapter()); + .registerTypeAdapter(OffsetDateTime.class, new GsonOffsetDateTimeAdapter()); Gson gson = builder.create(); Map data = new HashMap<>(); @@ -105,41 +105,50 @@ void watch() { updateData.put("application.properties", "spring.cloud.kubernetes.configuration.watcher.refreshDelay=1\n" + "logging.level.org.springframework.cloud.kubernetes=TRACE"); V1ConfigMap applicationConfig = new V1ConfigMap().kind("ConfigMap") - .metadata(new V1ObjectMeta().namespace("default").name("bar1")).data(data); + .metadata(new V1ObjectMeta().namespace("default").name("bar1")) + .data(data); V1ConfigMapList configMapList = new V1ConfigMapList().metadata(new V1ListMeta().resourceVersion("0")) - .items(List.of(applicationConfig)); + .items(List.of(applicationConfig)); stubFor(get(urlMatching("^/api/v1/namespaces/default/configmaps.*")).inScenario("watch") - .whenScenarioStateIs(STARTED).withQueryParam("watch", equalTo("false")) - .willReturn(aResponse().withStatus(200).withBody(gson.toJson(configMapList))).willSetStateTo("update")); - - Watch.Response watchResponse = new Watch.Response<>(EventType.MODIFIED.name(), new V1ConfigMap() - .kind("ConfigMap").metadata(new V1ObjectMeta().namespace("default").name("bar1")).data(updateData)); + .whenScenarioStateIs(STARTED) + .withQueryParam("watch", equalTo("false")) + .willReturn(aResponse().withStatus(200).withBody(gson.toJson(configMapList))) + .willSetStateTo("update")); + + Watch.Response watchResponse = new Watch.Response<>(EventType.MODIFIED.name(), + new V1ConfigMap().kind("ConfigMap") + .metadata(new V1ObjectMeta().namespace("default").name("bar1")) + .data(updateData)); stubFor(get(urlMatching("^/api/v1/namespaces/default/configmaps.*")).inScenario("watch") - .whenScenarioStateIs("update").withQueryParam("watch", equalTo("true")) - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(watchResponse))) - .willSetStateTo("add")); + .whenScenarioStateIs("update") + .withQueryParam("watch", equalTo("true")) + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(watchResponse))) + .willSetStateTo("add")); stubFor(get(urlMatching("^/api/v1/namespaces/default/configmaps.*")).inScenario("watch") - .whenScenarioStateIs("add").withQueryParam("watch", equalTo("true")) - .willReturn(aResponse().withStatus(200) - .withBody(new JSON().serialize(new Watch.Response<>(EventType.ADDED.name(), - new V1ConfigMap().kind("ConfigMap") - .metadata(new V1ObjectMeta().namespace("default").name("bar3")) - .putDataItem("application.properties", "debug=true"))))) - .willSetStateTo("delete")); + .whenScenarioStateIs("add") + .withQueryParam("watch", equalTo("true")) + .willReturn(aResponse().withStatus(200) + .withBody(new JSON().serialize(new Watch.Response<>(EventType.ADDED.name(), + new V1ConfigMap().kind("ConfigMap") + .metadata(new V1ObjectMeta().namespace("default").name("bar3")) + .putDataItem("application.properties", "debug=true"))))) + .willSetStateTo("delete")); stubFor(get(urlMatching("^/api/v1/namespaces/default/configmaps.*")).inScenario("watch") - .whenScenarioStateIs("delete").withQueryParam("watch", equalTo("true")) - .willReturn(aResponse().withStatus(200) - .withBody(new JSON().serialize(new Watch.Response<>(EventType.DELETED.name(), - new V1ConfigMap().kind("ConfigMap") - .metadata(new V1ObjectMeta().namespace("default").name("bar1")) - .putDataItem("application.properties", "debug=true"))))) - .willSetStateTo("done")); + .whenScenarioStateIs("delete") + .withQueryParam("watch", equalTo("true")) + .willReturn(aResponse().withStatus(200) + .withBody(new JSON().serialize(new Watch.Response<>(EventType.DELETED.name(), + new V1ConfigMap().kind("ConfigMap") + .metadata(new V1ObjectMeta().namespace("default").name("bar1")) + .putDataItem("application.properties", "debug=true"))))) + .willSetStateTo("done")); stubFor(get(urlMatching("^/api/v1/namespaces/default/configmaps.*")).inScenario("watch") - .whenScenarioStateIs("done").withQueryParam("watch", equalTo("true")) - .willReturn(aResponse().withStatus(200))); + .whenScenarioStateIs("done") + .withQueryParam("watch", equalTo("true")) + .willReturn(aResponse().withStatus(200))); ApiClient apiClient = new ClientBuilder().setBasePath("http://localhost:" + wireMockServer.port()).build(); OkHttpClient httpClient = apiClient.getHttpClient().newBuilder().readTimeout(0, TimeUnit.SECONDS).build(); apiClient.setHttpClient(httpClient); @@ -152,7 +161,8 @@ void watch() { ConfigurationUpdateStrategy strategy = new ConfigurationUpdateStrategy("strategy", run); KubernetesMockEnvironment environment = new KubernetesMockEnvironment( - mock(KubernetesClientConfigMapPropertySource.class)).withProperty("debug", "true"); + mock(KubernetesClientConfigMapPropertySource.class)) + .withProperty("debug", "true"); KubernetesClientConfigMapPropertySourceLocator locator = mock( KubernetesClientConfigMapPropertySourceLocator.class); when(locator.locate(environment)).thenAnswer(x -> new MockPropertySource().withProperty("debug", "false")); diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/reload/KubernetesClientEventBasedSecretsChangeDetectorTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/reload/KubernetesClientEventBasedSecretsChangeDetectorTests.java index 98bfef6cf1..b38e49f90c 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/reload/KubernetesClientEventBasedSecretsChangeDetectorTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/reload/KubernetesClientEventBasedSecretsChangeDetectorTests.java @@ -96,48 +96,54 @@ public void afterEach() { void watch() { V1Secret dbPassword = new V1Secret().metadata(new V1ObjectMeta().name("db-password")) - .putStringDataItem("password", Base64.getEncoder().encodeToString("p455w0rd".getBytes())) - .putDataItem("password", Base64.getEncoder().encode("p455w0rd".getBytes())) - .putStringDataItem("username", Base64.getEncoder().encodeToString("user".getBytes())) - .putDataItem("username", Base64.getEncoder().encode("user".getBytes())); + .putStringDataItem("password", Base64.getEncoder().encodeToString("p455w0rd".getBytes())) + .putDataItem("password", Base64.getEncoder().encode("p455w0rd".getBytes())) + .putStringDataItem("username", Base64.getEncoder().encodeToString("user".getBytes())) + .putDataItem("username", Base64.getEncoder().encode("user".getBytes())); V1SecretList secretList = new V1SecretList().metadata(new V1ListMeta().resourceVersion("0")) - .items(List.of(dbPassword)); + .items(List.of(dbPassword)); V1Secret dbPasswordUpdated = new V1Secret().metadata(new V1ObjectMeta().name("db-password")) - .putStringDataItem("password", Base64.getEncoder().encodeToString("p455w0rd2".getBytes())) - .putDataItem("password", Base64.getEncoder().encode("p455w0rd2".getBytes())) - .putStringDataItem("username", Base64.getEncoder().encodeToString("user".getBytes())) - .putDataItem("username", Base64.getEncoder().encode("user".getBytes())); + .putStringDataItem("password", Base64.getEncoder().encodeToString("p455w0rd2".getBytes())) + .putDataItem("password", Base64.getEncoder().encode("p455w0rd2".getBytes())) + .putStringDataItem("username", Base64.getEncoder().encodeToString("user".getBytes())) + .putDataItem("username", Base64.getEncoder().encode("user".getBytes())); Watch.Response watchResponse = new Watch.Response<>(EventType.MODIFIED.name(), dbPasswordUpdated); stubFor(get(urlMatching("/api/v1/namespaces/default/secrets.*")).inScenario(SCENARIO) - .whenScenarioStateIs(STARTED).withQueryParams(WATCH_FALSE) - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(secretList))) - .willSetStateTo("update")); + .whenScenarioStateIs(STARTED) + .withQueryParams(WATCH_FALSE) + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(secretList))) + .willSetStateTo("update")); stubFor(get(urlMatching("/api/v1/namespaces/default/secrets.*")).inScenario(SCENARIO) - .whenScenarioStateIs("update").withQueryParams(WATCH_TRUE) - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(watchResponse))) - .willSetStateTo("add")); - - stubFor(get(urlMatching("/api/v1/namespaces/default/secrets.*")).inScenario(SCENARIO).whenScenarioStateIs("add") - .withQueryParams(WATCH_TRUE) - .willReturn(aResponse().withStatus(200) - .withBody(new JSON().serialize(new Watch.Response<>(EventType.ADDED.name(), - new V1Secret().metadata(new V1ObjectMeta().name("rabbit-password")) - .putDataItem("rabbit-pw", Base64.getEncoder().encode("password".getBytes())))))) - .willSetStateTo("delete")); + .whenScenarioStateIs("update") + .withQueryParams(WATCH_TRUE) + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(watchResponse))) + .willSetStateTo("add")); stubFor(get(urlMatching("/api/v1/namespaces/default/secrets.*")).inScenario(SCENARIO) - .whenScenarioStateIs("delete").withQueryParams(WATCH_TRUE) - .willReturn(aResponse().withStatus(200) - .withBody(new JSON().serialize(new Watch.Response<>(EventType.DELETED.name(), - new V1Secret().metadata(new V1ObjectMeta().name("rabbit-password")) - .putDataItem("rabbit-pw", Base64.getEncoder().encode("password".getBytes())))))) - .willSetStateTo("done")); + .whenScenarioStateIs("add") + .withQueryParams(WATCH_TRUE) + .willReturn(aResponse().withStatus(200) + .withBody(new JSON().serialize(new Watch.Response<>(EventType.ADDED.name(), + new V1Secret().metadata(new V1ObjectMeta().name("rabbit-password")) + .putDataItem("rabbit-pw", Base64.getEncoder().encode("password".getBytes())))))) + .willSetStateTo("delete")); - stubFor(get(urlMatching("/api/v1/namespaces/default/secrets.*")).inScenario("watch").whenScenarioStateIs("done") - .withQueryParam("watch", equalTo("true")).willReturn(aResponse().withStatus(200))); + stubFor(get(urlMatching("/api/v1/namespaces/default/secrets.*")).inScenario(SCENARIO) + .whenScenarioStateIs("delete") + .withQueryParams(WATCH_TRUE) + .willReturn(aResponse().withStatus(200) + .withBody(new JSON().serialize(new Watch.Response<>(EventType.DELETED.name(), + new V1Secret().metadata(new V1ObjectMeta().name("rabbit-password")) + .putDataItem("rabbit-pw", Base64.getEncoder().encode("password".getBytes())))))) + .willSetStateTo("done")); + + stubFor(get(urlMatching("/api/v1/namespaces/default/secrets.*")).inScenario("watch") + .whenScenarioStateIs("done") + .withQueryParam("watch", equalTo("true")) + .willReturn(aResponse().withStatus(200))); ApiClient apiClient = new ClientBuilder().setBasePath("http://localhost:" + wireMockServer.port()).build(); OkHttpClient httpClient = apiClient.getHttpClient().newBuilder().readTimeout(0, TimeUnit.SECONDS).build(); @@ -151,10 +157,11 @@ void watch() { ConfigurationUpdateStrategy strategy = new ConfigurationUpdateStrategy("strategy", run); KubernetesMockEnvironment environment = new KubernetesMockEnvironment( - mock(KubernetesClientSecretsPropertySource.class)).withProperty("db-password", "p455w0rd"); + mock(KubernetesClientSecretsPropertySource.class)) + .withProperty("db-password", "p455w0rd"); KubernetesClientSecretsPropertySourceLocator locator = mock(KubernetesClientSecretsPropertySourceLocator.class); when(locator.locate(environment)) - .thenAnswer(ignoreMe -> new MockPropertySource().withProperty("db-password", "p455w0rd2")); + .thenAnswer(ignoreMe -> new MockPropertySource().withProperty("db-password", "p455w0rd2")); ConfigReloadProperties properties = new ConfigReloadProperties(false, false, true, ConfigReloadProperties.ReloadStrategy.REFRESH, ConfigReloadProperties.ReloadDetectionMode.EVENT, Duration.ofMillis(15000), Set.of(), false, Duration.ofSeconds(2)); diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/sanitize_secrets/BootstrapKubernetesClientSanitizeConfigpropsEndpointTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/sanitize_secrets/BootstrapKubernetesClientSanitizeConfigpropsEndpointTests.java index 585747b5a5..d5f7c60def 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/sanitize_secrets/BootstrapKubernetesClientSanitizeConfigpropsEndpointTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/sanitize_secrets/BootstrapKubernetesClientSanitizeConfigpropsEndpointTests.java @@ -47,24 +47,42 @@ class DefaultSettingsTest { @Test void test() { // configmap is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectBody() - .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeConfigMapName") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectBody() + .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeConfigMapName") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectBody() - .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeSecretName") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectBody() + .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeSecretName") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -87,24 +105,46 @@ class ExplicitNever { @Test void test() { // configmap is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeConfigMapName") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeConfigMapName") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeSecretName") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeSecretName") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -137,24 +177,46 @@ class AlwaysWithoutSanitizingFunction { @Test void test() { // configmap is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeConfigMapName") - .isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeConfigMapName") + .isEqualTo("sanitizeConfigMapValue"); // secret is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeSecretName") - .isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeSecretName") + .isEqualTo("sanitizeSecretValue"); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -187,30 +249,57 @@ class AlwaysWithSanitizingFunction { @Test void test() { // configmap is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeConfigMapName") - .isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeConfigMapName") + .isEqualTo("sanitizeConfigMapValue"); // first secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeSecretName") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeSecretName") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // second secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeSecretNameTwo") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeSecretNameTwo") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/sanitize_secrets/BootstrapKubernetesClientSanitizeEnvEndpointTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/sanitize_secrets/BootstrapKubernetesClientSanitizeEnvEndpointTests.java index 98fca219b4..5767a2e3ef 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/sanitize_secrets/BootstrapKubernetesClientSanitizeEnvEndpointTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/sanitize_secrets/BootstrapKubernetesClientSanitizeEnvEndpointTests.java @@ -47,24 +47,46 @@ class DefaultSettingsTest { @Test void test() { // configmap is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -87,24 +109,46 @@ class ExplicitNever { @Test void test() { // configmap is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -136,24 +180,46 @@ class AlwaysWithoutSanitizingFunction { @Test void test() { // configmap is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") - .isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") + .isEqualTo("sanitizeConfigMapValue"); // secret is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") - .isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") + .isEqualTo("sanitizeSecretValue"); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -185,30 +251,57 @@ class AlwaysWithSanitizingFunction { @Test void test() { // configmap is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") - .isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") + .isEqualTo("sanitizeConfigMapValue"); // first secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // second secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretNameTwo'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretNameTwo'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/sanitize_secrets/ConfigDataFabric8ConfigpropsEndpointTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/sanitize_secrets/ConfigDataFabric8ConfigpropsEndpointTests.java index c1100c04ce..c3c93fd4bd 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/sanitize_secrets/ConfigDataFabric8ConfigpropsEndpointTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/sanitize_secrets/ConfigDataFabric8ConfigpropsEndpointTests.java @@ -46,24 +46,42 @@ class DefaultSettingsTest extends ConfigDataSanitize { @Test void test() { // configmap is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectBody() - .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeConfigMapName") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectBody() + .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeConfigMapName") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectBody() - .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeSecretName") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectBody() + .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeSecretName") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -85,24 +103,46 @@ class ExplicitNever extends ConfigDataSanitize { @Test void test() { // configmap is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeConfigMapName") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeConfigMapName") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeSecretName") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeSecretName") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -134,24 +174,46 @@ class AlwaysWithoutSanitizingFunction extends ConfigDataSanitize { @Test void test() { // configmap is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeConfigMapName") - .isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeConfigMapName") + .isEqualTo("sanitizeConfigMapValue"); // secret is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeSecretName") - .isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeSecretName") + .isEqualTo("sanitizeSecretValue"); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -183,30 +245,57 @@ class AlwaysWithSanitizingFunction extends ConfigDataSanitize { @Test void test() { // configmap is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeConfigMapName") - .isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeConfigMapName") + .isEqualTo("sanitizeConfigMapValue"); // first secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeSecretName") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeSecretName") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // second secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeSecretNameTwo") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeSecretNameTwo") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/sanitize_secrets/ConfigDataKubernetesClientSanitizeEnvEndpointTests.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/sanitize_secrets/ConfigDataKubernetesClientSanitizeEnvEndpointTests.java index 07156c3f1f..7fe21345fa 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/sanitize_secrets/ConfigDataKubernetesClientSanitizeEnvEndpointTests.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/sanitize_secrets/ConfigDataKubernetesClientSanitizeEnvEndpointTests.java @@ -47,24 +47,46 @@ class DefaultSettingsTest extends ConfigDataSanitize { @Test void test() { // configmap is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -86,24 +108,46 @@ class ExplicitNever extends ConfigDataSanitize { @Test void test() { // configmap is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -135,24 +179,46 @@ class AlwaysWithoutSanitizingFunction extends ConfigDataSanitize { @Test void test() { // configmap is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") - .isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") + .isEqualTo("sanitizeConfigMapValue"); // secret is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") - .isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") + .isEqualTo("sanitizeSecretValue"); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -184,30 +250,57 @@ class AlwaysWithSanitizingFunction extends ConfigDataSanitize { @Test void test() { // configmap is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") - .isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") + .isEqualTo("sanitizeConfigMapValue"); // first secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // second secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretNameTwo'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretNameTwo'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/sanitize_secrets/ConfigDataSanitize.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/sanitize_secrets/ConfigDataSanitize.java index 974e5ae181..b7235bae3c 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/sanitize_secrets/ConfigDataSanitize.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/sanitize_secrets/ConfigDataSanitize.java @@ -44,10 +44,10 @@ static void wireMock() { WireMock.configureFor("localhost", server.port()); clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(server.baseUrl()).build()); clientUtilsMock - .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("test"); + .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn("test"); stubData(); } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/secrets_retry/SecretsEnableRetryWithoutFailFastTest.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/secrets_retry/SecretsEnableRetryWithoutFailFastTest.java index e0312b4892..8472a4bf25 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/secrets_retry/SecretsEnableRetryWithoutFailFastTest.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/secrets_retry/SecretsEnableRetryWithoutFailFastTest.java @@ -79,7 +79,7 @@ public static void setup() { clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build()); stubConfigMapAndSecretsDefaults(); } @@ -87,7 +87,7 @@ private static void stubConfigMapAndSecretsDefaults() { // return empty config map / secret list to not fail context creation stubFor(get(API).willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(new V1ConfigMapList())))); stubFor(get(SECRETS_API) - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(new V1SecretList())))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(new V1SecretList())))); } @AfterAll @@ -108,7 +108,9 @@ protected void setup(String... env) { ConfigurationPropertiesRebinderAutoConfiguration.class, KubernetesClientBootstrapConfiguration.class, KubernetesClientRetryBootstrapConfiguration.class, KubernetesBootstrapConfiguration.class, KubernetesClientConfigReloadAutoConfiguration.class) - .web(org.springframework.boot.WebApplicationType.NONE).properties(envArray).run(); + .web(org.springframework.boot.WebApplicationType.NONE) + .properties(envArray) + .run(); } @AfterEach diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/secrets_retry/SecretsFailFastDisabled.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/secrets_retry/SecretsFailFastDisabled.java index dd23fe1a53..393273602b 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/secrets_retry/SecretsFailFastDisabled.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/secrets_retry/SecretsFailFastDisabled.java @@ -68,7 +68,7 @@ static void setup() { clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build()); stubConfigMapAndSecretsDefaults(); } diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/secrets_retry/SecretsFailFastEnabledButRetryDisabled.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/secrets_retry/SecretsFailFastEnabledButRetryDisabled.java index b536c300f5..cb8f3109f8 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/secrets_retry/SecretsFailFastEnabledButRetryDisabled.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/secrets_retry/SecretsFailFastEnabledButRetryDisabled.java @@ -75,10 +75,10 @@ static void setup() { clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build()); clientUtilsMock - .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("default"); + .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn("default"); stubConfigMapAndSecretsDefaults(); } @@ -86,7 +86,7 @@ private static void stubConfigMapAndSecretsDefaults() { // return empty config map / secret list to not fail context creation stubFor(get(API).willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(new V1SecretList())))); stubFor(get(CONFIG_MAPS_API) - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(new V1ConfigMapList())))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(new V1ConfigMapList())))); } @AfterAll @@ -114,7 +114,8 @@ void locateShouldFailWithoutRetrying() { assertThat(context.containsBean("kubernetesSecretsRetryInterceptor")).isFalse(); assertThatThrownBy(() -> propertySourceLocator.locate(new MockEnvironment())) - .isInstanceOf(IllegalStateException.class).hasMessage("Internal Server Error"); + .isInstanceOf(IllegalStateException.class) + .hasMessage("Internal Server Error"); // verify that propertySourceLocator.locate is called only once verify(propertySourceLocator, times(1)).locate(any()); diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/secrets_retry/SecretsRetryDisabledButConfigRetryEnabled.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/secrets_retry/SecretsRetryDisabledButConfigRetryEnabled.java index 1791fef951..773aae0572 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/secrets_retry/SecretsRetryDisabledButConfigRetryEnabled.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/secrets_retry/SecretsRetryDisabledButConfigRetryEnabled.java @@ -74,10 +74,10 @@ static void setup() { clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build()); clientUtilsMock - .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("default"); + .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn("default"); stubConfigMapAndSecretsDefaults(); } @@ -85,7 +85,7 @@ private static void stubConfigMapAndSecretsDefaults() { // return empty config map / secret list to not fail context creation stubFor(get(API).willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(new V1SecretList())))); stubFor(get(CONFIG_MAPS_API) - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(new V1ConfigMapList())))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(new V1ConfigMapList())))); } @AfterAll @@ -121,7 +121,8 @@ void locateShouldFailWithoutRetrying() { // TODO not in bootstrap // assertThat(context.containsBean("kubernetesSecretsRetryInterceptor")).isTrue(); assertThatThrownBy(() -> propertySourceLocator.locate(new MockEnvironment())) - .isInstanceOf(IllegalStateException.class).hasMessage("Internal Server Error"); + .isInstanceOf(IllegalStateException.class) + .hasMessage("Internal Server Error"); // verify that propertySourceLocator.locate is called only once verify(propertySourceLocator, times(1)).locate(any()); diff --git a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/secrets_retry/SecretsRetryEnabled.java b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/secrets_retry/SecretsRetryEnabled.java index bda4f7b481..160741c5c4 100644 --- a/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/secrets_retry/SecretsRetryEnabled.java +++ b/spring-cloud-kubernetes-client-config/src/test/java/org/springframework/cloud/kubernetes/client/config/secrets_retry/SecretsRetryEnabled.java @@ -78,10 +78,10 @@ static void setup() { clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build()); clientUtilsMock - .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("default"); + .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn("default"); stubConfigMapAndSecretsDefaults(); } @@ -113,12 +113,12 @@ void locateShouldNotRetryWhenThereIsNoFailure() { data.put("some.sensitive.number", "1".getBytes()); V1SecretList secretList = new V1SecretList() - .addItemsItem(new V1Secret().metadata(new V1ObjectMeta().name("my-secret")).data(data)); + .addItemsItem(new V1Secret().metadata(new V1ObjectMeta().name("my-secret")).data(data)); stubFor(get(API).willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(secretList)))); PropertySource propertySource = Assertions - .assertDoesNotThrow(() -> propertySourceLocator.locate(new MockEnvironment())); + .assertDoesNotThrow(() -> propertySourceLocator.locate(new MockEnvironment())); // verify locate is called only once WireMock.verify(1, getRequestedFor(urlEqualTo(API))); @@ -136,24 +136,31 @@ void locateShouldRetryAndRecover() { data.put("some.sensitive.number", "1".getBytes()); V1SecretList secretList = new V1SecretList() - .addItemsItem(new V1Secret().metadata(new V1ObjectMeta().name("my-secret")).data(data)); + .addItemsItem(new V1Secret().metadata(new V1ObjectMeta().name("my-secret")).data(data)); // fail 3 times - stubFor(get(API).inScenario("Retry and Recover").whenScenarioStateIs(STARTED) - .willReturn(aResponse().withStatus(500)).willSetStateTo("Failed once")); + stubFor(get(API).inScenario("Retry and Recover") + .whenScenarioStateIs(STARTED) + .willReturn(aResponse().withStatus(500)) + .willSetStateTo("Failed once")); - stubFor(get(API).inScenario("Retry and Recover").whenScenarioStateIs("Failed once") - .willReturn(aResponse().withStatus(500)).willSetStateTo("Failed twice")); + stubFor(get(API).inScenario("Retry and Recover") + .whenScenarioStateIs("Failed once") + .willReturn(aResponse().withStatus(500)) + .willSetStateTo("Failed twice")); - stubFor(get(API).inScenario("Retry and Recover").whenScenarioStateIs("Failed twice") - .willReturn(aResponse().withStatus(500)).willSetStateTo("Failed thrice")); + stubFor(get(API).inScenario("Retry and Recover") + .whenScenarioStateIs("Failed twice") + .willReturn(aResponse().withStatus(500)) + .willSetStateTo("Failed thrice")); // then succeed - stubFor(get(API).inScenario("Retry and Recover").whenScenarioStateIs("Failed thrice") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(secretList)))); + stubFor(get(API).inScenario("Retry and Recover") + .whenScenarioStateIs("Failed thrice") + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(secretList)))); PropertySource propertySource = Assertions - .assertDoesNotThrow(() -> propertySourceLocator.locate(new MockEnvironment())); + .assertDoesNotThrow(() -> propertySourceLocator.locate(new MockEnvironment())); // verify retried 4 times WireMock.verify(4, getRequestedFor(urlEqualTo(API))); @@ -170,7 +177,8 @@ void locateShouldRetryAndFail() { stubFor(get(API).willReturn(aResponse().withStatus(500).withBody("Internal Server Error"))); assertThatThrownBy(() -> propertySourceLocator.locate(new MockEnvironment())) - .isInstanceOf(IllegalStateException.class).hasMessage("Internal Server Error"); + .isInstanceOf(IllegalStateException.class) + .hasMessage("Internal Server Error"); // verify retried 5 times until failure WireMock.verify(5, getRequestedFor(urlEqualTo(API))); diff --git a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/ConditionalOnBlockingOrReactiveEnabled.java b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/ConditionalOnBlockingOrReactiveEnabled.java index 1d53204690..260db6ccb8 100644 --- a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/ConditionalOnBlockingOrReactiveEnabled.java +++ b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/ConditionalOnBlockingOrReactiveEnabled.java @@ -33,8 +33,8 @@ * Conditional that is resolved to active when either * {@link ConditionalOnBlockingDiscoveryEnabled} or * {@link ConditionalOnReactiveDiscoveryEnabled} matches. - * @deprecated in favor of {@link ConditionalOnBlockingOrReactiveDiscoveryEnabled} * + * @deprecated in favor of {@link ConditionalOnBlockingOrReactiveDiscoveryEnabled} * @author wind57 */ @Target({ ElementType.TYPE, ElementType.METHOD }) diff --git a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/ConditionalOnSelectiveNamespacesMissing.java b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/ConditionalOnSelectiveNamespacesMissing.java index 5f1815d0b1..5d21e0ff8f 100644 --- a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/ConditionalOnSelectiveNamespacesMissing.java +++ b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/ConditionalOnSelectiveNamespacesMissing.java @@ -42,7 +42,8 @@ public final class ConditionalOnSelectiveNamespacesMissing implements Configurat public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { Set selectiveNamespaces = Binder.get(context.getEnvironment()) - .bind("spring.cloud.kubernetes.discovery.namespaces", Bindable.setOf(String.class)).orElse(Set.of()); + .bind("spring.cloud.kubernetes.discovery.namespaces", Bindable.setOf(String.class)) + .orElse(Set.of()); boolean selectiveNamespacesMissing = selectiveNamespaces.isEmpty(); if (selectiveNamespacesMissing) { LOG.debug(() -> "selective namespaces not present"); diff --git a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/ConditionalOnSelectiveNamespacesPresent.java b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/ConditionalOnSelectiveNamespacesPresent.java index 6832287d74..118ab0dff5 100644 --- a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/ConditionalOnSelectiveNamespacesPresent.java +++ b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/ConditionalOnSelectiveNamespacesPresent.java @@ -42,7 +42,8 @@ public final class ConditionalOnSelectiveNamespacesPresent implements Configurat public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { Set selectiveNamespaces = Binder.get(context.getEnvironment()) - .bind("spring.cloud.kubernetes.discovery.namespaces", Bindable.setOf(String.class)).orElse(Set.of()); + .bind("spring.cloud.kubernetes.discovery.namespaces", Bindable.setOf(String.class)) + .orElse(Set.of()); boolean selectiveNamespacesPresent = !selectiveNamespaces.isEmpty(); if (selectiveNamespacesPresent) { LOG.debug(() -> "found selective namespaces : " + selectiveNamespaces.stream().sorted().toList()); diff --git a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/K8sInstanceIdHostPodNameSupplier.java b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/K8sInstanceIdHostPodNameSupplier.java index 49628ebd71..6ede548506 100644 --- a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/K8sInstanceIdHostPodNameSupplier.java +++ b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/K8sInstanceIdHostPodNameSupplier.java @@ -60,19 +60,24 @@ static K8sInstanceIdHostPodNameSupplier externalName(V1Service service) { // instanceId is usually the pod-uid as seen in the .metadata.uid private String instanceId() { - return Optional.ofNullable(endpointAddress).map(V1EndpointAddress::getTargetRef).map(V1ObjectReference::getUid) - .orElseGet(() -> service.getMetadata().getUid()); + return Optional.ofNullable(endpointAddress) + .map(V1EndpointAddress::getTargetRef) + .map(V1ObjectReference::getUid) + .orElseGet(() -> service.getMetadata().getUid()); } private String host() { - return Optional.ofNullable(endpointAddress).map(V1EndpointAddress::getIp) - .orElseGet(() -> service.getSpec().getExternalName()); + return Optional.ofNullable(endpointAddress) + .map(V1EndpointAddress::getIp) + .orElseGet(() -> service.getSpec().getExternalName()); } private String podName() { - return Optional.ofNullable(endpointAddress).map(V1EndpointAddress::getTargetRef) - .filter(objectReference -> "Pod".equals(objectReference.getKind())).map(V1ObjectReference::getName) - .orElse(null); + return Optional.ofNullable(endpointAddress) + .map(V1EndpointAddress::getTargetRef) + .filter(objectReference -> "Pod".equals(objectReference.getKind())) + .map(V1ObjectReference::getName) + .orElse(null); } } diff --git a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/K8sPodLabelsAndAnnotationsSupplier.java b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/K8sPodLabelsAndAnnotationsSupplier.java index 21c32f8f8a..0101a61454 100644 --- a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/K8sPodLabelsAndAnnotationsSupplier.java +++ b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/K8sPodLabelsAndAnnotationsSupplier.java @@ -66,7 +66,7 @@ public PodLabelsAndAnnotations apply(String podName) { try { objectMeta = Optional.ofNullable(coreV1Api.readNamespacedPod(podName, namespace, null).getMetadata()) - .orElse(new V1ObjectMetaBuilder().withLabels(Map.of()).withAnnotations(Map.of()).build()); + .orElse(new V1ObjectMetaBuilder().withLabels(Map.of()).withAnnotations(Map.of()).build()); } catch (ApiException e) { LOG.warn(e, "Could not get pod metadata"); diff --git a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesClientConfigServerBootstrapper.java b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesClientConfigServerBootstrapper.java index 43db30536b..94c2ef0540 100644 --- a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesClientConfigServerBootstrapper.java +++ b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesClientConfigServerBootstrapper.java @@ -81,19 +81,19 @@ public void initialize(BootstrapRegistry registry) { ApiClient apiClient = context.getOrElseSupply(ApiClient.class, () -> defaultApiClient); KubernetesNamespaceProvider kubernetesNamespaceProvider = clientAutoConfiguration - .kubernetesNamespaceProvider(getNamespaceEnvironment(propertyResolver)); + .kubernetesNamespaceProvider(getNamespaceEnvironment(propertyResolver)); KubernetesDiscoveryProperties discoveryProperties = context.get(KubernetesDiscoveryProperties.class); String namespace = getInformerNamespace(kubernetesNamespaceProvider, discoveryProperties); SharedInformerFactory sharedInformerFactory = new SharedInformerFactory(apiClient); GenericKubernetesApi servicesApi = new GenericKubernetesApi<>(V1Service.class, V1ServiceList.class, "", "v1", "services", apiClient); SharedIndexInformer serviceSharedIndexInformer = sharedInformerFactory - .sharedIndexInformerFor(servicesApi, V1Service.class, 0L, namespace); + .sharedIndexInformerFor(servicesApi, V1Service.class, 0L, namespace); Lister serviceLister = new Lister<>(serviceSharedIndexInformer.getIndexer()); GenericKubernetesApi endpointsApi = new GenericKubernetesApi<>( V1Endpoints.class, V1EndpointsList.class, "", "v1", "endpoints", apiClient); SharedIndexInformer endpointsSharedIndexInformer = sharedInformerFactory - .sharedIndexInformerFor(endpointsApi, V1Endpoints.class, 0L, namespace); + .sharedIndexInformerFor(endpointsApi, V1Endpoints.class, 0L, namespace); Lister endpointsLister = new Lister<>(endpointsSharedIndexInformer.getIndexer()); KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient( sharedInformerFactory, serviceLister, endpointsLister, serviceSharedIndexInformer, diff --git a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesClientInformerSelectiveNamespacesAutoConfiguration.java b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesClientInformerSelectiveNamespacesAutoConfiguration.java index 23f1ed26a2..b8f5bc17c6 100644 --- a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesClientInformerSelectiveNamespacesAutoConfiguration.java +++ b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesClientInformerSelectiveNamespacesAutoConfiguration.java @@ -101,7 +101,7 @@ public List> serviceSharedIndexInformers( GenericKubernetesApi servicesApi = new GenericKubernetesApi<>(V1Service.class, V1ServiceList.class, "", "v1", "services", apiClient); SharedIndexInformer sharedIndexInformer = sharedInformerFactories.get(i) - .sharedIndexInformerFor(servicesApi, V1Service.class, 0L, selectiveNamespaces.get(i)); + .sharedIndexInformerFor(servicesApi, V1Service.class, 0L, selectiveNamespaces.get(i)); serviceSharedIndexedInformers.add(sharedIndexInformer); } return serviceSharedIndexedInformers; @@ -138,7 +138,7 @@ public List> endpointsSharedIndexInformers( GenericKubernetesApi endpointsApi = new GenericKubernetesApi<>( V1Endpoints.class, V1EndpointsList.class, "", "v1", "endpoints", apiClient); SharedIndexInformer sharedIndexInformer = sharedInformerFactories.get(i) - .sharedIndexInformerFor(endpointsApi, V1Endpoints.class, 0L, selectiveNamespaces.get(i)); + .sharedIndexInformerFor(endpointsApi, V1Endpoints.class, 0L, selectiveNamespaces.get(i)); endpointsSharedIndexedInformers.add(sharedIndexInformer); } return endpointsSharedIndexedInformers; diff --git a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientUtils.java b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientUtils.java index 864d469dc5..5bd5076f94 100644 --- a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientUtils.java +++ b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientUtils.java @@ -57,7 +57,8 @@ final class KubernetesDiscoveryClientUtils { private static final SpelExpressionParser PARSER = new SpelExpressionParser(); private static final SimpleEvaluationContext EVALUATION_CONTEXT = SimpleEvaluationContext.forReadOnlyDataBinding() - .withInstanceMethods().build(); + .withInstanceMethods() + .build(); private KubernetesDiscoveryClientUtils() { @@ -66,8 +67,9 @@ private KubernetesDiscoveryClientUtils() { static boolean matchesServiceLabels(V1Service service, KubernetesDiscoveryProperties properties) { Map propertiesServiceLabels = properties.serviceLabels(); - Map serviceLabels = Optional.ofNullable(service.getMetadata()).map(V1ObjectMeta::getLabels) - .orElse(Map.of()); + Map serviceLabels = Optional.ofNullable(service.getMetadata()) + .map(V1ObjectMeta::getLabels) + .orElse(Map.of()); if (propertiesServiceLabels.isEmpty()) { LOG.debug(() -> "service labels from properties are empty, service with name : '" @@ -142,16 +144,17 @@ static ServiceMetadata serviceMetadata(V1Service service) { */ static Map endpointSubsetsPortData(List endpointSubsets) { return endpointSubsets.stream() - .flatMap(endpointSubset -> Optional.ofNullable(endpointSubset.getPorts()).orElse(List.of()).stream()) - .collect(Collectors.toMap( - endpointPort -> hasText(endpointPort.getName()) ? endpointPort.getName() : UNSET_PORT_NAME, - CoreV1EndpointPort::getPort)); + .flatMap(endpointSubset -> Optional.ofNullable(endpointSubset.getPorts()).orElse(List.of()).stream()) + .collect(Collectors.toMap( + endpointPort -> hasText(endpointPort.getName()) ? endpointPort.getName() : UNSET_PORT_NAME, + CoreV1EndpointPort::getPort)); } static List addresses(V1EndpointSubset endpointSubset, KubernetesDiscoveryProperties properties) { - List addresses = Optional.ofNullable(endpointSubset.getAddresses()).map(ArrayList::new) - .orElse(new ArrayList<>()); + List addresses = Optional.ofNullable(endpointSubset.getAddresses()) + .map(ArrayList::new) + .orElse(new ArrayList<>()); if (properties.includeNotReadyAddresses()) { List notReadyAddresses = endpointSubset.getNotReadyAddresses(); diff --git a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesInformerDiscoveryClient.java b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesInformerDiscoveryClient.java index 251d4a3a56..1c2c1e72cf 100644 --- a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesInformerDiscoveryClient.java +++ b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesInformerDiscoveryClient.java @@ -124,9 +124,13 @@ public KubernetesInformerDiscoveryClient(List sharedInfor this.endpointsListers = endpointsListers; this.informersReadyFunc = () -> { boolean serviceInformersReady = serviceInformers.isEmpty() || serviceInformers.stream() - .map(SharedInformer::hasSynced).reduce(Boolean::logicalAnd).orElse(false); + .map(SharedInformer::hasSynced) + .reduce(Boolean::logicalAnd) + .orElse(false); boolean endpointsInformersReady = endpointsInformers.isEmpty() || endpointsInformers.stream() - .map(SharedInformer::hasSynced).reduce(Boolean::logicalAnd).orElse(false); + .map(SharedInformer::hasSynced) + .reduce(Boolean::logicalAnd) + .orElse(false); return serviceInformersReady && endpointsInformersReady; }; @@ -144,18 +148,24 @@ public String description() { public List getInstances(String serviceId) { Objects.requireNonNull(serviceId, "serviceId must be provided"); - List allServices = serviceListers.stream().flatMap(x -> x.list().stream()) - .filter(scv -> scv.getMetadata() != null).filter(svc -> serviceId.equals(svc.getMetadata().getName())) - .filter(scv -> matchesServiceLabels(scv, properties)).toList(); + List allServices = serviceListers.stream() + .flatMap(x -> x.list().stream()) + .filter(scv -> scv.getMetadata() != null) + .filter(svc -> serviceId.equals(svc.getMetadata().getName())) + .filter(scv -> matchesServiceLabels(scv, properties)) + .toList(); - List serviceInstances = allServices.stream().filter(filter) - .flatMap(service -> serviceInstances(service, serviceId).stream()) - .collect(Collectors.toCollection(ArrayList::new)); + List serviceInstances = allServices.stream() + .filter(filter) + .flatMap(service -> serviceInstances(service, serviceId).stream()) + .collect(Collectors.toCollection(ArrayList::new)); if (properties.includeExternalNameServices()) { LOG.debug(() -> "Searching for 'ExternalName' type of services with serviceId : " + serviceId); - List externalNameServices = allServices.stream().filter(s -> s.getSpec() != null) - .filter(s -> EXTERNAL_NAME.equals(s.getSpec().getType())).toList(); + List externalNameServices = allServices.stream() + .filter(s -> s.getSpec() != null) + .filter(s -> EXTERNAL_NAME.equals(s.getSpec().getType())) + .toList(); for (V1Service service : externalNameServices) { ServiceMetadata serviceMetadata = serviceMetadata(service); Map serviceInstanceMetadata = serviceInstanceMetadata(Map.of(), serviceMetadata, @@ -178,8 +188,9 @@ private List serviceInstances(V1Service service, String service List instances = new ArrayList<>(); List allEndpoints = endpointsListers.stream() - .map(endpointsLister -> endpointsLister.namespace(service.getMetadata().getNamespace()).get(serviceId)) - .filter(Objects::nonNull).toList(); + .map(endpointsLister -> endpointsLister.namespace(service.getMetadata().getNamespace()).get(serviceId)) + .filter(Objects::nonNull) + .toList(); for (V1Endpoints endpoints : allEndpoints) { List subsets = endpoints.getSubsets(); @@ -218,9 +229,13 @@ private List serviceInstances(V1Service service, String service @Override public List getServices() { - List services = serviceListers.stream().flatMap(serviceLister -> serviceLister.list().stream()) - .filter(service -> matchesServiceLabels(service, properties)).filter(filter) - .map(s -> s.getMetadata().getName()).distinct().toList(); + List services = serviceListers.stream() + .flatMap(serviceLister -> serviceLister.list().stream()) + .filter(service -> matchesServiceLabels(service, properties)) + .filter(filter) + .map(s -> s.getMetadata().getName()) + .distinct() + .toList(); LOG.debug(() -> "will return services : " + services); return services; } diff --git a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesCatalogWatch.java b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesCatalogWatch.java index bb9fbe5c67..664763960c 100644 --- a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesCatalogWatch.java +++ b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesCatalogWatch.java @@ -101,7 +101,7 @@ Function> stateGen CustomObjectsApi customObjectsApi = new CustomObjectsApi(apiClient); try { List resources = customObjectsApi.getAPIResources(DISCOVERY_GROUP, DISCOVERY_VERSION) - .getResources(); + .getResources(); boolean found = resources.stream().map(V1APIResource::getKind).anyMatch(ENDPOINT_SLICE::equals); if (!found) { throw new IllegalArgumentException("EndpointSlices are not supported on the cluster"); diff --git a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesCatalogWatchContext.java b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesCatalogWatchContext.java index 215931cac3..6b41745a5e 100644 --- a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesCatalogWatchContext.java +++ b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesCatalogWatchContext.java @@ -41,8 +41,10 @@ record KubernetesCatalogWatchContext(CoreV1Api coreV1Api, ApiClient apiClient, K KubernetesNamespaceProvider namespaceProvider) { static List state(Stream references) { - return references.filter(Objects::nonNull).map(x -> new EndpointNameAndNamespace(x.getName(), x.getNamespace())) - .sorted(Comparator.comparing(EndpointNameAndNamespace::endpointName, String::compareTo)).toList(); + return references.filter(Objects::nonNull) + .map(x -> new EndpointNameAndNamespace(x.getName(), x.getNamespace())) + .sorted(Comparator.comparing(EndpointNameAndNamespace::endpointName, String::compareTo)) + .toList(); } static String labelSelector(Map labels) { diff --git a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesEndpointSlicesCatalogWatch.java b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesEndpointSlicesCatalogWatch.java index 1d14db25f5..3177302c78 100644 --- a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesEndpointSlicesCatalogWatch.java +++ b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesEndpointSlicesCatalogWatch.java @@ -60,7 +60,9 @@ public List apply(KubernetesCatalogWatchContext contex else if (!context.properties().namespaces().isEmpty()) { LOG.debug(() -> "discovering endpoint slices in " + context.properties().namespaces()); List inner = new ArrayList<>(context.properties().namespaces().size()); - context.properties().namespaces().forEach(namespace -> inner + context.properties() + .namespaces() + .forEach(namespace -> inner .addAll(namespacedEndpointSlices(api, namespace, context.properties().serviceLabels()))); endpointSlices = inner; } @@ -71,8 +73,10 @@ else if (!context.properties().namespaces().isEmpty()) { endpointSlices = namespacedEndpointSlices(api, namespace, context.properties().serviceLabels()); } - Stream references = endpointSlices.stream().map(V1EndpointSlice::getEndpoints) - .flatMap(List::stream).map(V1Endpoint::getTargetRef); + Stream references = endpointSlices.stream() + .map(V1EndpointSlice::getEndpoints) + .flatMap(List::stream) + .map(V1Endpoint::getTargetRef); return KubernetesCatalogWatchContext.state(references); @@ -80,8 +84,10 @@ else if (!context.properties().namespaces().isEmpty()) { private List endpointSlices(DiscoveryV1Api api, Map labels) { try { - return api.listEndpointSliceForAllNamespaces(null, null, null, labelSelector(labels), null, null, null, - null, null, null, null).getItems(); + return api + .listEndpointSliceForAllNamespaces(null, null, null, labelSelector(labels), null, null, null, null, + null, null, null) + .getItems(); } catch (ApiException e) { LOG.warn(e, () -> "can not list endpoint slices in all namespaces"); @@ -92,8 +98,10 @@ private List endpointSlices(DiscoveryV1Api api, Map namespacedEndpointSlices(DiscoveryV1Api api, String namespace, Map labels) { try { - return api.listNamespacedEndpointSlice(namespace, null, null, null, null, labelSelector(labels), null, null, - null, null, null, null).getItems(); + return api + .listNamespacedEndpointSlice(namespace, null, null, null, null, labelSelector(labels), null, null, null, + null, null, null) + .getItems(); } catch (ApiException e) { LOG.warn(e, () -> "can not list endpoint slices in namespace " + namespace); diff --git a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesEndpointsCatalogWatch.java b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesEndpointsCatalogWatch.java index 3bac70afb4..1d3fcac51b 100644 --- a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesEndpointsCatalogWatch.java +++ b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesEndpointsCatalogWatch.java @@ -59,7 +59,9 @@ public List apply(KubernetesCatalogWatchContext contex else if (!context.properties().namespaces().isEmpty()) { LOG.debug(() -> "discovering endpoints in " + context.properties().namespaces()); List inner = new ArrayList<>(context.properties().namespaces().size()); - context.properties().namespaces().forEach(namespace -> inner + context.properties() + .namespaces() + .forEach(namespace -> inner .addAll(namespacedEndpoints(coreV1Api, namespace, context.properties().serviceLabels()))); endpoints = inner; } @@ -80,9 +82,14 @@ else if (!context.properties().namespaces().isEmpty()) { * V1EndpointSubset::getAddresses and V1EndpointSubset::getPorts (each is a List) * */ - Stream references = endpoints.stream().map(V1Endpoints::getSubsets).filter(Objects::nonNull) - .flatMap(List::stream).map(V1EndpointSubset::getAddresses).filter(Objects::nonNull) - .flatMap(List::stream).map(V1EndpointAddress::getTargetRef); + Stream references = endpoints.stream() + .map(V1Endpoints::getSubsets) + .filter(Objects::nonNull) + .flatMap(List::stream) + .map(V1EndpointSubset::getAddresses) + .filter(Objects::nonNull) + .flatMap(List::stream) + .map(V1EndpointAddress::getTargetRef); return KubernetesCatalogWatchContext.state(references); @@ -90,8 +97,10 @@ else if (!context.properties().namespaces().isEmpty()) { private List endpoints(CoreV1Api client, Map labels) { try { - return client.listEndpointsForAllNamespaces(null, null, null, labelSelector(labels), null, null, null, null, - null, null, null).getItems(); + return client + .listEndpointsForAllNamespaces(null, null, null, labelSelector(labels), null, null, null, null, null, + null, null) + .getItems(); } catch (ApiException e) { LOG.warn(e, () -> "can not list endpoints in all namespaces"); @@ -101,8 +110,10 @@ private List endpoints(CoreV1Api client, Map labels private List namespacedEndpoints(CoreV1Api client, String namespace, Map labels) { try { - return client.listNamespacedEndpoints(namespace, null, null, null, null, labelSelector(labels), null, null, - null, null, null, null).getItems(); + return client + .listNamespacedEndpoints(namespace, null, null, null, null, labelSelector(labels), null, null, null, + null, null, null) + .getItems(); } catch (ApiException e) { LOG.warn(e, () -> "can not list endpoints in namespace " + namespace); diff --git a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/reactive/KubernetesInformerReactiveDiscoveryClient.java b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/reactive/KubernetesInformerReactiveDiscoveryClient.java index 13248a2a5e..f078aa3e7a 100644 --- a/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/reactive/KubernetesInformerReactiveDiscoveryClient.java +++ b/spring-cloud-kubernetes-client-discovery/src/main/java/org/springframework/cloud/kubernetes/client/discovery/reactive/KubernetesInformerReactiveDiscoveryClient.java @@ -64,13 +64,13 @@ public String description() { public Flux getInstances(String serviceId) { Objects.requireNonNull(serviceId, "serviceId must be provided"); return Flux.defer(() -> Flux.fromIterable(kubernetesDiscoveryClient.getInstances(serviceId))) - .subscribeOn(Schedulers.boundedElastic()); + .subscribeOn(Schedulers.boundedElastic()); } @Override public Flux getServices() { return Flux.defer(() -> Flux.fromIterable(kubernetesDiscoveryClient.getServices())) - .subscribeOn(Schedulers.boundedElastic()); + .subscribeOn(Schedulers.boundedElastic()); } } diff --git a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/K8sInstanceIdHostPodNameSupplierTests.java b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/K8sInstanceIdHostPodNameSupplierTests.java index fd9ce80b59..b39117ffff 100644 --- a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/K8sInstanceIdHostPodNameSupplierTests.java +++ b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/K8sInstanceIdHostPodNameSupplierTests.java @@ -37,7 +37,8 @@ class K8sInstanceIdHostPodNameSupplierTests { @Test void instanceIdNoEndpointAddress() { V1Service service = new V1ServiceBuilder().withSpec(new V1ServiceSpecBuilder().build()) - .withMetadata(new V1ObjectMetaBuilder().withUid("123").build()).build(); + .withMetadata(new V1ObjectMetaBuilder().withUid("123").build()) + .build(); K8sInstanceIdHostPodNameSupplier supplier = K8sInstanceIdHostPodNameSupplier.externalName(service); InstanceIdHostPodName result = supplier.get(); @@ -49,9 +50,11 @@ void instanceIdNoEndpointAddress() { @Test void instanceIdWithEndpointAddress() { V1EndpointAddress endpointAddress = new V1EndpointAddressBuilder() - .withTargetRef(new V1ObjectReferenceBuilder().withUid("456").build()).build(); + .withTargetRef(new V1ObjectReferenceBuilder().withUid("456").build()) + .build(); V1Service service = new V1ServiceBuilder().withSpec(new V1ServiceSpecBuilder().build()) - .withMetadata(new V1ObjectMetaBuilder().withUid("123").build()).build(); + .withMetadata(new V1ObjectMetaBuilder().withUid("123").build()) + .build(); K8sInstanceIdHostPodNameSupplier supplier = K8sInstanceIdHostPodNameSupplier.nonExternalName(endpointAddress, service); @@ -64,8 +67,9 @@ void instanceIdWithEndpointAddress() { @Test void hostNoEndpointAddress() { V1Service service = new V1ServiceBuilder() - .withSpec(new V1ServiceSpecBuilder().withExternalName("external-name").build()) - .withMetadata(new V1ObjectMeta()).build(); + .withSpec(new V1ServiceSpecBuilder().withExternalName("external-name").build()) + .withMetadata(new V1ObjectMeta()) + .build(); K8sInstanceIdHostPodNameSupplier supplier = K8sInstanceIdHostPodNameSupplier.externalName(service); InstanceIdHostPodName result = supplier.get(); @@ -78,8 +82,9 @@ void hostNoEndpointAddress() { void hostWithEndpointAddress() { V1EndpointAddress endpointAddress = new V1EndpointAddressBuilder().withIp("127.0.0.1").build(); V1Service service = new V1ServiceBuilder() - .withSpec(new V1ServiceSpecBuilder().withExternalName("external-name").build()) - .withMetadata(new V1ObjectMeta()).build(); + .withSpec(new V1ServiceSpecBuilder().withExternalName("external-name").build()) + .withMetadata(new V1ObjectMeta()) + .build(); K8sInstanceIdHostPodNameSupplier supplier = K8sInstanceIdHostPodNameSupplier.nonExternalName(endpointAddress, service); @@ -92,7 +97,8 @@ void hostWithEndpointAddress() { @Test void testPodNameIsNull() { V1Service service = new V1ServiceBuilder().withMetadata(new V1ObjectMetaBuilder().withUid("123").build()) - .withSpec(new V1ServiceSpecBuilder().withExternalName("external-name").build()).build(); + .withSpec(new V1ServiceSpecBuilder().withExternalName("external-name").build()) + .build(); K8sInstanceIdHostPodNameSupplier supplier = K8sInstanceIdHostPodNameSupplier.externalName(service); InstanceIdHostPodName result = supplier.get(); @@ -103,10 +109,12 @@ void testPodNameIsNull() { @Test void podNameKindNotPod() { V1EndpointAddress endpointAddress = new V1EndpointAddressBuilder() - .withTargetRef(new V1ObjectReferenceBuilder().withKind("Service").build()).build(); + .withTargetRef(new V1ObjectReferenceBuilder().withKind("Service").build()) + .build(); V1Service service = new V1ServiceBuilder() - .withSpec(new V1ServiceSpecBuilder().withExternalName("external-name").build()) - .withMetadata(new V1ObjectMeta()).build(); + .withSpec(new V1ServiceSpecBuilder().withExternalName("external-name").build()) + .withMetadata(new V1ObjectMeta()) + .build(); K8sInstanceIdHostPodNameSupplier supplier = K8sInstanceIdHostPodNameSupplier.nonExternalName(endpointAddress, service); @@ -119,10 +127,12 @@ void podNameKindNotPod() { @Test void podNameKindIsPod() { V1EndpointAddress endpointAddress = new V1EndpointAddressBuilder() - .withTargetRef(new V1ObjectReferenceBuilder().withKind("Pod").withName("my-pod").build()).build(); + .withTargetRef(new V1ObjectReferenceBuilder().withKind("Pod").withName("my-pod").build()) + .build(); V1Service service = new V1ServiceBuilder() - .withSpec(new V1ServiceSpecBuilder().withExternalName("external-name").build()) - .withMetadata(new V1ObjectMeta()).build(); + .withSpec(new V1ServiceSpecBuilder().withExternalName("external-name").build()) + .withMetadata(new V1ObjectMeta()) + .build(); K8sInstanceIdHostPodNameSupplier supplier = K8sInstanceIdHostPodNameSupplier.nonExternalName(endpointAddress, service); diff --git a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/K8sPodLabelsAndAnnotationsSupplierTests.java b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/K8sPodLabelsAndAnnotationsSupplierTests.java index 8b9ad13589..b8aa6c4b46 100644 --- a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/K8sPodLabelsAndAnnotationsSupplierTests.java +++ b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/K8sPodLabelsAndAnnotationsSupplierTests.java @@ -47,11 +47,11 @@ void afterEach() { @Test void noObjetMeta() throws Exception { - Mockito.when(coreV1Api.readNamespacedPod(POD_NAME, NAMESPACE, null)).thenReturn( - new V1PodBuilder().withMetadata(new V1ObjectMetaBuilder().withName(POD_NAME).build()).build()); + Mockito.when(coreV1Api.readNamespacedPod(POD_NAME, NAMESPACE, null)) + .thenReturn(new V1PodBuilder().withMetadata(new V1ObjectMetaBuilder().withName(POD_NAME).build()).build()); PodLabelsAndAnnotations result = K8sPodLabelsAndAnnotationsSupplier.nonExternalName(coreV1Api, NAMESPACE) - .apply(POD_NAME); + .apply(POD_NAME); Assertions.assertNotNull(result); Assertions.assertTrue(result.labels().isEmpty()); Assertions.assertTrue(result.annotations().isEmpty()); @@ -61,11 +61,15 @@ void noObjetMeta() throws Exception { void labelsAndAnnotationsPresent() throws Exception { Mockito.when(coreV1Api.readNamespacedPod(POD_NAME, NAMESPACE, null)) - .thenReturn(new V1PodBuilder().withMetadata(new V1ObjectMetaBuilder().withName(POD_NAME) - .withLabels(Map.of("a", "b")).withAnnotations(Map.of("c", "d")).build()).build()); + .thenReturn(new V1PodBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName(POD_NAME) + .withLabels(Map.of("a", "b")) + .withAnnotations(Map.of("c", "d")) + .build()) + .build()); PodLabelsAndAnnotations result = K8sPodLabelsAndAnnotationsSupplier.nonExternalName(coreV1Api, NAMESPACE) - .apply(POD_NAME); + .apply(POD_NAME); Assertions.assertNotNull(result); Assertions.assertEquals(result.labels(), Map.of("a", "b")); Assertions.assertEquals(result.annotations(), Map.of("c", "d")); diff --git a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesClientConfigServerBootstrapperTests.java b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesClientConfigServerBootstrapperTests.java index a3cfbf68d4..a034a3bea6 100644 --- a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesClientConfigServerBootstrapperTests.java +++ b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesClientConfigServerBootstrapperTests.java @@ -83,29 +83,37 @@ public void before() throws JsonProcessingException { WireMock.configureFor(wireMockServer.port()); V1ServiceList SERVICE_LIST = new V1ServiceListBuilder() - .withMetadata(new V1ListMetaBuilder().withResourceVersion("1").build()) - .addToItems(new V1ServiceBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("spring-cloud-kubernetes-configserver") - .withNamespace("default").withResourceVersion("0").addToLabels("beta", "true") - .addToAnnotations("org.springframework.cloud", "true").withUid("0").build()) - .withSpec(new V1ServiceSpecBuilder().withClusterIP("localhost").withSessionAffinity("None") - .withType("ClusterIP") - .addToPorts(new V1ServicePortBuilder().withPort(wireMockServer.port()).withName("http") - .withProtocol("TCP").withNewTargetPort(wireMockServer.port()).build()) - .build()) + .withMetadata(new V1ListMetaBuilder().withResourceVersion("1").build()) + .addToItems(new V1ServiceBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("spring-cloud-kubernetes-configserver") + .withNamespace("default") + .withResourceVersion("0") + .addToLabels("beta", "true") + .addToAnnotations("org.springframework.cloud", "true") + .withUid("0") + .build()) + .withSpec(new V1ServiceSpecBuilder().withClusterIP("localhost") + .withSessionAffinity("None") + .withType("ClusterIP") + .addToPorts(new V1ServicePortBuilder().withPort(wireMockServer.port()) + .withName("http") + .withProtocol("TCP") + .withNewTargetPort(wireMockServer.port()) .build()) - .build(); + .build()) + .build()) + .build(); V1EndpointsList ENDPOINTS_LIST = new V1EndpointsListBuilder() - .withMetadata(new V1ListMetaBuilder().withResourceVersion("0").build()) - .addToItems(new V1Endpoints() - .metadata(new V1ObjectMeta().name("spring-cloud-kubernetes-configserver").namespace("default")) - .addSubsetsItem( - new V1EndpointSubset() - .addPortsItem(new CoreV1EndpointPort().port(wireMockServer.port()).name("http")) - .addAddressesItem(new V1EndpointAddress().hostname("localhost").ip("localhost") - .targetRef(new V1ObjectReferenceBuilder().withUid("uid1").build())))) - .build(); + .withMetadata(new V1ListMetaBuilder().withResourceVersion("0").build()) + .addToItems(new V1Endpoints() + .metadata(new V1ObjectMeta().name("spring-cloud-kubernetes-configserver").namespace("default")) + .addSubsetsItem(new V1EndpointSubset() + .addPortsItem(new CoreV1EndpointPort().port(wireMockServer.port()).name("http")) + .addAddressesItem(new V1EndpointAddress().hostname("localhost") + .ip("localhost") + .targetRef(new V1ObjectReferenceBuilder().withUid("uid1").build())))) + .build(); Environment environment = new Environment("test", "default"); Map properties = new HashMap<>(); @@ -113,19 +121,21 @@ public void before() throws JsonProcessingException { org.springframework.cloud.config.environment.PropertySource p = new PropertySource("p1", properties); environment.add(p); ObjectMapper objectMapper = new ObjectMapper(); - stubFor(get("/application/default") - .willReturn(aResponse().withStatus(200).withBody(objectMapper.writeValueAsString(environment)) - .withHeader("content-type", "application/json"))); + stubFor(get("/application/default").willReturn(aResponse().withStatus(200) + .withBody(objectMapper.writeValueAsString(environment)) + .withHeader("content-type", "application/json"))); stubFor(get("/api/v1/namespaces/default/endpoints?resourceVersion=0&watch=false") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(ENDPOINTS_LIST)) - .withHeader("content-type", "application/json"))); + .willReturn(aResponse().withStatus(200) + .withBody(new JSON().serialize(ENDPOINTS_LIST)) + .withHeader("content-type", "application/json"))); stubFor(get("/api/v1/namespaces/default/services?resourceVersion=0&watch=false") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(SERVICE_LIST)) - .withHeader("content-type", "application/json"))); + .willReturn(aResponse().withStatus(200) + .withBody(new JSON().serialize(SERVICE_LIST)) + .withHeader("content-type", "application/json"))); stubFor(get(urlMatching("/api/v1/namespaces/default/services.*.watch=true")) - .willReturn(aResponse().withStatus(200))); + .willReturn(aResponse().withStatus(200))); stubFor(get(urlMatching("/api/v1/namespaces/default/endpoints.*.watch=true")) - .willReturn(aResponse().withStatus(200))); + .willReturn(aResponse().withStatus(200))); } @AfterEach @@ -143,9 +153,10 @@ void testBootstrapper() { SpringApplicationBuilder setup(String... env) { SpringApplicationBuilder builder = new SpringApplicationBuilder(TestConfig.class) - .properties(addDefaultEnv(env)); + .properties(addDefaultEnv(env)); ApiClient apiClient = new ClientBuilder().setBasePath("http://localhost:" + wireMockServer.port()) - .setReadTimeout(Duration.ZERO).build(); + .setReadTimeout(Duration.ZERO) + .build(); builder.addBootstrapRegistryInitializer(registry -> registry.register(ApiClient.class, (context) -> apiClient)); builder.addBootstrapRegistryInitializer(new KubernetesClientConfigServerBootstrapper()); return builder; diff --git a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesClientInformerSelectiveNamespacesAutoConfigurationTests.java b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesClientInformerSelectiveNamespacesAutoConfigurationTests.java index c65544cc4c..abc6b410a9 100644 --- a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesClientInformerSelectiveNamespacesAutoConfigurationTests.java +++ b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesClientInformerSelectiveNamespacesAutoConfigurationTests.java @@ -54,44 +54,44 @@ class KubernetesClientInformerSelectiveNamespacesAutoConfigurationTests { void testBeansCreates(CapturedOutput output) { new ApplicationContextRunner() - .withPropertyValues("spring.cloud.discovery.enabled=true", - "spring.cloud.kubernetes.discovery.enabled=true", - "spring.cloud.kubernetes.discovery.namespaces[0]=" + NAMESPACE_A, - "spring.cloud.kubernetes.discovery.namespaces[1]=" + NAMESPACE_B, - "spring.main.cloud-platform=kubernetes") - .withConfiguration( - AutoConfigurations.of(KubernetesClientInformerSelectiveNamespacesAutoConfiguration.class)) - .withUserConfiguration(Config.class).run(context -> { - assertThat(context.getBean("selectiveNamespaces")).isNotNull(); - - @SuppressWarnings("unchecked") - Set selectiveNamespaces = context.getBean("selectiveNamespaces", Set.class); - Assertions.assertEquals(selectiveNamespaces, Set.of("a", "b")); - - @SuppressWarnings("unchecked") - Set namespaces = context.getBean("namespaces", Set.class); - Assertions.assertEquals(namespaces, Set.of("c", "d")); - }); + .withPropertyValues("spring.cloud.discovery.enabled=true", "spring.cloud.kubernetes.discovery.enabled=true", + "spring.cloud.kubernetes.discovery.namespaces[0]=" + NAMESPACE_A, + "spring.cloud.kubernetes.discovery.namespaces[1]=" + NAMESPACE_B, + "spring.main.cloud-platform=kubernetes") + .withConfiguration( + AutoConfigurations.of(KubernetesClientInformerSelectiveNamespacesAutoConfiguration.class)) + .withUserConfiguration(Config.class) + .run(context -> { + assertThat(context.getBean("selectiveNamespaces")).isNotNull(); + + @SuppressWarnings("unchecked") + Set selectiveNamespaces = context.getBean("selectiveNamespaces", Set.class); + Assertions.assertEquals(selectiveNamespaces, Set.of("a", "b")); + + @SuppressWarnings("unchecked") + Set namespaces = context.getBean("namespaces", Set.class); + Assertions.assertEquals(namespaces, Set.of("c", "d")); + }); assertThat(output.getOut().contains("registering lister (for services) in namespace : " + NAMESPACE_A)) - .isTrue(); + .isTrue(); assertThat(output.getOut().contains("registering lister (for services) in namespace : " + NAMESPACE_B)) - .isTrue(); + .isTrue(); assertThat(output.getOut().contains("registering lister (for services) in namespace : " + NAMESPACE_C)) - .isFalse(); + .isFalse(); assertThat(output.getOut().contains("registering lister (for services) in namespace : " + NAMESPACE_D)) - .isFalse(); + .isFalse(); assertThat(output.getOut().contains("registering lister (for endpoints) in namespace : " + NAMESPACE_A)) - .isTrue(); + .isTrue(); assertThat(output.getOut().contains("registering lister (for endpoints) in namespace : " + NAMESPACE_B)) - .isTrue(); + .isTrue(); assertThat(output.getOut().contains("registering lister (for endpoints) in namespace : " + NAMESPACE_C)) - .isFalse(); + .isFalse(); assertThat(output.getOut().contains("registering lister (for endpoints) in namespace : " + NAMESPACE_D)) - .isFalse(); + .isFalse(); } @Configuration diff --git a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientAutoConfigurationTests.java b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientAutoConfigurationTests.java index f3405ac95f..be32167646 100644 --- a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientAutoConfigurationTests.java +++ b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientAutoConfigurationTests.java @@ -70,8 +70,9 @@ void kubernetesDiscoveryClientCreated() { assertThat(this.discoveryClient).isNotNull().isInstanceOf(CompositeDiscoveryClient.class); CompositeDiscoveryClient composite = (CompositeDiscoveryClient) this.discoveryClient; - assertThat(composite.getDiscoveryClients().stream() - .anyMatch(dc -> dc instanceof KubernetesInformerDiscoveryClient)).isTrue(); + assertThat(composite.getDiscoveryClients() + .stream() + .anyMatch(dc -> dc instanceof KubernetesInformerDiscoveryClient)).isTrue(); } @SpringBootApplication @@ -90,11 +91,15 @@ ApiClient apiClient() { wireMockServer.start(); WireMock.configureFor(wireMockServer.port()); stubFor(get("/api/v1/namespaces/test/endpoints?resourceVersion=0&watch=false") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(new V1EndpointsListBuilder() - .withMetadata(new V1ListMetaBuilder().withResourceVersion("0").build()).build())))); + .willReturn(aResponse().withStatus(200) + .withBody(new JSON().serialize(new V1EndpointsListBuilder() + .withMetadata(new V1ListMetaBuilder().withResourceVersion("0").build()) + .build())))); stubFor(get("/api/v1/namespaces/test/services?resourceVersion=0&watch=false") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(new V1ServiceListBuilder() - .withMetadata(new V1ListMetaBuilder().withResourceVersion("0").build()).build())))); + .willReturn(aResponse().withStatus(200) + .withBody(new JSON().serialize(new V1ServiceListBuilder() + .withMetadata(new V1ListMetaBuilder().withResourceVersion("0").build()) + .build())))); return new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build(); } diff --git a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientFilterMetadataTest.java b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientFilterMetadataTest.java index 3071b3671e..e508488e51 100644 --- a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientFilterMetadataTest.java +++ b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientFilterMetadataTest.java @@ -235,9 +235,14 @@ private void setup(String serviceId, String namespace, Map label Map ports) { V1Service service = new V1ServiceBuilder() - .withSpec(new V1ServiceSpecBuilder().withType("ClusterIP").withPorts(getServicePorts(ports)).build()) - .withNewMetadata().withName(serviceId).withNamespace(namespace).withLabels(labels) - .withAnnotations(annotations).endMetadata().build(); + .withSpec(new V1ServiceSpecBuilder().withType("ClusterIP").withPorts(getServicePorts(ports)).build()) + .withNewMetadata() + .withName(serviceId) + .withNamespace(namespace) + .withLabels(labels) + .withAnnotations(annotations) + .endMetadata() + .build(); servicesCache.add(service); @@ -245,8 +250,13 @@ private void setup(String serviceId, String namespace, Map label objectMeta.setNamespace(namespace); objectMeta.setName(serviceId); - V1Endpoints endpoints = new V1EndpointsBuilder().withMetadata(objectMeta).addNewSubset() - .addAllToPorts(getEndpointPorts(ports)).addNewAddress().endAddress().endSubset().build(); + V1Endpoints endpoints = new V1EndpointsBuilder().withMetadata(objectMeta) + .addNewSubset() + .addAllToPorts(getEndpointPorts(ports)) + .addNewAddress() + .endAddress() + .endSubset() + .build(); endpointsCache.add(endpoints); diff --git a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientFilterTests.java b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientFilterTests.java index f730894004..617970ea1a 100644 --- a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientFilterTests.java +++ b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientFilterTests.java @@ -76,8 +76,10 @@ void testTwoServicesBothMatch() { List unfiltered = List.of(a, b); Predicate predicate = KubernetesDiscoveryClientUtils.filter(properties); - List filtered = unfiltered.stream().filter(predicate) - .sorted(Comparator.comparing(service -> service.getMetadata().getName())).toList(); + List filtered = unfiltered.stream() + .filter(predicate) + .sorted(Comparator.comparing(service -> service.getMetadata().getName())) + .toList(); Assertions.assertEquals(filtered.get(0).getMetadata().getName(), "a"); Assertions.assertEquals(filtered.get(1).getMetadata().getName(), "a"); } @@ -96,8 +98,10 @@ void testTwoServicesNoneMatch() { List unfiltered = List.of(a, b); Predicate predicate = KubernetesDiscoveryClientUtils.filter(properties); - List filtered = unfiltered.stream().filter(predicate) - .sorted(Comparator.comparing(service -> service.getMetadata().getName())).toList(); + List filtered = unfiltered.stream() + .filter(predicate) + .sorted(Comparator.comparing(service -> service.getMetadata().getName())) + .toList(); Assertions.assertEquals(filtered.size(), 0); } @@ -115,8 +119,10 @@ void testTwoServicesOneMatch() { List unfiltered = List.of(a, b); Predicate predicate = KubernetesDiscoveryClientUtils.filter(properties); - List filtered = unfiltered.stream().filter(predicate) - .sorted(Comparator.comparing(service -> service.getMetadata().getName())).toList(); + List filtered = unfiltered.stream() + .filter(predicate) + .sorted(Comparator.comparing(service -> service.getMetadata().getName())) + .toList(); Assertions.assertEquals(filtered.size(), 0); } diff --git a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientServiceWithoutPortNameTests.java b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientServiceWithoutPortNameTests.java index 5bfcc509f2..2766663b84 100644 --- a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientServiceWithoutPortNameTests.java +++ b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientServiceWithoutPortNameTests.java @@ -73,20 +73,18 @@ void beforeEach() { void testDiscoveryWithoutAServicePortName() { V1Endpoints endpoints = new V1EndpointsBuilder() - .withSubsets( - new V1EndpointSubsetBuilder().withPorts(new CoreV1EndpointPortBuilder().withPort(8080).build()) - .withAddresses(new V1EndpointAddressBuilder().withIp("127.0.0.1").build()).build()) - .withMetadata( - new V1ObjectMetaBuilder().withName("no-port-name-service").withNamespace(NAMESPACE).build()) - .build(); + .withSubsets(new V1EndpointSubsetBuilder().withPorts(new CoreV1EndpointPortBuilder().withPort(8080).build()) + .withAddresses(new V1EndpointAddressBuilder().withIp("127.0.0.1").build()) + .build()) + .withMetadata(new V1ObjectMetaBuilder().withName("no-port-name-service").withNamespace(NAMESPACE).build()) + .build(); endpointsCache.add(endpoints); V1Service service = new V1ServiceBuilder() - .withSpec( - new V1ServiceSpecBuilder().withPorts(new V1ServicePortBuilder().withPort(8080).build()).build()) - .withMetadata( - new V1ObjectMetaBuilder().withName("no-port-name-service").withNamespace(NAMESPACE).build()) - .withSpec(new V1ServiceSpecBuilder().withType("ClusterIP").build()).build(); + .withSpec(new V1ServiceSpecBuilder().withPorts(new V1ServicePortBuilder().withPort(8080).build()).build()) + .withMetadata(new V1ObjectMetaBuilder().withName("no-port-name-service").withNamespace(NAMESPACE).build()) + .withSpec(new V1ServiceSpecBuilder().withType("ClusterIP").build()) + .build(); servicesCache.add(service); KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, false, Set.of(NAMESPACE), diff --git a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientTests.java b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientTests.java index b531bf3083..9ea92ffcd6 100644 --- a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientTests.java +++ b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientTests.java @@ -97,8 +97,11 @@ void getInstancesShouldBeAbleToHandleEndpointsSingleAddress() { List instances = discoveryClient.getInstances("id"); - assertThat(instances).hasSize(1).filteredOn(s -> s.getHost().equals("ip1") && !s.isSecure()).hasSize(1) - .filteredOn(s -> s.getInstanceId().equals("10")).hasSize(1); + assertThat(instances).hasSize(1) + .filteredOn(s -> s.getHost().equals("ip1") && !s.isSecure()) + .hasSize(1) + .filteredOn(s -> s.getInstanceId().equals("10")) + .hasSize(1); } @Test @@ -124,9 +127,13 @@ void getInstancesShouldBeAbleToHandleEndpointsSingleAddressAndMultiplePorts() { List instances = discoveryClient.getInstances("endpoint"); - assertThat(instances).hasSize(1).filteredOn(s -> s.getHost().equals("ip1") && !s.isSecure()).hasSize(1) - .filteredOn(s -> s.getInstanceId().equals("20")).hasSize(1).filteredOn(s -> 80 == s.getPort()) - .hasSize(1); + assertThat(instances).hasSize(1) + .filteredOn(s -> s.getHost().equals("ip1") && !s.isSecure()) + .hasSize(1) + .filteredOn(s -> s.getInstanceId().equals("20")) + .hasSize(1) + .filteredOn(s -> 80 == s.getPort()) + .hasSize(1); } @Test @@ -154,8 +161,10 @@ void getInstancesShouldBeAbleToHandleEndpointsMultipleAddresses() { List instances = discoveryClient.getInstances("endpoint"); - assertThat(instances).hasSize(2).filteredOn(ServiceInstance::isSecure).extracting(ServiceInstance::getHost) - .containsOnly("ip1", "ip2"); + assertThat(instances).hasSize(2) + .filteredOn(ServiceInstance::isSecure) + .extracting(ServiceInstance::getHost) + .containsOnly("ip1", "ip2"); } @Test @@ -191,22 +200,33 @@ void getInstancesShouldBeAbleToHandleEndpointsFromMultipleNamespaces() { assertThat(instances).hasSize(2); assertThat(instances).filteredOn(s -> s.getHost().equals("ip1") && !s.isSecure()).hasSize(1); assertThat(instances).filteredOn(s -> s.getHost().equals("ip2") && !s.isSecure()).hasSize(1); - assertThat(instances).filteredOn(s -> s.getServiceId().contains("endpoint") - && ((KubernetesServiceInstance) s).getNamespace().equals("test")).hasSize(1); - assertThat(instances).filteredOn(s -> s.getServiceId().contains("endpoint") - && ((KubernetesServiceInstance) s).getNamespace().equals("test2")).hasSize(1); + assertThat(instances) + .filteredOn(s -> s.getServiceId().contains("endpoint") + && ((KubernetesServiceInstance) s).getNamespace().equals("test")) + .hasSize(1); + assertThat(instances) + .filteredOn(s -> s.getServiceId().contains("endpoint") + && ((KubernetesServiceInstance) s).getNamespace().equals("test2")) + .hasSize(1); assertThat(instances).filteredOn(s -> s.getInstanceId().equals("60")).hasSize(1); assertThat(instances).filteredOn(s -> s.getInstanceId().equals("70")).hasSize(1); } @Test void instanceWithoutSubsetsShouldBeSkipped() { - V1Endpoints endpoints = new V1EndpointsBuilder().withNewMetadata().withName("endpoint1").withNamespace("test") - .withLabels(Collections.emptyMap()).endMetadata().build(); + V1Endpoints endpoints = new V1EndpointsBuilder().withNewMetadata() + .withName("endpoint1") + .withNamespace("test") + .withLabels(Collections.emptyMap()) + .endMetadata() + .build(); endpointsCache.add(endpoints); - V1Service service = new V1ServiceBuilder().withNewMetadata().withName("endpoint1").withNamespace("test").and() - .build(); + V1Service service = new V1ServiceBuilder().withNewMetadata() + .withName("endpoint1") + .withNamespace("test") + .and() + .build(); servicesCache.add(service); KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, true, Set.of(), true, 60, @@ -242,9 +262,13 @@ void getInstancesShouldBeAbleToHandleEndpointsSingleAddressAndMultiplePortsUsing List instances = discoveryClient.getInstances("endpoint2"); - assertThat(instances).hasSize(1).filteredOn(s -> s.getHost().equals("ip1") && s.isSecure()).hasSize(1) - .filteredOn(s -> s.getInstanceId().equals("80")).hasSize(1).filteredOn(s -> 443 == s.getPort()) - .hasSize(1); + assertThat(instances).hasSize(1) + .filteredOn(s -> s.getHost().equals("ip1") && s.isSecure()) + .hasSize(1) + .filteredOn(s -> s.getInstanceId().equals("80")) + .hasSize(1) + .filteredOn(s -> 443 == s.getPort()) + .hasSize(1); } @Test @@ -270,8 +294,12 @@ void instanceWithMultiplePortsAndMisconfiguredPrimaryPortNameInLabelWithoutFallb List instances = discoveryClient.getInstances("endpoint3"); - assertThat(instances).hasSize(1).filteredOn(s -> s.getHost().equals("ip1") && s.isSecure()).hasSize(1) - .filteredOn(s -> s.getInstanceId().equals("90")).hasSize(1).hasSize(1); + assertThat(instances).hasSize(1) + .filteredOn(s -> s.getHost().equals("ip1") && s.isSecure()) + .hasSize(1) + .filteredOn(s -> s.getInstanceId().equals("90")) + .hasSize(1) + .hasSize(1); } @Test @@ -297,8 +325,12 @@ void instanceWithMultiplePortsAndMisconfiguredGenericPrimaryPortNameWithoutFallb List instances = discoveryClient.getInstances("endpoint4"); - assertThat(instances).hasSize(1).filteredOn(s -> s.getHost().equals("ip1") && s.isSecure()).hasSize(1) - .filteredOn(s -> s.getInstanceId().equals("100")).hasSize(1).hasSize(1); + assertThat(instances).hasSize(1) + .filteredOn(s -> s.getHost().equals("ip1") && s.isSecure()) + .hasSize(1) + .filteredOn(s -> s.getInstanceId().equals("100")) + .hasSize(1) + .hasSize(1); } @Test @@ -325,9 +357,13 @@ void instanceWithMultiplePortsAndWithoutPrimaryPortNameSpecifiedShouldFallBackTo List instances = discoveryClient.getInstances("endpoint5"); - assertThat(instances).hasSize(1).filteredOn(s -> s.getHost().equals("ip1") && s.isSecure()).hasSize(1) - .filteredOn(s -> s.getInstanceId().equals("110")).hasSize(1).filteredOn(s -> 443 == s.getPort()) - .hasSize(1); + assertThat(instances).hasSize(1) + .filteredOn(s -> s.getHost().equals("ip1") && s.isSecure()) + .hasSize(1) + .filteredOn(s -> s.getInstanceId().equals("110")) + .hasSize(1) + .filteredOn(s -> 443 == s.getPort()) + .hasSize(1); } @Test @@ -351,9 +387,13 @@ void instanceWithMultiplePortsAndWithoutPrimaryPortNameSpecifiedOrHttpsPortShoul List instances = discoveryClient.getInstances("endpoint5"); - assertThat(instances).hasSize(1).filteredOn(s -> s.getHost().equals("ip1") && !s.isSecure()).hasSize(1) - .filteredOn(s -> s.getInstanceId().equals("120")).hasSize(1).filteredOn(s -> 80 == s.getPort()) - .hasSize(1); + assertThat(instances).hasSize(1) + .filteredOn(s -> s.getHost().equals("ip1") && !s.isSecure()) + .hasSize(1) + .filteredOn(s -> s.getInstanceId().equals("120")) + .hasSize(1) + .filteredOn(s -> 80 == s.getPort()) + .hasSize(1); } @Test @@ -380,9 +420,13 @@ void instanceWithMultiplePortsAndWithoutPrimaryPortNameSpecifiedShouldLogWarning List instances = discoveryClient.getInstances("endpoint5"); // We're returning the first discovered port to not change previous behaviour - assertThat(instances).hasSize(1).filteredOn(s -> s.getHost().equals("ip1") && s.isSecure()).hasSize(1) - .filteredOn(s -> s.getInstanceId().equals("130")).hasSize(1).filteredOn(s -> 443 == s.getPort()) - .hasSize(1); + assertThat(instances).hasSize(1) + .filteredOn(s -> s.getHost().equals("ip1") && s.isSecure()) + .hasSize(1) + .filteredOn(s -> s.getInstanceId().equals("130")) + .hasSize(1) + .filteredOn(s -> 443 == s.getPort()) + .hasSize(1); } @Test @@ -408,10 +452,14 @@ public void instanceWithoutPorts() { List instances = discoveryClient.getInstances("endpoint5"); // We're returning the first discovered port to not change previous behaviour - assertThat(instances).hasSize(1).filteredOn(s -> s.getHost().equals("ip1") && !s.isSecure()).hasSize(1) - .filteredOn(s -> s.getUri().toASCIIString().equals("http://ip1")) - .filteredOn(s -> s.getInstanceId().equals("130")).hasSize(1).filteredOn(s -> 0 == s.getPort()) - .hasSize(1); + assertThat(instances).hasSize(1) + .filteredOn(s -> s.getHost().equals("ip1") && !s.isSecure()) + .hasSize(1) + .filteredOn(s -> s.getUri().toASCIIString().equals("http://ip1")) + .filteredOn(s -> s.getInstanceId().equals("130")) + .hasSize(1) + .filteredOn(s -> 0 == s.getPort()) + .hasSize(1); } private void setup(String serviceId, String serviceType, String namespace, Map labels, @@ -419,8 +467,12 @@ private void setup(String serviceId, String serviceType, String namespace, Map appProtocols) { V1Service service = new V1ServiceBuilder().withSpec(new V1ServiceSpecBuilder().withType(serviceType).build()) - .withNewMetadata().withName(serviceId).withNamespace(namespace).withLabels(labels).endMetadata() - .build(); + .withNewMetadata() + .withName(serviceId) + .withNamespace(namespace) + .withLabels(labels) + .endMetadata() + .build(); servicesCache.add(service); @@ -428,13 +480,20 @@ private void setup(String serviceId, String serviceType, String namespace, Map addresses = new ArrayList<>(); for (int i = 0; i < ips.size(); ++i) { - V1EndpointAddress address = new V1EndpointAddressBuilder().withIp(ips.get(i)).withNewTargetRef() - .withUid(uuids.get(i)).endTargetRef().build(); + V1EndpointAddress address = new V1EndpointAddressBuilder().withIp(ips.get(i)) + .withNewTargetRef() + .withUid(uuids.get(i)) + .endTargetRef() + .build(); addresses.add(address); } @@ -444,7 +503,10 @@ private void setup(String serviceId, String serviceType, String namespace, Map corePorts = new ArrayList<>(); for (int i = 0; i < names.size(); ++i) { CoreV1EndpointPort port = new CoreV1EndpointPortBuilder().withName(names.get(i)) - .withProtocol(protocols.get(i)).withPort(ports.get(i)).withAppProtocol(appProtocols.get(i)).build(); + .withProtocol(protocols.get(i)) + .withPort(ports.get(i)) + .withAppProtocol(appProtocols.get(i)) + .build(); corePorts.add(port); } subset.setPorts(corePorts); diff --git a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientUtilsTests.java b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientUtilsTests.java index 4cf2620b7a..19e0a15e6f 100644 --- a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientUtilsTests.java +++ b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientUtilsTests.java @@ -58,7 +58,7 @@ void testEmptyServiceLabelsFromProperties(CapturedOutput output) { boolean result = matchesServiceLabels(service, properties); Assertions.assertTrue(result); Assertions.assertTrue(output.getOut() - .contains("service labels from properties are empty, service with name : 'my-service' will match")); + .contains("service labels from properties are empty, service with name : 'my-service' will match")); } /** @@ -91,7 +91,8 @@ void testOne(CapturedOutput output) { KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, true, Set.of(), true, 60L, true, "", Set.of(), propertiesLabels, "", null, 0, false); V1Service service = new V1ServiceBuilder() - .withMetadata(new V1ObjectMeta().labels(serviceLabels).name("my-service")).build(); + .withMetadata(new V1ObjectMeta().labels(serviceLabels).name("my-service")) + .build(); boolean result = matchesServiceLabels(service, properties); Assertions.assertTrue(result); @@ -114,7 +115,8 @@ void testTwo(CapturedOutput output) { KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, true, Set.of(), true, 60L, true, "", Set.of(), propertiesLabels, "", null, 0, false); V1Service service = new V1ServiceBuilder() - .withMetadata(new V1ObjectMeta().labels(serviceLabels).name("my-service")).build(); + .withMetadata(new V1ObjectMeta().labels(serviceLabels).name("my-service")) + .build(); boolean result = matchesServiceLabels(service, properties); Assertions.assertFalse(result); @@ -137,7 +139,8 @@ void testThree(CapturedOutput output) { KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, true, Set.of(), true, 60L, true, "", Set.of(), propertiesLabels, "", null, 0, false); V1Service service = new V1ServiceBuilder() - .withMetadata(new V1ObjectMeta().labels(serviceLabels).name("my-service")).build(); + .withMetadata(new V1ObjectMeta().labels(serviceLabels).name("my-service")) + .build(); boolean result = matchesServiceLabels(service, properties); Assertions.assertTrue(result); @@ -160,7 +163,8 @@ void testFour(CapturedOutput output) { KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, true, Set.of(), true, 60L, true, "", Set.of(), propertiesLabels, "", null, 0, false); V1Service service = new V1ServiceBuilder() - .withMetadata(new V1ObjectMeta().labels(serviceLabels).name("my-service")).build(); + .withMetadata(new V1ObjectMeta().labels(serviceLabels).name("my-service")) + .build(); boolean result = matchesServiceLabels(service, properties); Assertions.assertTrue(result); @@ -172,9 +176,11 @@ void testFour(CapturedOutput output) { void testPortsDataOne() { List endpointSubsets = List.of( new V1EndpointSubsetBuilder() - .withPorts(new CoreV1EndpointPortBuilder().withPort(8081).withName("").build()).build(), + .withPorts(new CoreV1EndpointPortBuilder().withPort(8081).withName("").build()) + .build(), new V1EndpointSubsetBuilder() - .withPorts(new CoreV1EndpointPortBuilder().withPort(8080).withName("https").build()).build()); + .withPorts(new CoreV1EndpointPortBuilder().withPort(8080).withName("https").build()) + .build()); Map portsData = endpointSubsetsPortData(endpointSubsets); Assertions.assertEquals(portsData.size(), 2); @@ -186,9 +192,11 @@ void testPortsDataOne() { void testPortsDataTwo() { List endpointSubsets = List.of( new V1EndpointSubsetBuilder() - .withPorts(new CoreV1EndpointPortBuilder().withPort(8081).withName("http").build()).build(), + .withPorts(new CoreV1EndpointPortBuilder().withPort(8081).withName("http").build()) + .build(), new V1EndpointSubsetBuilder() - .withPorts(new CoreV1EndpointPortBuilder().withPort(8080).withName("https").build()).build()); + .withPorts(new CoreV1EndpointPortBuilder().withPort(8080).withName("https").build()) + .build()); Map portsData = endpointSubsetsPortData(endpointSubsets); Assertions.assertEquals(portsData.size(), 2); @@ -207,7 +215,8 @@ void endpointSubsetPortsDataWithoutPorts() { @Test void endpointSubsetPortsDataSinglePort() { V1EndpointSubset endpointSubset = new V1EndpointSubsetBuilder() - .withPorts(new CoreV1EndpointPortBuilder().withName("name").withPort(80).build()).build(); + .withPorts(new CoreV1EndpointPortBuilder().withName("name").withPort(80).build()) + .build(); Map result = endpointSubsetsPortData(List.of(endpointSubset)); Assertions.assertEquals(result.size(), 1); @@ -217,7 +226,8 @@ void endpointSubsetPortsDataSinglePort() { @Test void endpointSubsetPortsDataSinglePortNoName() { V1EndpointSubset endpointSubset = new V1EndpointSubsetBuilder() - .withPorts(new CoreV1EndpointPortBuilder().withPort(80).build()).build(); + .withPorts(new CoreV1EndpointPortBuilder().withPort(80).build()) + .build(); Map result = endpointSubsetsPortData(List.of(endpointSubset)); Assertions.assertEquals(result.size(), 1); @@ -252,9 +262,9 @@ void testReadyAddressesOnly() { KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, true, Set.of(), true, 60L, includeNotReadyAddresses, "", Set.of(), Map.of(), "", null, 0, false); V1EndpointSubset endpointSubset = new V1EndpointSubsetBuilder() - .withAddresses(new V1EndpointAddressBuilder().withHostname("one").build(), - new V1EndpointAddressBuilder().withHostname("two").build()) - .build(); + .withAddresses(new V1EndpointAddressBuilder().withHostname("one").build(), + new V1EndpointAddressBuilder().withHostname("two").build()) + .build(); List addresses = KubernetesDiscoveryClientUtils.addresses(endpointSubset, properties); Assertions.assertEquals(addresses.size(), 2); } @@ -271,9 +281,10 @@ void testReadyAddressesTakenNotReadyAddressesNotTaken() { KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, true, Set.of(), true, 60L, includeNotReadyAddresses, "", Set.of(), Map.of(), "", null, 0, false, false); V1EndpointSubset endpointSubset = new V1EndpointSubsetBuilder() - .withAddresses(new V1EndpointAddressBuilder().withHostname("one").build(), - new V1EndpointAddressBuilder().withHostname("two").build()) - .withNotReadyAddresses(new V1EndpointAddressBuilder().withHostname("three").build()).build(); + .withAddresses(new V1EndpointAddressBuilder().withHostname("one").build(), + new V1EndpointAddressBuilder().withHostname("two").build()) + .withNotReadyAddresses(new V1EndpointAddressBuilder().withHostname("three").build()) + .build(); List addresses = KubernetesDiscoveryClientUtils.addresses(endpointSubset, properties); Assertions.assertEquals(addresses.size(), 2); List hostNames = addresses.stream().map(V1EndpointAddress::getHostname).sorted().toList(); @@ -292,9 +303,10 @@ void testBothAddressesTaken() { KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, true, Set.of(), true, 60L, includeNotReadyAddresses, "", Set.of(), Map.of(), "", null, 0, false); V1EndpointSubset endpointSubset = new V1EndpointSubsetBuilder() - .withAddresses(new V1EndpointAddressBuilder().withHostname("one").build(), - new V1EndpointAddressBuilder().withHostname("two").build()) - .withNotReadyAddresses(new V1EndpointAddressBuilder().withHostname("three").build()).build(); + .withAddresses(new V1EndpointAddressBuilder().withHostname("one").build(), + new V1EndpointAddressBuilder().withHostname("two").build()) + .withNotReadyAddresses(new V1EndpointAddressBuilder().withHostname("three").build()) + .build(); List addresses = KubernetesDiscoveryClientUtils.addresses(endpointSubset, properties); Assertions.assertEquals(addresses.size(), 3); List hostNames = addresses.stream().map(V1EndpointAddress::getHostname).sorted().toList(); @@ -303,8 +315,11 @@ void testBothAddressesTaken() { // preserve order for testing reasons private Map ordered(Map input) { - return input.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect( - Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (left, right) -> left, LinkedHashMap::new)); + return input.entrySet() + .stream() + .sorted(Map.Entry.comparingByKey()) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (left, right) -> left, + LinkedHashMap::new)); } } diff --git a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesInformerDiscoveryClientAutoConfigurationApplicationContextTests.java b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesInformerDiscoveryClientAutoConfigurationApplicationContextTests.java index 58c7329f82..0345e21f1b 100644 --- a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesInformerDiscoveryClientAutoConfigurationApplicationContextTests.java +++ b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesInformerDiscoveryClientAutoConfigurationApplicationContextTests.java @@ -426,21 +426,23 @@ void reactiveDisabledWithSelectiveNamespaces() { private void setup(String... properties) { applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(KubernetesInformerDiscoveryClientAutoConfiguration.class, - KubernetesClientAutoConfiguration.class, KubernetesDiscoveryPropertiesAutoConfiguration.class, - KubernetesClientInformerAutoConfiguration.class, - KubernetesClientInformerSelectiveNamespacesAutoConfiguration.class)) - .withUserConfiguration(ApiClientConfig.class).withPropertyValues(properties); + .withConfiguration(AutoConfigurations.of(KubernetesInformerDiscoveryClientAutoConfiguration.class, + KubernetesClientAutoConfiguration.class, KubernetesDiscoveryPropertiesAutoConfiguration.class, + KubernetesClientInformerAutoConfiguration.class, + KubernetesClientInformerSelectiveNamespacesAutoConfiguration.class)) + .withUserConfiguration(ApiClientConfig.class) + .withPropertyValues(properties); } private void setupWithFilteredClassLoader(Class cls, String... properties) { applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(KubernetesInformerDiscoveryClientAutoConfiguration.class, - KubernetesClientAutoConfiguration.class, KubernetesDiscoveryPropertiesAutoConfiguration.class, - KubernetesClientInformerAutoConfiguration.class, - KubernetesClientInformerSelectiveNamespacesAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(cls)).withUserConfiguration(ApiClientConfig.class) - .withPropertyValues(properties); + .withConfiguration(AutoConfigurations.of(KubernetesInformerDiscoveryClientAutoConfiguration.class, + KubernetesClientAutoConfiguration.class, KubernetesDiscoveryPropertiesAutoConfiguration.class, + KubernetesClientInformerAutoConfiguration.class, + KubernetesClientInformerSelectiveNamespacesAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(cls)) + .withUserConfiguration(ApiClientConfig.class) + .withPropertyValues(properties); } @Configuration diff --git a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesInformerDiscoveryClientTests.java b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesInformerDiscoveryClientTests.java index a83aeeac37..0eefaeed8c 100644 --- a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesInformerDiscoveryClientTests.java +++ b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/KubernetesInformerDiscoveryClientTests.java @@ -107,9 +107,9 @@ void testServiceWithUnsetPortNames() { SHARED_INFORMER_FACTORY, serviceLister, endpointsLister, null, null, ALL_NAMESPACES); assertThat(discoveryClient.getInstances("test-svc-1").toArray()) - .containsOnly(new DefaultKubernetesServiceInstance(null, "test-svc-1", "1.1.1.1", 80, - Map.of("port.", "80", "k8s_namespace", "namespace1", "type", "ClusterIP"), false, - "namespace1", null)); + .containsOnly(new DefaultKubernetesServiceInstance(null, "test-svc-1", "1.1.1.1", 80, + Map.of("port.", "80", "k8s_namespace", "namespace1", "type", "ClusterIP"), false, + "namespace1", null)); } @Test @@ -153,8 +153,8 @@ void testDiscoveryInstancesWithServiceLabels() { SHARED_INFORMER_FACTORY, serviceLister, endpointsLister, null, null, kubernetesDiscoveryProperties); assertThat(discoveryClient.getInstances("test-svc-1").toArray()).isEmpty(); - assertThat(discoveryClient.getInstances("test-svc-3").toArray()) - .containsOnly(new DefaultKubernetesServiceInstance( + assertThat(discoveryClient.getInstances("test-svc-3").toArray()).containsOnly( + new DefaultKubernetesServiceInstance( null, "test-svc-3", "2.2.2.2", 8080, Map.of("spring", "true", "port.", "8080", "k8s", "true", "k8s_namespace", "namespace1", "type", "ClusterIP"), false, "namespace1", null)); @@ -205,9 +205,9 @@ void testDiscoveryGetInstanceAllNamespaceShouldWork() { SHARED_INFORMER_FACTORY, serviceLister, endpointsLister, null, null, ALL_NAMESPACES); assertThat(discoveryClient.getInstances("test-svc-1")) - .containsOnly(new DefaultKubernetesServiceInstance(null, "test-svc-1", "2.2.2.2", 8080, - Map.of("port.", "8080", "k8s_namespace", "namespace1", "type", "ClusterIP"), false, - "namespace1", null)); + .containsOnly(new DefaultKubernetesServiceInstance(null, "test-svc-1", "2.2.2.2", 8080, + Map.of("port.", "8080", "k8s_namespace", "namespace1", "type", "ClusterIP"), false, + "namespace1", null)); } @Test @@ -219,9 +219,9 @@ void testDiscoveryGetInstanceOneNamespaceShouldWork() { SHARED_INFORMER_FACTORY, serviceLister, endpointsLister, null, null, NOT_ALL_NAMESPACES); assertThat(discoveryClient.getInstances("test-svc-1")) - .containsOnly(new DefaultKubernetesServiceInstance(null, "test-svc-1", "2.2.2.2", 8080, - Map.of("port.", "8080", "k8s_namespace", "namespace1", "type", "ClusterIP"), false, - "namespace1", null)); + .containsOnly(new DefaultKubernetesServiceInstance(null, "test-svc-1", "2.2.2.2", 8080, + Map.of("port.", "8080", "k8s_namespace", "namespace1", "type", "ClusterIP"), false, + "namespace1", null)); } @Test @@ -249,9 +249,9 @@ void testDiscoveryGetInstanceWithNotReadyAddressesIncludedShouldWork() { SHARED_INFORMER_FACTORY, serviceLister, endpointsLister, null, null, kubernetesDiscoveryProperties); assertThat(discoveryClient.getInstances("test-svc-1")) - .containsOnly(new DefaultKubernetesServiceInstance(null, "test-svc-1", "2.2.2.2", 8080, - Map.of("port.", "8080", "k8s_namespace", "namespace1", "type", "ClusterIP"), false, - "namespace1", null)); + .containsOnly(new DefaultKubernetesServiceInstance(null, "test-svc-1", "2.2.2.2", 8080, + Map.of("port.", "8080", "k8s_namespace", "namespace1", "type", "ClusterIP"), false, + "namespace1", null)); } @Test @@ -276,8 +276,8 @@ void instanceWithoutPortsWillNotBeSkipped() { KubernetesDiscoveryProperties.DEFAULT); assertThat(discoveryClient.getInstances("test-svc-1")) - .containsOnly(new DefaultKubernetesServiceInstance(null, "test-svc-1", "1.1.1.1", 0, - Map.of("k8s_namespace", "namespace1", "type", "ClusterIP"), false, "namespace1", null)); + .containsOnly(new DefaultKubernetesServiceInstance(null, "test-svc-1", "1.1.1.1", 0, + Map.of("k8s_namespace", "namespace1", "type", "ClusterIP"), false, "namespace1", null)); } @Test @@ -304,10 +304,10 @@ void instanceWithMultiplePortsAndMisconfiguredPrimaryPortNameInLabelShouldReturn SHARED_INFORMER_FACTORY, serviceLister, endpointsLister, null, null, NOT_ALL_NAMESPACES); assertThat(discoveryClient.getInstances("test-svc-1")) - .containsOnly(new DefaultKubernetesServiceInstance( - null, "test-svc-1", "1.1.1.1", 80, Map.of("port.tcp1", "80", "primary-port-name", "oops", - "port.tcp2", "443", "k8s_namespace", "namespace1", "type", "ClusterIP"), - false, "namespace1", null)); + .containsOnly(new DefaultKubernetesServiceInstance( + null, "test-svc-1", "1.1.1.1", 80, Map.of("port.tcp1", "80", "primary-port-name", "oops", + "port.tcp2", "443", "k8s_namespace", "namespace1", "type", "ClusterIP"), + false, "namespace1", null)); } @Test @@ -318,10 +318,10 @@ void instanceWithMultiplePortsAndGenericPrimaryPortNameConfiguredShouldWork() { KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient( SHARED_INFORMER_FACTORY, serviceLister, endpointsLister, null, null, NOT_ALL_NAMESPACES); - assertThat(discoveryClient.getInstances("test-svc-1")).containsOnly(new DefaultKubernetesServiceInstance(null, - "test-svc-1", "1.1.1.1", 443, - Map.of("port.http", "80", "port.https", "443", "k8s_namespace", "namespace1", "type", "ClusterIP"), - true, "namespace1", null)); + assertThat(discoveryClient.getInstances("test-svc-1")) + .containsOnly(new DefaultKubernetesServiceInstance(null, "test-svc-1", "1.1.1.1", 443, + Map.of("port.http", "80", "port.https", "443", "k8s_namespace", "namespace1", "type", "ClusterIP"), + true, "namespace1", null)); } @Test @@ -333,10 +333,10 @@ void instanceWithMultiplePortsAndMisconfiguredGenericPrimaryPortNameShouldReturn KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient( SHARED_INFORMER_FACTORY, serviceLister, endpointsLister, null, null, NOT_ALL_NAMESPACES); - assertThat(discoveryClient.getInstances("test-svc-1")).containsOnly(new DefaultKubernetesServiceInstance(null, - "test-svc-1", "1.1.1.1", 80, - Map.of("port.tcp1", "80", "port.tcp2", "443", "k8s_namespace", "namespace1", "type", "ClusterIP"), - false, "namespace1", null)); + assertThat(discoveryClient.getInstances("test-svc-1")) + .containsOnly(new DefaultKubernetesServiceInstance(null, "test-svc-1", "1.1.1.1", 80, + Map.of("port.tcp1", "80", "port.tcp2", "443", "k8s_namespace", "namespace1", "type", "ClusterIP"), + false, "namespace1", null)); } @Test @@ -347,10 +347,10 @@ void instanceWithMultiplePortsAndWithoutPrimaryPortNameSpecifiedShouldFallBackTo KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient( SHARED_INFORMER_FACTORY, serviceLister, endpointsLister, null, null, NOT_ALL_NAMESPACES); - assertThat(discoveryClient.getInstances("test-svc-1")).containsOnly(new DefaultKubernetesServiceInstance(null, - "test-svc-1", "1.1.1.1", 443, - Map.of("port.http", "80", "port.https", "443", "k8s_namespace", "namespace1", "type", "ClusterIP"), - true, "namespace1", null)); + assertThat(discoveryClient.getInstances("test-svc-1")) + .containsOnly(new DefaultKubernetesServiceInstance(null, "test-svc-1", "1.1.1.1", 443, + Map.of("port.http", "80", "port.https", "443", "k8s_namespace", "namespace1", "type", "ClusterIP"), + true, "namespace1", null)); } @Test @@ -361,10 +361,10 @@ void instanceWithMultiplePortsAndWithoutPrimaryPortNameSpecifiedOrHttpsPortShoul KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient( SHARED_INFORMER_FACTORY, serviceLister, endpointsLister, null, null, NOT_ALL_NAMESPACES); - assertThat(discoveryClient.getInstances("test-svc-1")).containsOnly(new DefaultKubernetesServiceInstance(null, - "test-svc-1", "1.1.1.1", 80, - Map.of("port.http", "80", "port.tcp", "443", "k8s_namespace", "namespace1", "type", "ClusterIP"), false, - "namespace1", null)); + assertThat(discoveryClient.getInstances("test-svc-1")) + .containsOnly(new DefaultKubernetesServiceInstance(null, "test-svc-1", "1.1.1.1", 80, + Map.of("port.http", "80", "port.tcp", "443", "k8s_namespace", "namespace1", "type", "ClusterIP"), + false, "namespace1", null)); } @Test @@ -376,10 +376,10 @@ void instanceWithMultiplePortsAndWithoutAnyConfigurationShouldPickTheFirstPort() KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient( SHARED_INFORMER_FACTORY, serviceLister, endpointsLister, null, null, NOT_ALL_NAMESPACES); - assertThat(discoveryClient.getInstances("test-svc-1")).containsOnly(new DefaultKubernetesServiceInstance(null, - "test-svc-1", "1.1.1.1", 80, - Map.of("port.tcp1", "80", "port.tcp2", "443", "k8s_namespace", "namespace1", "type", "ClusterIP"), - false, "namespace1", null)); + assertThat(discoveryClient.getInstances("test-svc-1")) + .containsOnly(new DefaultKubernetesServiceInstance(null, "test-svc-1", "1.1.1.1", 80, + Map.of("port.tcp1", "80", "port.tcp2", "443", "k8s_namespace", "namespace1", "type", "ClusterIP"), + false, "namespace1", null)); } @Test @@ -439,8 +439,10 @@ void testOneServiceMatchesFilter() { // only one here because of distinct assertThat(discoveryClient.getServices()).contains("test-svc-1"); - List result = discoveryClient.getInstances("test-svc-1").stream() - .sorted(Comparator.comparing(res -> res.getMetadata().get("k8s_namespace"))).toList(); + List result = discoveryClient.getInstances("test-svc-1") + .stream() + .sorted(Comparator.comparing(res -> res.getMetadata().get("k8s_namespace"))) + .toList(); assertThat(result.get(0).getMetadata().get("k8s_namespace")).isEqualTo("namespace1"); assertThat(result.get(1).getMetadata().get("k8s_namespace")).isEqualTo("namespace2"); @@ -457,8 +459,10 @@ void testOneServiceMatchesFilter() { // only one here because of distinct assertThat(discoveryClient.getServices()).contains("test-svc-1"); - result = discoveryClient.getInstances("test-svc-1").stream() - .sorted(Comparator.comparing(res -> res.getMetadata().get("k8s_namespace"))).toList(); + result = discoveryClient.getInstances("test-svc-1") + .stream() + .sorted(Comparator.comparing(res -> res.getMetadata().get("k8s_namespace"))) + .toList(); assertThat(result.size()).isEqualTo(1); assertThat(result.get(0).getMetadata().get("k8s_namespace")).isEqualTo("namespace1"); @@ -505,8 +509,10 @@ void testServicesWithSameMetadataLabels() { KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient( SHARED_INFORMER_FACTORY, serviceLister, endpointsLister, null, null, properties); - List serviceInstances = discoveryClient.getInstances("serviceX").stream() - .sorted(Comparator.comparing(x -> x.getMetadata().get("k8s_namespace"))).toList(); + List serviceInstances = discoveryClient.getInstances("serviceX") + .stream() + .sorted(Comparator.comparing(x -> x.getMetadata().get("k8s_namespace"))) + .toList(); assertThat(serviceInstances.size()).isEqualTo(2); assertThat(serviceInstances.get(0).getMetadata().get("k8s_namespace")).isEqualTo("namespaceA"); assertThat(serviceInstances.get(1).getMetadata().get("k8s_namespace")).isEqualTo("namespaceB"); @@ -515,12 +521,17 @@ void testServicesWithSameMetadataLabels() { @Test void testExternalNameService() { V1Service externalNameService = new V1ServiceBuilder() - .withSpec(new V1ServiceSpecBuilder().withType("ExternalName").withExternalName("k8s-spring-b").build()) - .withNewMetadata().withLabels(Map.of("label-key", "label-value")).withAnnotations(Map.of("abc", "def")) - .withName("blue-service").withNamespace("b").endMetadata().build(); + .withSpec(new V1ServiceSpecBuilder().withType("ExternalName").withExternalName("k8s-spring-b").build()) + .withNewMetadata() + .withLabels(Map.of("label-key", "label-value")) + .withAnnotations(Map.of("abc", "def")) + .withName("blue-service") + .withNamespace("b") + .endMetadata() + .build(); V1Endpoints endpoints = new V1EndpointsBuilder().withMetadata(new V1ObjectMeta().namespace("irrelevant")) - .build(); + .build(); Lister serviceLister = setupServiceLister(externalNameService); Lister endpointsLister = setupEndpointsLister(endpoints); @@ -548,18 +559,21 @@ void testExternalNameService() { @Test void testPodMetadata() { V1Service nonExternalNameService = new V1ServiceBuilder() - .withSpec(new V1ServiceSpecBuilder().withType("ClusterIP").build()).withNewMetadata() - .withName("blue-service").withNamespace("a").endMetadata().build(); + .withSpec(new V1ServiceSpecBuilder().withType("ClusterIP").build()) + .withNewMetadata() + .withName("blue-service") + .withNamespace("a") + .endMetadata() + .build(); V1Endpoints endpoints = new V1EndpointsBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("blue-service").withNamespace("a").build()) - .withSubsets( - new V1EndpointSubsetBuilder().withPorts(new CoreV1EndpointPortBuilder().withPort(8080).build()) - .withAddresses(new V1EndpointAddressBuilder().withIp("127.0.0.1").withTargetRef( - new V1ObjectReferenceBuilder().withKind("Pod").withName("my-pod").build()) - .build()) - .build()) - .build(); + .withMetadata(new V1ObjectMetaBuilder().withName("blue-service").withNamespace("a").build()) + .withSubsets(new V1EndpointSubsetBuilder().withPorts(new CoreV1EndpointPortBuilder().withPort(8080).build()) + .withAddresses(new V1EndpointAddressBuilder().withIp("127.0.0.1") + .withTargetRef(new V1ObjectReferenceBuilder().withKind("Pod").withName("my-pod").build()) + .build()) + .build()) + .build(); Lister serviceLister = setupServiceLister(nonExternalNameService); Lister endpointsLister = setupEndpointsLister(endpoints); @@ -569,11 +583,15 @@ void testPodMetadata() { WireMock.configureFor("localhost", server.port()); ApiClient apiClient = new ClientBuilder().setBasePath("http://localhost:" + server.port()).build(); - V1Pod pod = new V1PodBuilder().withNewMetadata().withName("my-pod").withLabels(Map.of("a", "b")) - .withAnnotations(Map.of("c", "d")).endMetadata().build(); + V1Pod pod = new V1PodBuilder().withNewMetadata() + .withName("my-pod") + .withLabels(Map.of("a", "b")) + .withAnnotations(Map.of("c", "d")) + .endMetadata() + .build(); WireMock.stubFor(WireMock.get("/api/v1/namespaces/a/pods/my-pod") - .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(pod)))); + .willReturn(WireMock.aResponse().withStatus(200).withBody(new JSON().serialize(pod)))); KubernetesDiscoveryProperties.Metadata metadata = new KubernetesDiscoveryProperties.Metadata(true, "labels-prefix-", true, "annotations-prefix-", true, "ports-prefix", true, true); @@ -620,51 +638,51 @@ private Lister setupEndpointsLister(V1Endpoints... endpoints) { private static V1Service service(String name, String namespace, Map labels) { return new V1Service().metadata(new V1ObjectMeta().name(name).namespace(namespace).labels(labels)) - .spec(new V1ServiceSpec().type("ClusterIP")); + .spec(new V1ServiceSpec().type("ClusterIP")); } private static V1Endpoints endpointsReadyAddress(String name, String namespace) { return new V1Endpoints().metadata(new V1ObjectMeta().name(name).namespace(namespace)) - .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(8080)) - .addAddressesItem(new V1EndpointAddress().ip("2.2.2.2"))); + .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(8080)) + .addAddressesItem(new V1EndpointAddress().ip("2.2.2.2"))); } private static V1Endpoints endpointsNotReadyAddress() { return new V1Endpoints().metadata(new V1ObjectMeta().name("test-svc-1").namespace("namespace1")) - .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(8080)) - .addNotReadyAddressesItem(new V1EndpointAddress().ip("2.2.2.2"))); + .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(8080)) + .addNotReadyAddressesItem(new V1EndpointAddress().ip("2.2.2.2"))); } private static V1Endpoints endpointsNoPorts() { return new V1Endpoints().metadata(new V1ObjectMeta().name("test-svc-1").namespace("namespace1")) - .addSubsetsItem(new V1EndpointSubset().addAddressesItem(new V1EndpointAddress().ip("1.1.1.1"))); + .addSubsetsItem(new V1EndpointSubset().addAddressesItem(new V1EndpointAddress().ip("1.1.1.1"))); } private static V1Endpoints endpointsNoUnsetPortName() { return new V1Endpoints().metadata(new V1ObjectMeta().name("test-svc-1").namespace("namespace1")) - .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(80)) - .addAddressesItem(new V1EndpointAddress().ip("1.1.1.1"))); + .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(80)) + .addAddressesItem(new V1EndpointAddress().ip("1.1.1.1"))); } private static V1Endpoints endpointsWithMultiplePorts() { return new V1Endpoints().metadata(new V1ObjectMeta().name("test-svc-1").namespace("namespace1")) - .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().name("http").port(80)) - .addPortsItem(new CoreV1EndpointPort().name("https").port(443)) - .addAddressesItem(new V1EndpointAddress().ip("1.1.1.1"))); + .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().name("http").port(80)) + .addPortsItem(new CoreV1EndpointPort().name("https").port(443)) + .addAddressesItem(new V1EndpointAddress().ip("1.1.1.1"))); } private static V1Endpoints endpointsWithMultiplePortsNoHttps() { return new V1Endpoints().metadata(new V1ObjectMeta().name("test-svc-1").namespace("namespace1")) - .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().name("http").port(80)) - .addPortsItem(new CoreV1EndpointPort().name("tcp").port(443)) - .addAddressesItem(new V1EndpointAddress().ip("1.1.1.1"))); + .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().name("http").port(80)) + .addPortsItem(new CoreV1EndpointPort().name("tcp").port(443)) + .addAddressesItem(new V1EndpointAddress().ip("1.1.1.1"))); } private static V1Endpoints endpointsMultiplePortsWithoutSupportedPortNames() { return new V1Endpoints().metadata(new V1ObjectMeta().name("test-svc-1").namespace("namespace1")) - .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().name("tcp1").port(80)) - .addPortsItem(new CoreV1EndpointPort().name("tcp2").port(443)) - .addAddressesItem(new V1EndpointAddress().ip("1.1.1.1"))); + .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().name("tcp1").port(80)) + .addPortsItem(new CoreV1EndpointPort().name("tcp2").port(443)) + .addAddressesItem(new V1EndpointAddress().ip("1.1.1.1"))); } private static KubernetesDiscoveryProperties properties(boolean allNamespaces, Map labels) { diff --git a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/TestUtils.java b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/TestUtils.java index 2cccd1f8fd..510e70fae9 100644 --- a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/TestUtils.java +++ b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/TestUtils.java @@ -42,9 +42,9 @@ private TestUtils() { } public static void assertSelectiveNamespacesBeansMissing(AssertableApplicationContext context) { - String[] sharedInformerFactoriesBeanName = context.getBeanNamesForType( - ResolvableType.forType(new ParameterizedTypeReference>() { - })); + String[] sharedInformerFactoriesBeanName = context + .getBeanNamesForType(ResolvableType.forType(new ParameterizedTypeReference>() { + })); assertThat(sharedInformerFactoriesBeanName).isEmpty(); String[] serviceSharedIndexInformersBeanName = context.getBeanNamesForType( @@ -58,50 +58,50 @@ public static void assertSelectiveNamespacesBeansMissing(AssertableApplicationCo assertThat(endpointsSharedIndexInformersBeanName).isEmpty(); String[] serviceListersBeanName = context - .getBeanNamesForType(ResolvableType.forType(new ParameterizedTypeReference>>() { - })); + .getBeanNamesForType(ResolvableType.forType(new ParameterizedTypeReference>>() { + })); assertThat(serviceListersBeanName).isEmpty(); - String[] endpointsListersBeanName = context.getBeanNamesForType( - ResolvableType.forType(new ParameterizedTypeReference>>() { - })); + String[] endpointsListersBeanName = context + .getBeanNamesForType(ResolvableType.forType(new ParameterizedTypeReference>>() { + })); assertThat(endpointsListersBeanName).isEmpty(); } @SuppressWarnings("unchecked") public static void assertSelectiveNamespacesBeansPresent(AssertableApplicationContext context, int times) { - String sharedInformerFactoriesBeanName = context.getBeanNamesForType( - ResolvableType.forType(new ParameterizedTypeReference>() { - }))[0]; + String sharedInformerFactoriesBeanName = context + .getBeanNamesForType(ResolvableType.forType(new ParameterizedTypeReference>() { + }))[0]; List sharedInformerFactories = (List) context - .getBean(sharedInformerFactoriesBeanName); + .getBean(sharedInformerFactoriesBeanName); assertThat(sharedInformerFactories.size()).isEqualTo(times); String serviceSharedIndexInformersBeanName = context.getBeanNamesForType( ResolvableType.forType(new ParameterizedTypeReference>>() { }))[0]; List> serviceSharedIndexInformers = (List>) context - .getBean(serviceSharedIndexInformersBeanName); + .getBean(serviceSharedIndexInformersBeanName); assertThat(serviceSharedIndexInformers.size()).isEqualTo(times); String endpointsSharedIndexInformersBeanName = context.getBeanNamesForType( ResolvableType.forType(new ParameterizedTypeReference>>() { }))[0]; List> endpointsSharedIndexInformers = (List>) context - .getBean(endpointsSharedIndexInformersBeanName); + .getBean(endpointsSharedIndexInformersBeanName); assertThat(endpointsSharedIndexInformers.size()).isEqualTo(times); String serviceListersBeanName = context - .getBeanNamesForType(ResolvableType.forType(new ParameterizedTypeReference>>() { - }))[0]; + .getBeanNamesForType(ResolvableType.forType(new ParameterizedTypeReference>>() { + }))[0]; List> serviceListers = (List>) context.getBean(serviceListersBeanName); assertThat(serviceListers.size()).isEqualTo(times); - String endpointsListersBeanName = context.getBeanNamesForType( - ResolvableType.forType(new ParameterizedTypeReference>>() { - }))[0]; + String endpointsListersBeanName = context + .getBeanNamesForType(ResolvableType.forType(new ParameterizedTypeReference>>() { + }))[0]; List> endpointsListers = (List>) context - .getBean(endpointsListersBeanName); + .getBean(endpointsListersBeanName); assertThat(endpointsListers.size()).isEqualTo(times); } @@ -113,25 +113,25 @@ public static void assertNonSelectiveNamespacesBeansPresent(AssertableApplicatio ResolvableType.forType(new ParameterizedTypeReference>() { }))[0]; SharedIndexInformer serviceSharedIndexInformer = (SharedIndexInformer) context - .getBean(serviceSharedIndexInformerBeanName); + .getBean(serviceSharedIndexInformerBeanName); assertThat(serviceSharedIndexInformer).isNotNull(); String endpointSharedIndexInformerBeanName = context.getBeanNamesForType( ResolvableType.forType(new ParameterizedTypeReference>() { }))[0]; SharedIndexInformer endpointsSharedIndexInformer = (SharedIndexInformer) context - .getBean(endpointSharedIndexInformerBeanName); + .getBean(endpointSharedIndexInformerBeanName); assertThat(endpointsSharedIndexInformer).isNotNull(); String serviceListerBeanName = context - .getBeanNamesForType(ResolvableType.forType(new ParameterizedTypeReference>() { - }))[0]; + .getBeanNamesForType(ResolvableType.forType(new ParameterizedTypeReference>() { + }))[0]; Lister serviceLister = (Lister) context.getBean(serviceListerBeanName); assertThat(serviceLister).isNotNull(); String endpointsListerBeanName = context - .getBeanNamesForType(ResolvableType.forType(new ParameterizedTypeReference>() { - }))[0]; + .getBeanNamesForType(ResolvableType.forType(new ParameterizedTypeReference>() { + }))[0]; Lister endpointsLister = (Lister) context.getBean(endpointsListerBeanName); assertThat(endpointsLister).isNotNull(); } @@ -148,13 +148,13 @@ public static void assertNonSelectiveNamespacesBeansMissing(AssertableApplicatio assertThat(endpointSharedIndexInformerBeanName).isEmpty(); String[] serviceListerBeanName = context - .getBeanNamesForType(ResolvableType.forType(new ParameterizedTypeReference>() { - })); + .getBeanNamesForType(ResolvableType.forType(new ParameterizedTypeReference>() { + })); assertThat(serviceListerBeanName).isEmpty(); String[] endpointsListerBeanName = context - .getBeanNamesForType(ResolvableType.forType(new ParameterizedTypeReference>() { - })); + .getBeanNamesForType(ResolvableType.forType(new ParameterizedTypeReference>() { + })); assertThat(endpointsListerBeanName).isEmpty(); } diff --git a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesCatalogWatchAutoConfigurationApplicationContextTests.java b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesCatalogWatchAutoConfigurationApplicationContextTests.java index cd54467cfd..bfcb945dd3 100644 --- a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesCatalogWatchAutoConfigurationApplicationContextTests.java +++ b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesCatalogWatchAutoConfigurationApplicationContextTests.java @@ -133,10 +133,10 @@ void disableKubernetesDiscovery() { private void setup(String... properties) { applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(KubernetesCatalogWatchAutoConfiguration.class, - KubernetesClientAutoConfiguration.class, KubernetesDiscoveryPropertiesAutoConfiguration.class, - KubernetesCommonsAutoConfiguration.class)) - .withPropertyValues(properties); + .withConfiguration(AutoConfigurations.of(KubernetesCatalogWatchAutoConfiguration.class, + KubernetesClientAutoConfiguration.class, KubernetesDiscoveryPropertiesAutoConfiguration.class, + KubernetesCommonsAutoConfiguration.class)) + .withPropertyValues(properties); } } diff --git a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesCatalogWatchEndpointSlicesTests.java b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesCatalogWatchEndpointSlicesTests.java index 72206d8cd3..e2b72963e1 100644 --- a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesCatalogWatchEndpointSlicesTests.java +++ b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesCatalogWatchEndpointSlicesTests.java @@ -74,8 +74,8 @@ public void afterEach() { @Test @Override void testInAllNamespacesEmptyServiceLabels() { - stubFor(get("/apis/discovery.k8s.io/v1/endpointslices?labelSelector=").willReturn( - aResponse().withStatus(200).withBody(new JSON().serialize(endpointSlices("a", "default"))))); + stubFor(get("/apis/discovery.k8s.io/v1/endpointslices?labelSelector=") + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpointSlices("a", "default"))))); KubernetesCatalogWatch watch = createWatcherInAllNamespacesWithLabels(Map.of(), Set.of(), null, apiClient, USE_ENDPOINT_SLICES); @@ -85,8 +85,8 @@ void testInAllNamespacesEmptyServiceLabels() { @Test @Override void testInAllNamespacesWithSingleLabel() { - stubFor(get("/apis/discovery.k8s.io/v1/endpointslices?labelSelector=a%3Db").willReturn( - aResponse().withStatus(200).withBody(new JSON().serialize(endpointSlices("a", "default"))))); + stubFor(get("/apis/discovery.k8s.io/v1/endpointslices?labelSelector=a%3Db") + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpointSlices("a", "default"))))); KubernetesCatalogWatch watch = createWatcherInAllNamespacesWithLabels(Map.of("a", "b"), Set.of(), null, apiClient, USE_ENDPOINT_SLICES); @@ -96,8 +96,8 @@ void testInAllNamespacesWithSingleLabel() { @Test @Override void testInAllNamespacesWithDoubleLabel() { - stubFor(get("/apis/discovery.k8s.io/v1/endpointslices?labelSelector=a%3Db%26c%3Dd").willReturn( - aResponse().withStatus(200).withBody(new JSON().serialize(endpointSlices("a", "default"))))); + stubFor(get("/apis/discovery.k8s.io/v1/endpointslices?labelSelector=a%3Db%26c%3Dd") + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpointSlices("a", "default"))))); // otherwise the stub might fail LinkedHashMap map = new LinkedHashMap<>(); map.put("a", "b"); @@ -112,7 +112,7 @@ void testInAllNamespacesWithDoubleLabel() { @Override void testInSpecificNamespacesEmptyServiceLabels() { stubFor(get("/apis/discovery.k8s.io/v1/namespaces/b/endpointslices?labelSelector=") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpointSlices("a", "b"))))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpointSlices("a", "b"))))); KubernetesCatalogWatch watch = createWatcherInSpecificNamespacesWithLabels(Set.of("b"), Map.of(), null, apiClient, USE_ENDPOINT_SLICES); @@ -123,9 +123,9 @@ void testInSpecificNamespacesEmptyServiceLabels() { @Override void testInSpecificNamespacesWithSingleLabel() { stubFor(get("/apis/discovery.k8s.io/v1/namespaces/one/endpointslices?labelSelector=a%3Db") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpointSlices("aa", "a"))))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpointSlices("aa", "a"))))); stubFor(get("/apis/discovery.k8s.io/v1/namespaces/two/endpointslices?labelSelector=a%3Db") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpointSlices("bb", "b"))))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpointSlices("bb", "b"))))); KubernetesCatalogWatch watch = createWatcherInSpecificNamespacesWithLabels(Set.of("one", "two"), Map.of("a", "b"), null, apiClient, USE_ENDPOINT_SLICES); @@ -138,9 +138,9 @@ void testInSpecificNamespacesWithSingleLabel() { @Override void testInSpecificNamespacesWithDoubleLabel() { stubFor(get("/apis/discovery.k8s.io/v1/namespaces/one/endpointslices?labelSelector=a%3Db%26c%3Dd") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpointSlices("aa", "a"))))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpointSlices("aa", "a"))))); stubFor(get("/apis/discovery.k8s.io/v1/namespaces/two/endpointslices?labelSelector=a%3Db%26c%3Dd") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpointSlices("bb", "b"))))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpointSlices("bb", "b"))))); // otherwise the stub might fail LinkedHashMap map = new LinkedHashMap<>(); @@ -158,7 +158,7 @@ void testInSpecificNamespacesWithDoubleLabel() { @Override void testInOneNamespaceEmptyServiceLabels() { stubFor(get("/apis/discovery.k8s.io/v1/namespaces/b/endpointslices?labelSelector=") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpointSlices("a", "b"))))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpointSlices("a", "b"))))); KubernetesCatalogWatch watch = createWatcherInSpecificNamespaceWithLabels("b", Map.of(), null, apiClient, USE_ENDPOINT_SLICES); @@ -169,7 +169,7 @@ void testInOneNamespaceEmptyServiceLabels() { @Override void testInOneNamespaceWithSingleLabel() { stubFor(get("/apis/discovery.k8s.io/v1/namespaces/b/endpointslices?labelSelector=key%3Dvalue") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpointSlices("a", "b"))))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpointSlices("a", "b"))))); KubernetesCatalogWatch watch = createWatcherInSpecificNamespaceWithLabels("b", Map.of("key", "value"), null, apiClient, USE_ENDPOINT_SLICES); @@ -180,7 +180,7 @@ void testInOneNamespaceWithSingleLabel() { @Override void testInOneNamespaceWithDoubleLabel() { stubFor(get("/apis/discovery.k8s.io/v1/namespaces/b/endpointslices?labelSelector=key%3Dvalue%26key1%3Dvalue1") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpointSlices("a", "b"))))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpointSlices("a", "b"))))); // otherwise the stub might fail LinkedHashMap map = new LinkedHashMap<>(); map.put("key", "value"); diff --git a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesCatalogWatchEndpointsTests.java b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesCatalogWatchEndpointsTests.java index f50fb75c0c..15f6e6e5fe 100644 --- a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesCatalogWatchEndpointsTests.java +++ b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesCatalogWatchEndpointsTests.java @@ -75,7 +75,7 @@ public void afterEach() { @Override void testInAllNamespacesEmptyServiceLabels() { stubFor(get("/api/v1/endpoints?labelSelector=") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpoints("a", "default"))))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpoints("a", "default"))))); KubernetesCatalogWatch watch = createWatcherInAllNamespacesWithLabels(Map.of(), Set.of(), coreV1Api, null, USE_ENDPOINT_SLICES); @@ -86,7 +86,7 @@ void testInAllNamespacesEmptyServiceLabels() { @Override void testInAllNamespacesWithSingleLabel() { stubFor(get("/api/v1/endpoints?labelSelector=a%3Db") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpoints("a", "default"))))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpoints("a", "default"))))); KubernetesCatalogWatch watch = createWatcherInAllNamespacesWithLabels(Map.of("a", "b"), Set.of(), coreV1Api, null, USE_ENDPOINT_SLICES); @@ -97,7 +97,7 @@ void testInAllNamespacesWithSingleLabel() { @Override void testInAllNamespacesWithDoubleLabel() { stubFor(get("/api/v1/endpoints?labelSelector=a%3Db%26c%3Dd") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpoints("a", "default"))))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpoints("a", "default"))))); // otherwise the stub might fail LinkedHashMap map = new LinkedHashMap<>(); map.put("a", "b"); @@ -112,7 +112,7 @@ void testInAllNamespacesWithDoubleLabel() { @Override void testInSpecificNamespacesEmptyServiceLabels() { stubFor(get("/api/v1/namespaces/b/endpoints?labelSelector=") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpoints("a", "b"))))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpoints("a", "b"))))); KubernetesCatalogWatch watch = createWatcherInSpecificNamespacesWithLabels(Set.of("b"), Map.of(), coreV1Api, null, USE_ENDPOINT_SLICES); @@ -123,9 +123,9 @@ void testInSpecificNamespacesEmptyServiceLabels() { @Override void testInSpecificNamespacesWithSingleLabel() { stubFor(get("/api/v1/namespaces/one/endpoints?labelSelector=a%3Db") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpoints("aa", "a"))))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpoints("aa", "a"))))); stubFor(get("/api/v1/namespaces/two/endpoints?labelSelector=a%3Db") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpoints("bb", "b"))))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpoints("bb", "b"))))); KubernetesCatalogWatch watch = createWatcherInSpecificNamespacesWithLabels(Set.of("one", "two"), Map.of("a", "b"), coreV1Api, null, USE_ENDPOINT_SLICES); @@ -138,9 +138,9 @@ void testInSpecificNamespacesWithSingleLabel() { @Override void testInSpecificNamespacesWithDoubleLabel() { stubFor(get("/api/v1/namespaces/one/endpoints?labelSelector=a%3Db%26c%3Dd") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpoints("aa", "a"))))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpoints("aa", "a"))))); stubFor(get("/api/v1/namespaces/two/endpoints?labelSelector=a%3Db%26c%3Dd") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpoints("bb", "b"))))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpoints("bb", "b"))))); // otherwise the stub might fail LinkedHashMap map = new LinkedHashMap<>(); @@ -158,7 +158,7 @@ void testInSpecificNamespacesWithDoubleLabel() { @Override void testInOneNamespaceEmptyServiceLabels() { stubFor(get("/api/v1/namespaces/b/endpoints?labelSelector=") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpoints("a", "b"))))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpoints("a", "b"))))); KubernetesCatalogWatch watch = createWatcherInSpecificNamespaceWithLabels("b", Map.of(), coreV1Api, null, USE_ENDPOINT_SLICES); @@ -169,7 +169,7 @@ void testInOneNamespaceEmptyServiceLabels() { @Override void testInOneNamespaceWithSingleLabel() { stubFor(get("/api/v1/namespaces/b/endpoints?labelSelector=key%3Dvalue") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpoints("a", "b"))))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpoints("a", "b"))))); KubernetesCatalogWatch watch = createWatcherInSpecificNamespaceWithLabels("b", Map.of("key", "value"), coreV1Api, null, USE_ENDPOINT_SLICES); @@ -180,7 +180,7 @@ void testInOneNamespaceWithSingleLabel() { @Override void testInOneNamespaceWithDoubleLabel() { stubFor(get("/api/v1/namespaces/b/endpoints?labelSelector=key%3Dvalue%26key1%3Dvalue1") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpoints("a", "b"))))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(endpoints("a", "b"))))); // otherwise the stub might fail LinkedHashMap map = new LinkedHashMap<>(); map.put("key", "value"); diff --git a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesClientCatalogWatchEndpointSlicesSupportTests.java b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesClientCatalogWatchEndpointSlicesSupportTests.java index 29d822f0fa..ae3715891c 100644 --- a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesClientCatalogWatchEndpointSlicesSupportTests.java +++ b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesClientCatalogWatchEndpointSlicesSupportTests.java @@ -54,7 +54,7 @@ class KubernetesClientCatalogWatchEndpointSlicesSupportTests { public static WireMockServer wireMockServer; private static final KubernetesNamespaceProvider NAMESPACE_PROVIDER = Mockito - .mock(KubernetesNamespaceProvider.class); + .mock(KubernetesNamespaceProvider.class); private static ApiClient apiClient; @@ -92,7 +92,7 @@ void testEndpointSlicesEnabledButNotSupported() { V1APIResourceList list = new V1APIResourceListBuilder().addToResources(new V1APIResource()).build(); stubFor(get("/apis/discovery.k8s.io/v1") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(list)))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(list)))); KubernetesCatalogWatch watch = new KubernetesCatalogWatch(null, apiClient, properties, NAMESPACE_PROVIDER); IllegalArgumentException ex = Assertions.assertThrows(IllegalArgumentException.class, watch::postConstruct); @@ -113,9 +113,10 @@ void testEndpointSlicesEnabledButNotSupportedViaApiVersions() { false, "", Set.of(), Map.of(), "", null, 0, useEndpointSlices); V1APIResourceList list = new V1APIResourceListBuilder() - .addToResources(new V1APIResourceBuilder().withName("not-the-one").build()).build(); + .addToResources(new V1APIResourceBuilder().withName("not-the-one").build()) + .build(); stubFor(get("/apis/discovery.k8s.io/v1") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(list)))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(list)))); KubernetesCatalogWatch watch = new KubernetesCatalogWatch(null, apiClient, properties, NAMESPACE_PROVIDER); IllegalArgumentException ex = Assertions.assertThrows(IllegalArgumentException.class, watch::postConstruct); @@ -147,10 +148,10 @@ void testEndpointSlicesSupport() { false, "", Set.of(), Map.of(), "", null, 0, useEndpointSlices); V1APIResourceList list = new V1APIResourceListBuilder() - .addToResources(new V1APIResourceBuilder().withName("endpointslices").withKind(ENDPOINT_SLICE).build()) - .build(); + .addToResources(new V1APIResourceBuilder().withName("endpointslices").withKind(ENDPOINT_SLICE).build()) + .build(); stubFor(get("/apis/discovery.k8s.io/v1") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(list)))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(list)))); KubernetesCatalogWatch watch = new KubernetesCatalogWatch(null, apiClient, properties, NAMESPACE_PROVIDER); Assertions.assertEquals(KubernetesEndpointSlicesCatalogWatch.class, watch.stateGenerator().getClass()); diff --git a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesEndpointsAndEndpointSlicesTests.java b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesEndpointsAndEndpointSlicesTests.java index 1f8688e499..0fa40fd936 100644 --- a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesEndpointsAndEndpointSlicesTests.java +++ b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/catalog/KubernetesEndpointsAndEndpointSlicesTests.java @@ -55,7 +55,7 @@ abstract class KubernetesEndpointsAndEndpointSlicesTests { static final KubernetesNamespaceProvider NAMESPACE_PROVIDER = Mockito.mock(KubernetesNamespaceProvider.class); static final ArgumentCaptor HEARTBEAT_EVENT_ARGUMENT_CAPTOR = ArgumentCaptor - .forClass(HeartbeatEvent.class); + .forClass(HeartbeatEvent.class); static final ApplicationEventPublisher APPLICATION_EVENT_PUBLISHER = Mockito.mock(ApplicationEventPublisher.class); @@ -164,19 +164,22 @@ KubernetesCatalogWatch createWatcherInSpecificNamespaceWithLabels(String namespa } V1EndpointsList endpoints(String name, String namespace) { - return new V1EndpointsListBuilder().addToItems(new V1EndpointsBuilder() - .addToSubsets(new V1EndpointSubsetBuilder().addToAddresses(new V1EndpointAddressBuilder() - .withTargetRef(new V1ObjectReferenceBuilder().withName(name).withNamespace(namespace).build()) - .build()).build()) - .build()).build(); + return new V1EndpointsListBuilder().addToItems( + new V1EndpointsBuilder().addToSubsets( + new V1EndpointSubsetBuilder().addToAddresses(new V1EndpointAddressBuilder() + .withTargetRef( + new V1ObjectReferenceBuilder().withName(name).withNamespace(namespace).build()) + .build()).build()) + .build()) + .build(); } V1EndpointSliceList endpointSlices(String name, String namespace) { return new V1EndpointSliceListBuilder() - .addToItems(new V1EndpointSliceBuilder().addToEndpoints(new V1EndpointBuilder() - .withTargetRef(new V1ObjectReferenceBuilder().withName(name).withNamespace(namespace).build()) - .build()).build()) - .build(); + .addToItems(new V1EndpointSliceBuilder().addToEndpoints(new V1EndpointBuilder() + .withTargetRef(new V1ObjectReferenceBuilder().withName(name).withNamespace(namespace).build()) + .build()).build()) + .build(); } static void invokeAndAssert(KubernetesCatalogWatch watch, List state) { diff --git a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/reactive/KubernetesInformerReactiveDiscoveryClientAutoConfigurationApplicationContextTests.java b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/reactive/KubernetesInformerReactiveDiscoveryClientAutoConfigurationApplicationContextTests.java index 68d4f2153a..baa7744993 100644 --- a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/reactive/KubernetesInformerReactiveDiscoveryClientAutoConfigurationApplicationContextTests.java +++ b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/reactive/KubernetesInformerReactiveDiscoveryClientAutoConfigurationApplicationContextTests.java @@ -432,25 +432,25 @@ void healthEnabledClassNotPresentWithSelectiveNamespaces() { private void setup(String... properties) { applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - KubernetesInformerReactiveDiscoveryClientAutoConfiguration.class, - KubernetesClientAutoConfiguration.class, SimpleReactiveDiscoveryClientAutoConfiguration.class, - UtilAutoConfiguration.class, KubernetesDiscoveryPropertiesAutoConfiguration.class, - KubernetesClientInformerSelectiveNamespacesAutoConfiguration.class, - KubernetesCommonsAutoConfiguration.class, KubernetesClientInformerAutoConfiguration.class)) - .withUserConfiguration(ApiClientConfig.class).withPropertyValues(properties); + .withConfiguration(AutoConfigurations.of(KubernetesInformerReactiveDiscoveryClientAutoConfiguration.class, + KubernetesClientAutoConfiguration.class, SimpleReactiveDiscoveryClientAutoConfiguration.class, + UtilAutoConfiguration.class, KubernetesDiscoveryPropertiesAutoConfiguration.class, + KubernetesClientInformerSelectiveNamespacesAutoConfiguration.class, + KubernetesCommonsAutoConfiguration.class, KubernetesClientInformerAutoConfiguration.class)) + .withUserConfiguration(ApiClientConfig.class) + .withPropertyValues(properties); } private void setupWithFilteredClassLoader(String name, String... properties) { applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - KubernetesInformerReactiveDiscoveryClientAutoConfiguration.class, - KubernetesClientAutoConfiguration.class, SimpleReactiveDiscoveryClientAutoConfiguration.class, - UtilAutoConfiguration.class, KubernetesDiscoveryPropertiesAutoConfiguration.class, - KubernetesClientInformerSelectiveNamespacesAutoConfiguration.class, - KubernetesCommonsAutoConfiguration.class, KubernetesClientInformerAutoConfiguration.class)) - .withUserConfiguration(ApiClientConfig.class).withClassLoader(new FilteredClassLoader(name)) - .withPropertyValues(properties); + .withConfiguration(AutoConfigurations.of(KubernetesInformerReactiveDiscoveryClientAutoConfiguration.class, + KubernetesClientAutoConfiguration.class, SimpleReactiveDiscoveryClientAutoConfiguration.class, + UtilAutoConfiguration.class, KubernetesDiscoveryPropertiesAutoConfiguration.class, + KubernetesClientInformerSelectiveNamespacesAutoConfiguration.class, + KubernetesCommonsAutoConfiguration.class, KubernetesClientInformerAutoConfiguration.class)) + .withUserConfiguration(ApiClientConfig.class) + .withClassLoader(new FilteredClassLoader(name)) + .withPropertyValues(properties); } @Configuration diff --git a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/reactive/KubernetesInformerReactiveDiscoveryClientAutoConfigurationTests.java b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/reactive/KubernetesInformerReactiveDiscoveryClientAutoConfigurationTests.java index a22d101b5e..74029b1a41 100644 --- a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/reactive/KubernetesInformerReactiveDiscoveryClientAutoConfigurationTests.java +++ b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/reactive/KubernetesInformerReactiveDiscoveryClientAutoConfigurationTests.java @@ -73,8 +73,9 @@ void kubernetesDiscoveryClientCreated() { assertThat(this.discoveryClient).isNotNull().isInstanceOf(ReactiveCompositeDiscoveryClient.class); ReactiveCompositeDiscoveryClient composite = (ReactiveCompositeDiscoveryClient) this.discoveryClient; - assertThat(composite.getDiscoveryClients().stream() - .anyMatch(dc -> dc instanceof KubernetesInformerReactiveDiscoveryClient)).isTrue(); + assertThat(composite.getDiscoveryClients() + .stream() + .anyMatch(dc -> dc instanceof KubernetesInformerReactiveDiscoveryClient)).isTrue(); } @SpringBootApplication @@ -86,11 +87,15 @@ ApiClient apiClient() { wireMockServer.start(); WireMock.configureFor(wireMockServer.port()); stubFor(get("/api/v1/namespaces/test/endpoints?resourceVersion=0&watch=false") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(new V1EndpointsListBuilder() - .withMetadata(new V1ListMetaBuilder().withResourceVersion("0").build()).build())))); + .willReturn(aResponse().withStatus(200) + .withBody(new JSON().serialize(new V1EndpointsListBuilder() + .withMetadata(new V1ListMetaBuilder().withResourceVersion("0").build()) + .build())))); stubFor(get("/api/v1/namespaces/test/services?resourceVersion=0&watch=false") - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(new V1ServiceListBuilder() - .withMetadata(new V1ListMetaBuilder().withResourceVersion("0").build()).build())))); + .willReturn(aResponse().withStatus(200) + .withBody(new JSON().serialize(new V1ServiceListBuilder() + .withMetadata(new V1ListMetaBuilder().withResourceVersion("0").build()) + .build())))); return new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build(); } diff --git a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/reactive/KubernetesInformerReactiveDiscoveryClientTests.java b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/reactive/KubernetesInformerReactiveDiscoveryClientTests.java index a5b9e32124..a41a389203 100644 --- a/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/reactive/KubernetesInformerReactiveDiscoveryClientTests.java +++ b/spring-cloud-kubernetes-client-discovery/src/test/java/org/springframework/cloud/kubernetes/client/discovery/reactive/KubernetesInformerReactiveDiscoveryClientTests.java @@ -62,19 +62,19 @@ class KubernetesInformerReactiveDiscoveryClientTests { private final SharedInformerFactory sharedInformerFactory = Mockito.mock(SharedInformerFactory.class); private static final V1Service TEST_SERVICE_1 = new V1Service().spec(new V1ServiceSpec().type("ClusterIP")) - .metadata(new V1ObjectMeta().name("test-svc-1").namespace(NAMESPACE_1)); + .metadata(new V1ObjectMeta().name("test-svc-1").namespace(NAMESPACE_1)); private static final V1Service TEST_SERVICE_2 = new V1Service().spec(new V1ServiceSpec().type("ClusterIP")) - .metadata(new V1ObjectMeta().name("test-svc-2").namespace(NAMESPACE_2)); + .metadata(new V1ObjectMeta().name("test-svc-2").namespace(NAMESPACE_2)); // same name as TEST_SERVICE_1, to test distinct private static final V1Service TEST_SERVICE_3 = new V1Service() - .metadata(new V1ObjectMeta().name("test-svc-2").namespace(NAMESPACE_2)); + .metadata(new V1ObjectMeta().name("test-svc-2").namespace(NAMESPACE_2)); private static final V1Endpoints TEST_ENDPOINTS_1 = new V1Endpoints() - .metadata(new V1ObjectMeta().name("test-svc-1").namespace(NAMESPACE_1)) - .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(8080)) - .addAddressesItem(new V1EndpointAddress().ip("2.2.2.2"))); + .metadata(new V1ObjectMeta().name("test-svc-1").namespace(NAMESPACE_1)) + .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(8080)) + .addAddressesItem(new V1EndpointAddress().ip("2.2.2.2"))); @AfterEach void afterEach() { @@ -96,8 +96,9 @@ void testDiscoveryGetServicesAllNamespaceShouldWork() { kubernetesDiscoveryProperties)); StepVerifier.create(discoveryClient.getServices()) - .expectNext(TEST_SERVICE_1.getMetadata().getName(), TEST_SERVICE_2.getMetadata().getName()) - .expectComplete().verify(); + .expectNext(TEST_SERVICE_1.getMetadata().getName(), TEST_SERVICE_2.getMetadata().getName()) + .expectComplete() + .verify(); } @@ -110,8 +111,10 @@ void testDiscoveryGetServicesOneNamespaceShouldWork() { new KubernetesInformerDiscoveryClient(sharedInformerFactory, serviceLister, endpointsLister, null, null, KubernetesDiscoveryProperties.DEFAULT)); - StepVerifier.create(discoveryClient.getServices()).expectNext(TEST_SERVICE_1.getMetadata().getName()) - .expectComplete().verify(); + StepVerifier.create(discoveryClient.getServices()) + .expectNext(TEST_SERVICE_1.getMetadata().getName()) + .expectComplete() + .verify(); } @@ -129,10 +132,11 @@ void testDiscoveryGetInstanceAllNamespaceShouldWork() { kubernetesDiscoveryProperties)); StepVerifier.create(discoveryClient.getInstances("test-svc-1")) - .expectNext(new DefaultKubernetesServiceInstance(null, "test-svc-1", "2.2.2.2", 8080, - Map.of("type", "ClusterIP", "port.", "8080", "k8s_namespace", "namespace1"), false, - "namespace1", null)) - .expectComplete().verify(); + .expectNext(new DefaultKubernetesServiceInstance(null, "test-svc-1", "2.2.2.2", 8080, + Map.of("type", "ClusterIP", "port.", "8080", "k8s_namespace", "namespace1"), false, + "namespace1", null)) + .expectComplete() + .verify(); } @@ -150,10 +154,11 @@ void testDiscoveryGetInstanceOneNamespaceShouldWork() { kubernetesDiscoveryProperties)); StepVerifier.create(discoveryClient.getInstances("test-svc-1")) - .expectNext(new DefaultKubernetesServiceInstance(null, "test-svc-1", "2.2.2.2", 8080, - Map.of("type", "ClusterIP", "port.", "8080", "k8s_namespace", "namespace1"), false, - "namespace1", null)) - .expectComplete().verify(); + .expectNext(new DefaultKubernetesServiceInstance(null, "test-svc-1", "2.2.2.2", 8080, + Map.of("type", "ClusterIP", "port.", "8080", "k8s_namespace", "namespace1"), false, + "namespace1", null)) + .expectComplete() + .verify(); } @@ -238,22 +243,22 @@ void testAllNamespacesTwoEndpointsPresent() { boolean allNamespaces = true; V1Service serviceXNamespaceA = new V1Service() - .metadata(new V1ObjectMeta().name("endpoints-x").namespace("namespace-a")) - .spec(new V1ServiceSpecBuilder().withType("ClusterIP").build()); + .metadata(new V1ObjectMeta().name("endpoints-x").namespace("namespace-a")) + .spec(new V1ServiceSpecBuilder().withType("ClusterIP").build()); V1Service serviceXNamespaceB = new V1Service() - .metadata(new V1ObjectMeta().name("endpoints-x").namespace("namespace-b")) - .spec(new V1ServiceSpecBuilder().withType("ClusterIP").build()); + .metadata(new V1ObjectMeta().name("endpoints-x").namespace("namespace-b")) + .spec(new V1ServiceSpecBuilder().withType("ClusterIP").build()); serviceCache.add(serviceXNamespaceA); serviceCache.add(serviceXNamespaceB); V1Endpoints endpointsXNamespaceA = new V1Endpoints() - .metadata(new V1ObjectMeta().name("endpoints-x").namespace("namespace-a")) - .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(8080)) - .addAddressesItem(new V1EndpointAddress().ip("1.1.1.1"))); + .metadata(new V1ObjectMeta().name("endpoints-x").namespace("namespace-a")) + .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(8080)) + .addAddressesItem(new V1EndpointAddress().ip("1.1.1.1"))); V1Endpoints endpointsXNamespaceB = new V1Endpoints() - .metadata(new V1ObjectMeta().name("endpoints-x").namespace("namespace-b")) - .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(8080)) - .addAddressesItem(new V1EndpointAddress().ip("2.2.2.2"))); + .metadata(new V1ObjectMeta().name("endpoints-x").namespace("namespace-b")) + .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(8080)) + .addAddressesItem(new V1EndpointAddress().ip("2.2.2.2"))); endpointsCache.add(endpointsXNamespaceA); endpointsCache.add(endpointsXNamespaceB); @@ -289,22 +294,22 @@ void testAllSingleTwoEndpointsPresent() { boolean allNamespaces = true; V1Service serviceXNamespaceA = new V1Service() - .metadata(new V1ObjectMeta().name("endpoints-x").namespace("namespace-a")) - .spec(new V1ServiceSpecBuilder().withType("ClusterIP").build()); + .metadata(new V1ObjectMeta().name("endpoints-x").namespace("namespace-a")) + .spec(new V1ServiceSpecBuilder().withType("ClusterIP").build()); V1Service serviceXNamespaceB = new V1Service() - .metadata(new V1ObjectMeta().name("endpoints-x").namespace("namespace-b")) - .spec(new V1ServiceSpecBuilder().withType("ClusterIP").build()); + .metadata(new V1ObjectMeta().name("endpoints-x").namespace("namespace-b")) + .spec(new V1ServiceSpecBuilder().withType("ClusterIP").build()); serviceCache.add(serviceXNamespaceA); serviceCache.add(serviceXNamespaceB); V1Endpoints endpointsXNamespaceA = new V1Endpoints() - .metadata(new V1ObjectMeta().name("endpoints-x").namespace("namespace-a")) - .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(8080)) - .addAddressesItem(new V1EndpointAddress().ip("1.1.1.1"))); + .metadata(new V1ObjectMeta().name("endpoints-x").namespace("namespace-a")) + .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(8080)) + .addAddressesItem(new V1EndpointAddress().ip("1.1.1.1"))); V1Endpoints endpointsXNamespaceB = new V1Endpoints() - .metadata(new V1ObjectMeta().name("endpoints-x").namespace("namespace-b")) - .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(8080)) - .addAddressesItem(new V1EndpointAddress().ip("2.2.2.2"))); + .metadata(new V1ObjectMeta().name("endpoints-x").namespace("namespace-b")) + .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(8080)) + .addAddressesItem(new V1EndpointAddress().ip("2.2.2.2"))); endpointsCache.add(endpointsXNamespaceA); endpointsCache.add(endpointsXNamespaceB); diff --git a/spring-cloud-kubernetes-client-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/client/loadbalancer/KubernetesClientLoadBalancerClientConfiguration.java b/spring-cloud-kubernetes-client-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/client/loadbalancer/KubernetesClientLoadBalancerClientConfiguration.java index 9d57b3bc01..64f2482012 100644 --- a/spring-cloud-kubernetes-client-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/client/loadbalancer/KubernetesClientLoadBalancerClientConfiguration.java +++ b/spring-cloud-kubernetes-client-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/client/loadbalancer/KubernetesClientLoadBalancerClientConfiguration.java @@ -36,8 +36,11 @@ public class KubernetesClientLoadBalancerClientConfiguration { ServiceInstanceListSupplier kubernetesServicesListSupplier(Environment environment, CoreV1Api coreV1Api, KubernetesClientServiceInstanceMapper mapper, KubernetesDiscoveryProperties discoveryProperties, KubernetesNamespaceProvider kubernetesNamespaceProvider, ConfigurableApplicationContext context) { - return ServiceInstanceListSupplier.builder().withBase(new KubernetesClientServicesListSupplier(environment, - mapper, discoveryProperties, coreV1Api, kubernetesNamespaceProvider)).withCaching().build(context); + return ServiceInstanceListSupplier.builder() + .withBase(new KubernetesClientServicesListSupplier(environment, mapper, discoveryProperties, coreV1Api, + kubernetesNamespaceProvider)) + .withCaching() + .build(context); } } diff --git a/spring-cloud-kubernetes-client-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/client/loadbalancer/KubernetesClientServiceInstanceMapper.java b/spring-cloud-kubernetes-client-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/client/loadbalancer/KubernetesClientServiceInstanceMapper.java index 249739c868..921a7186fe 100644 --- a/spring-cloud-kubernetes-client-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/client/loadbalancer/KubernetesClientServiceInstanceMapper.java +++ b/spring-cloud-kubernetes-client-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/client/loadbalancer/KubernetesClientServiceInstanceMapper.java @@ -92,7 +92,8 @@ public KubernetesServiceInstance map(V1Service service) { String portNameFromProperties = properties.getPortName(); if (StringUtils.hasText(portNameFromProperties)) { Optional optionalPort = ports.stream() - .filter(x -> Objects.equals(x.getName(), portNameFromProperties)).findAny(); + .filter(x -> Objects.equals(x.getName(), portNameFromProperties)) + .findAny(); if (optionalPort.isPresent()) { LOG.debug(() -> "found port name that matches : " + portNameFromProperties); port = optionalPort.get(); diff --git a/spring-cloud-kubernetes-client-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/client/loadbalancer/KubernetesClientServicesListSupplier.java b/spring-cloud-kubernetes-client-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/client/loadbalancer/KubernetesClientServicesListSupplier.java index f150288896..18c85940ec 100644 --- a/spring-cloud-kubernetes-client-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/client/loadbalancer/KubernetesClientServicesListSupplier.java +++ b/spring-cloud-kubernetes-client-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/client/loadbalancer/KubernetesClientServicesListSupplier.java @@ -93,8 +93,10 @@ private void addMappedService(KubernetesServiceInstanceMapper mapper, private List services(String namespace, String serviceName) { if (namespace == null) { try { - return coreV1Api.listServiceForAllNamespaces(null, null, "metadata.name=" + serviceName, null, null, - null, null, null, null, null, null).getItems(); + return coreV1Api + .listServiceForAllNamespaces(null, null, "metadata.name=" + serviceName, null, null, null, null, + null, null, null, null) + .getItems(); } catch (ApiException apiException) { LOG.warn(apiException, "Error retrieving services (in all namespaces) with name " + serviceName); @@ -104,8 +106,10 @@ private List services(String namespace, String serviceName) { else { try { // there is going to be a single service here, if found - return coreV1Api.listNamespacedService(namespace, null, null, null, "metadata.name=" + serviceName, - null, null, null, null, null, null, null).getItems(); + return coreV1Api + .listNamespacedService(namespace, null, null, null, "metadata.name=" + serviceName, null, null, + null, null, null, null, null) + .getItems(); } catch (ApiException apiException) { LOG.warn(apiException, diff --git a/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/KubernetesClientServiceInstanceMapperTests.java b/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/KubernetesClientServiceInstanceMapperTests.java index 950f3c278f..bc6e18eb18 100644 --- a/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/KubernetesClientServiceInstanceMapperTests.java +++ b/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/KubernetesClientServiceInstanceMapperTests.java @@ -117,8 +117,8 @@ void testEmptyPorts(CapturedOutput output) { V1Service service = createService("database", "default", annotations, labels, servicePorts); KubernetesServiceInstance serviceInstance = mapper.map(service); Assertions.assertNull(serviceInstance); - Assertions.assertTrue(output.getOut().contains( - "service : database does not have any ServicePort(s), will not consider it for load balancing")); + Assertions.assertTrue(output.getOut() + .contains("service : database does not have any ServicePort(s), will not consider it for load balancing")); } @Test @@ -134,8 +134,9 @@ void singlePortNameMatchesProperty(CapturedOutput output) { V1Service service = createService("database", "default", annotations, labels, servicePorts); KubernetesServiceInstance serviceInstance = mapper.map(service); Assertions.assertNotNull(serviceInstance); - Assertions.assertTrue(output.getOut().contains("single ServicePort found, " - + "will use it as-is (without checking 'spring.cloud.kubernetes.loadbalancer.portName')")); + Assertions.assertTrue(output.getOut() + .contains("single ServicePort found, " + + "will use it as-is (without checking 'spring.cloud.kubernetes.loadbalancer.portName')")); } @Test @@ -151,8 +152,9 @@ void singlePortNameDoesNotMatchProperty(CapturedOutput output) { V1Service service = createService("database", "default", annotations, labels, servicePorts); KubernetesServiceInstance serviceInstance = mapper.map(service); Assertions.assertNotNull(serviceInstance); - Assertions.assertTrue(output.getOut().contains("single ServicePort found, " - + "will use it as-is (without checking 'spring.cloud.kubernetes.loadbalancer.portName')")); + Assertions.assertTrue(output.getOut() + .contains("single ServicePort found, " + + "will use it as-is (without checking 'spring.cloud.kubernetes.loadbalancer.portName')")); } @Test @@ -214,9 +216,14 @@ void multiPortsEmptyPortNameProperty(CapturedOutput output) { private V1Service createService(String name, String namespace, Map annotations, Map labels, List servicePorts) { return new V1ServiceBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName(name).withUid("0").withNamespace(namespace) - .addToAnnotations(annotations).addToLabels(labels).build()) - .withSpec(new V1ServiceSpecBuilder().addAllToPorts(servicePorts).withType("V1Service").build()).build(); + .withMetadata(new V1ObjectMetaBuilder().withName(name) + .withUid("0") + .withNamespace(namespace) + .addToAnnotations(annotations) + .addToLabels(labels) + .build()) + .withSpec(new V1ServiceSpecBuilder().addAllToPorts(servicePorts).withType("V1Service").build()) + .build(); } } diff --git a/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/KubernetesClientServicesListSupplierTests.java b/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/KubernetesClientServicesListSupplierTests.java index be18b3fb02..423ce00f05 100644 --- a/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/KubernetesClientServicesListSupplierTests.java +++ b/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/KubernetesClientServicesListSupplierTests.java @@ -68,32 +68,37 @@ class KubernetesClientServicesListSupplierTests { private static final V1Service SERVICE_A_DEFAULT_NAMESPACE = new V1ServiceBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("service-a").withNamespace("default").withUid("0") - .addToLabels("beta", "true").addToAnnotations("org.springframework.cloud", "true").build()) - .withSpec(new V1ServiceSpecBuilder().withType("V1Service") - .addToPorts(new V1ServicePortBuilder().withPort(80).withName("http").build()).build()) - .build(); + .withMetadata(new V1ObjectMetaBuilder().withName("service-a") + .withNamespace("default") + .withUid("0") + .addToLabels("beta", "true") + .addToAnnotations("org.springframework.cloud", "true") + .build()) + .withSpec(new V1ServiceSpecBuilder().withType("V1Service") + .addToPorts(new V1ServicePortBuilder().withPort(80).withName("http").build()) + .build()) + .build(); private static final V1Service SERVICE_A_TEST_NAMESPACE = new V1ServiceBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("service-a").withNamespace("test").withUid("1").build()) - .withSpec( - new V1ServiceSpecBuilder().withType("V1Service") - .addToPorts(new V1ServicePortBuilder().withPort(80).withName("http").build(), - new V1ServicePortBuilder().withPort(443).withName("https").build()) - .build()) - .build(); + .withMetadata(new V1ObjectMetaBuilder().withName("service-a").withNamespace("test").withUid("1").build()) + .withSpec(new V1ServiceSpecBuilder().withType("V1Service") + .addToPorts(new V1ServicePortBuilder().withPort(80).withName("http").build(), + new V1ServicePortBuilder().withPort(443).withName("https").build()) + .build()) + .build(); private static final V1ServiceList SINGLE_NAMESPACE_SERVICES = new V1ServiceList() - .addItemsItem(SERVICE_A_DEFAULT_NAMESPACE); + .addItemsItem(SERVICE_A_DEFAULT_NAMESPACE); private static final V1ServiceList SERVICE_LIST_ALL_NAMESPACE = new V1ServiceList() - .addItemsItem(SERVICE_A_DEFAULT_NAMESPACE).addItemsItem(SERVICE_A_TEST_NAMESPACE); + .addItemsItem(SERVICE_A_DEFAULT_NAMESPACE) + .addItemsItem(SERVICE_A_TEST_NAMESPACE); private static final V1ServiceList SERVICE_A_DEFAULT_NAMESPACE_SELECTIVE_NAMESPACES = new V1ServiceList() - .addItemsItem(SERVICE_A_DEFAULT_NAMESPACE); + .addItemsItem(SERVICE_A_DEFAULT_NAMESPACE); private static final V1ServiceList SERVICE_A_TEST_NAMESPACE_SELECTIVE_NAMESPACES = new V1ServiceList() - .addItemsItem(SERVICE_A_TEST_NAMESPACE); + .addItemsItem(SERVICE_A_TEST_NAMESPACE); private static WireMockServer wireMockServer; @@ -138,7 +143,7 @@ void singleNamespaceTest(CapturedOutput output) { discoveryProperties, coreV1Api, kubernetesNamespaceProvider); stubFor(get(urlEqualTo("/api/v1/namespaces/default/services?fieldSelector=metadata.name%3Dservice-a")) - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(SINGLE_NAMESPACE_SERVICES)))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(SINGLE_NAMESPACE_SERVICES)))); Flux> instances = listSupplier.get(); @@ -175,7 +180,7 @@ void singleNamespaceNoServicePresentTest(CapturedOutput output) { discoveryProperties, coreV1Api, kubernetesNamespaceProvider); stubFor(get(urlEqualTo("/api/v1/namespaces/default/services?fieldSelector=metadata.name%3Dservice-a")) - .willReturn(aResponse().withStatus(404))); + .willReturn(aResponse().withStatus(404))); Flux> instances = listSupplier.get(); List services = List.of(); @@ -206,7 +211,7 @@ void allNamespacesTest(CapturedOutput output) { discoveryProperties, coreV1Api, kubernetesNamespaceProvider); stubFor(get(urlEqualTo("/api/v1/services?fieldSelector=metadata.name%3Dservice-a")) - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(SERVICE_LIST_ALL_NAMESPACE)))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(SERVICE_LIST_ALL_NAMESPACE)))); Flux> instances = listSupplier.get(); @@ -243,15 +248,15 @@ void selectiveNamespacesTest(CapturedOutput output) { discoveryProperties, coreV1Api, kubernetesNamespaceProvider); stubFor(get(urlEqualTo("/api/v1/namespaces/default/services?fieldSelector=metadata.name%3Dservice-a")) - .willReturn(aResponse().withStatus(200) - .withBody(new JSON().serialize(SERVICE_A_DEFAULT_NAMESPACE_SELECTIVE_NAMESPACES)))); + .willReturn(aResponse().withStatus(200) + .withBody(new JSON().serialize(SERVICE_A_DEFAULT_NAMESPACE_SELECTIVE_NAMESPACES)))); stubFor(get(urlEqualTo("/api/v1/namespaces/test/services?fieldSelector=metadata.name%3Dservice-a")) - .willReturn(aResponse().withStatus(200) - .withBody(new JSON().serialize(SERVICE_A_TEST_NAMESPACE_SELECTIVE_NAMESPACES)))); + .willReturn(aResponse().withStatus(200) + .withBody(new JSON().serialize(SERVICE_A_TEST_NAMESPACE_SELECTIVE_NAMESPACES)))); stubFor(get(urlEqualTo("/api/v1/namespaces/no-service/services?fieldSelector=metadata.name%3Dservice-a")) - .willReturn(aResponse().withStatus(404))); + .willReturn(aResponse().withStatus(404))); Flux> instances = listSupplier.get(); diff --git a/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/Util.java b/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/Util.java index 29825e161c..7cfabb82a3 100644 --- a/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/Util.java +++ b/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/Util.java @@ -49,40 +49,45 @@ private Util() { } public static V1Service service(String namespace, String name, int port) { - return new V1ServiceBuilder().withNewMetadata().withNamespace(namespace).withName(name).endMetadata() - .withSpec(new V1ServiceSpecBuilder() - .withPorts(new V1ServicePortBuilder().withName("http").withPort(port).build()).build()) - .build(); + return new V1ServiceBuilder().withNewMetadata() + .withNamespace(namespace) + .withName(name) + .endMetadata() + .withSpec(new V1ServiceSpecBuilder() + .withPorts(new V1ServicePortBuilder().withName("http").withPort(port).build()) + .build()) + .build(); } public static V1Endpoints endpoints(String namespace, String name, int port, String host) { return new V1EndpointsBuilder() - .withSubsets( - new V1EndpointSubsetBuilder().withPorts(new CoreV1EndpointPortBuilder().withPort(port).build()) - .withAddresses(new V1EndpointAddressBuilder().withIp(host).build()).build()) - .withMetadata(new V1ObjectMetaBuilder().withName(name).withNamespace(namespace).build()).build(); + .withSubsets(new V1EndpointSubsetBuilder().withPorts(new CoreV1EndpointPortBuilder().withPort(port).build()) + .withAddresses(new V1EndpointAddressBuilder().withIp(host).build()) + .build()) + .withMetadata(new V1ObjectMetaBuilder().withName(name).withNamespace(namespace).build()) + .build(); } public static void servicesPodMode(WireMockServer server, V1ServiceList serviceList) { server.stubFor(WireMock.get(WireMock.urlPathMatching("^/api/v1/services*")) - .willReturn(WireMock.aResponse().withBody(new JSON().serialize(serviceList)).withStatus(200))); + .willReturn(WireMock.aResponse().withBody(new JSON().serialize(serviceList)).withStatus(200))); } public static void servicesServiceMode(WireMockServer server, V1ServiceList serviceList, String serviceName) { // resourceVersion=0 is passed only from the watcher, so this mocks the // 'postConstruct' in the KubernetesInformerDiscoveryClient server.stubFor(WireMock.get(WireMock.urlPathMatching("^/api/v1/services*")) - .withQueryParam("resourceVersion", WireMock.equalTo("0")) - .willReturn(WireMock.aResponse().withBody(new JSON().serialize(serviceList)).withStatus(200))); + .withQueryParam("resourceVersion", WireMock.equalTo("0")) + .willReturn(WireMock.aResponse().withBody(new JSON().serialize(serviceList)).withStatus(200))); - server.stubFor( - WireMock.get(WireMock.urlEqualTo("/api/v1/services?fieldSelector=metadata.name%3D" + serviceName)) - .willReturn(WireMock.aResponse().withBody(new JSON().serialize(serviceList)).withStatus(200))); + server + .stubFor(WireMock.get(WireMock.urlEqualTo("/api/v1/services?fieldSelector=metadata.name%3D" + serviceName)) + .willReturn(WireMock.aResponse().withBody(new JSON().serialize(serviceList)).withStatus(200))); } public static void endpointsPodMode(WireMockServer server, V1EndpointsList endpointsList) { server.stubFor(WireMock.get(WireMock.urlPathMatching("^/api/v1/endpoints*")) - .willReturn(WireMock.aResponse().withBody(new JSON().serialize(endpointsList)).withStatus(200))); + .willReturn(WireMock.aResponse().withBody(new JSON().serialize(endpointsList)).withStatus(200))); } public static void endpointsServiceMode(WireMockServer server, V1EndpointsList endpointsList, @@ -90,17 +95,17 @@ public static void endpointsServiceMode(WireMockServer server, V1EndpointsList e // resourceVersion=0 is passed only from the watcher, so this mocks the // 'postConstruct' in the KubernetesInformerDiscoveryClient server.stubFor(WireMock.get(WireMock.urlPathMatching("^/api/v1/endpoints*")) - .withQueryParam("resourceVersion", WireMock.equalTo("0")) - .willReturn(WireMock.aResponse().withBody(new JSON().serialize(endpointsList)).withStatus(200))); + .withQueryParam("resourceVersion", WireMock.equalTo("0")) + .willReturn(WireMock.aResponse().withBody(new JSON().serialize(endpointsList)).withStatus(200))); - server.stubFor(WireMock - .get(WireMock.urlEqualTo("/api/v1/endpoints?fieldSelector=metadata.name%3D" + endpointsName)) - .willReturn(WireMock.aResponse().withBody(new JSON().serialize(endpointsList)).withStatus(200))); + server.stubFor( + WireMock.get(WireMock.urlEqualTo("/api/v1/endpoints?fieldSelector=metadata.name%3D" + endpointsName)) + .willReturn(WireMock.aResponse().withBody(new JSON().serialize(endpointsList)).withStatus(200))); } public static void servicesInNamespacePodMode(WireMockServer server, V1ServiceList serviceList, String namespace) { server.stubFor(WireMock.get(WireMock.urlPathMatching("^/api/v1/namespaces/" + namespace + "/services*")) - .willReturn(WireMock.aResponse().withBody(new JSON().serialize(serviceList)).withStatus(200))); + .willReturn(WireMock.aResponse().withBody(new JSON().serialize(serviceList)).withStatus(200))); } public static void servicesInNamespaceServiceMode(WireMockServer server, V1ServiceList serviceList, @@ -108,19 +113,19 @@ public static void servicesInNamespaceServiceMode(WireMockServer server, V1Servi // resourceVersion=0 is passed only from the watcher, so this mocks the // 'postConstruct' in the KubernetesInformerDiscoveryClient server.stubFor(WireMock.get(WireMock.urlPathMatching("^/api/v1/namespaces/" + namespace + "/services*")) - .withQueryParam("resourceVersion", WireMock.equalTo("0")) - .willReturn(WireMock.aResponse().withBody(new JSON().serialize(serviceList)).withStatus(200))); + .withQueryParam("resourceVersion", WireMock.equalTo("0")) + .willReturn(WireMock.aResponse().withBody(new JSON().serialize(serviceList)).withStatus(200))); server.stubFor(WireMock - .get(WireMock.urlEqualTo( - "/api/v1/namespaces/" + namespace + "/services?fieldSelector=metadata.name%3D" + serviceName)) - .willReturn(WireMock.aResponse().withBody(new JSON().serialize(serviceList)).withStatus(200))); + .get(WireMock.urlEqualTo( + "/api/v1/namespaces/" + namespace + "/services?fieldSelector=metadata.name%3D" + serviceName)) + .willReturn(WireMock.aResponse().withBody(new JSON().serialize(serviceList)).withStatus(200))); } public static void endpointsInNamespacePodMode(WireMockServer server, V1EndpointsList endpointsList, String namespace) { server.stubFor(WireMock.get(WireMock.urlPathMatching("^/api/v1/namespaces/" + namespace + "/endpoints*")) - .willReturn(WireMock.aResponse().withBody(new JSON().serialize(endpointsList)).withStatus(200))); + .willReturn(WireMock.aResponse().withBody(new JSON().serialize(endpointsList)).withStatus(200))); } public static void endpointsInNamespaceServiceMode(WireMockServer server, V1EndpointsList endpointsList, @@ -128,13 +133,13 @@ public static void endpointsInNamespaceServiceMode(WireMockServer server, V1Endp // resourceVersion=0 is passed only from the watcher, so this mocks the // 'postConstruct' in the KubernetesInformerDiscoveryClient server.stubFor(WireMock.get(WireMock.urlPathMatching("^/api/v1/namespaces/" + namespace + "/endpoints*")) - .withQueryParam("resourceVersion", WireMock.equalTo("0")) - .willReturn(WireMock.aResponse().withBody(new JSON().serialize(endpointsList)).withStatus(200))); + .withQueryParam("resourceVersion", WireMock.equalTo("0")) + .willReturn(WireMock.aResponse().withBody(new JSON().serialize(endpointsList)).withStatus(200))); server.stubFor(WireMock - .get(WireMock.urlEqualTo("/api/v1/namespaces/" + namespace + "/endpoints?fieldSelector=metadata.name%3D" - + endpointsName)) - .willReturn(WireMock.aResponse().withBody(new JSON().serialize(endpointsList)).withStatus(200))); + .get(WireMock.urlEqualTo( + "/api/v1/namespaces/" + namespace + "/endpoints?fieldSelector=metadata.name%3D" + endpointsName)) + .willReturn(WireMock.aResponse().withBody(new JSON().serialize(endpointsList)).withStatus(200))); } @TestConfiguration diff --git a/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/pod/AllNamespacesTest.java b/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/pod/AllNamespacesTest.java index e8738f1d4e..0689117a9a 100644 --- a/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/pod/AllNamespacesTest.java +++ b/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/pod/AllNamespacesTest.java @@ -78,7 +78,7 @@ class AllNamespacesTest { private static MockedStatic clientUtils; private static final MockedStatic MOCKED_STATIC = Mockito - .mockStatic(KubernetesServiceInstanceMapper.class); + .mockStatic(KubernetesServiceInstanceMapper.class); @Autowired private WebClient.Builder builder; @@ -105,10 +105,10 @@ static void beforeAll() { // we mock host creation so that it becomes something like : localhost:8888 // then wiremock can catch this request, and we can assert for the result MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("service-a", "a", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("service-b", "b", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); ApiClient client = new ClientBuilder().setBasePath("http://localhost:" + wireMockServer.port()).build(); clientUtils = mockStatic(KubernetesClientUtils.class); @@ -136,23 +136,33 @@ static void afterAll() { void test() { serviceAMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); + .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); serviceBMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); - - String serviceAResult = builder.baseUrl(SERVICE_A_URL).build().method(HttpMethod.GET).retrieve() - .bodyToMono(String.class).block(); + .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); + + String serviceAResult = builder.baseUrl(SERVICE_A_URL) + .build() + .method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .block(); Assertions.assertThat(serviceAResult).isEqualTo("service-a-reached"); - String serviceBResult = builder.baseUrl(SERVICE_B_URL).build().method(HttpMethod.GET).retrieve() - .bodyToMono(String.class).block(); + String serviceBResult = builder.baseUrl(SERVICE_B_URL) + .build() + .method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .block(); Assertions.assertThat(serviceBResult).isEqualTo("service-b-reached"); CachingServiceInstanceListSupplier supplier = (CachingServiceInstanceListSupplier) loadBalancerClientFactory - .getIfAvailable().getProvider("service-a", ServiceInstanceListSupplier.class).getIfAvailable(); + .getIfAvailable() + .getProvider("service-a", ServiceInstanceListSupplier.class) + .getIfAvailable(); Assertions.assertThat(supplier.getDelegate().getClass()) - .isSameAs(DiscoveryClientServiceInstanceListSupplier.class); + .isSameAs(DiscoveryClientServiceInstanceListSupplier.class); } @@ -160,16 +170,20 @@ private static void mockWatchers() { V1Service serviceA = Util.service("a", "service-a", SERVICE_A_PORT); V1Service serviceB = Util.service("b", "service-b", SERVICE_B_PORT); V1ServiceList serviceList = new V1ServiceListBuilder().withKind("V1ServiceList") - .withMetadata(new V1ListMetaBuilder().withResourceVersion("0").build()) - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(serviceA, serviceB).build(); + .withMetadata(new V1ListMetaBuilder().withResourceVersion("0").build()) + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(serviceA, serviceB) + .build(); Util.servicesPodMode(wireMockServer, serviceList); V1Endpoints endpointsA = Util.endpoints("a", "service-a", SERVICE_A_PORT, "127.0.0.1"); V1Endpoints endpointsB = Util.endpoints("b", "service-b", SERVICE_B_PORT, "127.0.0.1"); V1EndpointsList endpointsList = new V1EndpointsListBuilder().withKind("V1EndpointsList") - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(endpointsA, endpointsB).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(endpointsA, endpointsB) + .build(); Util.endpointsPodMode(wireMockServer, endpointsList); } diff --git a/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/pod/SelectiveNamespacesTest.java b/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/pod/SelectiveNamespacesTest.java index 563fff08ac..d5bdfb84b1 100644 --- a/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/pod/SelectiveNamespacesTest.java +++ b/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/pod/SelectiveNamespacesTest.java @@ -78,7 +78,7 @@ class SelectiveNamespacesTest { private static WireMockServer serviceCMockServer; private static final MockedStatic MOCKED_STATIC = Mockito - .mockStatic(KubernetesServiceInstanceMapper.class); + .mockStatic(KubernetesServiceInstanceMapper.class); private static MockedStatic clientUtils; @@ -111,13 +111,13 @@ static void beforeAll() { // we mock host creation so that it becomes something like : localhost:8888 // then wiremock can catch this request, and we can assert for the result MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("my-service", "a", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("my-service", "b", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("my-service", "c", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); ApiClient client = new ClientBuilder().setBasePath("http://localhost:" + wireMockServer.port()).build(); clientUtils = mockStatic(KubernetesClientUtils.class); @@ -150,19 +150,27 @@ static void afterAll() { void test() { serviceAMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); + .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); serviceBMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); + .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); serviceCMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-c-reached").withStatus(200))); - - String firstCallResult = builder.baseUrl(MY_SERVICE_URL).build().method(HttpMethod.GET).retrieve() - .bodyToMono(String.class).block(); - - String secondCallResult = builder.baseUrl(MY_SERVICE_URL).build().method(HttpMethod.GET).retrieve() - .bodyToMono(String.class).block(); + .willReturn(WireMock.aResponse().withBody("service-c-reached").withStatus(200))); + + String firstCallResult = builder.baseUrl(MY_SERVICE_URL) + .build() + .method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .block(); + + String secondCallResult = builder.baseUrl(MY_SERVICE_URL) + .build() + .method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .block(); // since selective namespaces is a Set, we need to be careful with assertion order if (firstCallResult.equals("service-a-reached")) { @@ -174,9 +182,11 @@ void test() { } CachingServiceInstanceListSupplier supplier = (CachingServiceInstanceListSupplier) loadBalancerClientFactory - .getIfAvailable().getProvider("my-service", ServiceInstanceListSupplier.class).getIfAvailable(); + .getIfAvailable() + .getProvider("my-service", ServiceInstanceListSupplier.class) + .getIfAvailable(); Assertions.assertThat(supplier.getDelegate().getClass()) - .isSameAs(DiscoveryClientServiceInstanceListSupplier.class); + .isSameAs(DiscoveryClientServiceInstanceListSupplier.class); } private static void mockWatchers() { @@ -185,14 +195,20 @@ private static void mockWatchers() { V1Service serviceC = Util.service("c", "my-service", SERVICE_C_PORT); V1ServiceList serviceListA = new V1ServiceListBuilder() - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(serviceA).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(serviceA) + .build(); V1ServiceList serviceListB = new V1ServiceListBuilder() - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(serviceB).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(serviceB) + .build(); V1ServiceList serviceListC = new V1ServiceListBuilder() - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(serviceC).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(serviceC) + .build(); Util.servicesInNamespacePodMode(wireMockServer, serviceListA, "a"); Util.servicesInNamespacePodMode(wireMockServer, serviceListB, "b"); @@ -203,14 +219,20 @@ private static void mockWatchers() { V1Endpoints endpointsC = Util.endpoints("c", "my-service", SERVICE_C_PORT, "127.0.0.1"); V1EndpointsList endpointsListA = new V1EndpointsListBuilder() - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(endpointsA).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(endpointsA) + .build(); V1EndpointsList endpointsListB = new V1EndpointsListBuilder() - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(endpointsB).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(endpointsB) + .build(); V1EndpointsList endpointsListC = new V1EndpointsListBuilder() - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(endpointsC).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(endpointsC) + .build(); Util.endpointsInNamespacePodMode(wireMockServer, endpointsListA, "a"); Util.endpointsInNamespacePodMode(wireMockServer, endpointsListB, "b"); diff --git a/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/pod/SpecificNamespaceTest.java b/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/pod/SpecificNamespaceTest.java index c24400c688..09e17861b3 100644 --- a/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/pod/SpecificNamespaceTest.java +++ b/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/pod/SpecificNamespaceTest.java @@ -73,7 +73,7 @@ class SpecificNamespaceTest { private static WireMockServer serviceBMockServer; private static final MockedStatic MOCKED_STATIC = Mockito - .mockStatic(KubernetesServiceInstanceMapper.class); + .mockStatic(KubernetesServiceInstanceMapper.class); private static MockedStatic clientUtils; @@ -102,10 +102,10 @@ static void beforeAll() { // we mock host creation so that it becomes something like : localhost:8888 // then wiremock can catch this request, and we can assert for the result MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("my-service", "a", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("my-service", "b", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); ApiClient client = new ClientBuilder().setBasePath("http://localhost:" + wireMockServer.port()).build(); // we need to not mock 'getApplicationNamespace' @@ -137,19 +137,25 @@ static void afterAll() { void test() { serviceAMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); + .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); serviceBMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); - - String serviceAResult = builder.baseUrl(SERVICE_A_URL).build().method(HttpMethod.GET).retrieve() - .bodyToMono(String.class).block(); + .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); + + String serviceAResult = builder.baseUrl(SERVICE_A_URL) + .build() + .method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .block(); Assertions.assertThat(serviceAResult).isEqualTo("service-a-reached"); CachingServiceInstanceListSupplier supplier = (CachingServiceInstanceListSupplier) loadBalancerClientFactory - .getIfAvailable().getProvider("my-service", ServiceInstanceListSupplier.class).getIfAvailable(); + .getIfAvailable() + .getProvider("my-service", ServiceInstanceListSupplier.class) + .getIfAvailable(); Assertions.assertThat(supplier.getDelegate().getClass()) - .isSameAs(DiscoveryClientServiceInstanceListSupplier.class); + .isSameAs(DiscoveryClientServiceInstanceListSupplier.class); } private static void mockWatchers() { @@ -157,11 +163,15 @@ private static void mockWatchers() { V1Service serviceB = Util.service("b", "my-service", SERVICE_B_PORT); V1ServiceList serviceListA = new V1ServiceListBuilder() - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(serviceA).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(serviceA) + .build(); V1ServiceList serviceListB = new V1ServiceListBuilder() - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(serviceB).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(serviceB) + .build(); Util.servicesInNamespacePodMode(wireMockServer, serviceListA, "a"); Util.servicesInNamespacePodMode(wireMockServer, serviceListB, "b"); @@ -170,11 +180,15 @@ private static void mockWatchers() { V1Endpoints endpointsB = Util.endpoints("b", "my-service", SERVICE_B_PORT, "127.0.0.1"); V1EndpointsList endpointsListA = new V1EndpointsListBuilder() - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(endpointsA).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(endpointsA) + .build(); V1EndpointsList endpointsListB = new V1EndpointsListBuilder() - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(endpointsB).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(endpointsB) + .build(); Util.endpointsInNamespacePodMode(wireMockServer, endpointsListA, "a"); Util.endpointsInNamespacePodMode(wireMockServer, endpointsListB, "b"); diff --git a/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/service/AllNamespacesTest.java b/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/service/AllNamespacesTest.java index 3ec2160cbc..cdaf2096a4 100644 --- a/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/service/AllNamespacesTest.java +++ b/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/service/AllNamespacesTest.java @@ -78,7 +78,7 @@ class AllNamespacesTest { private static MockedStatic clientUtils; private static final MockedStatic MOCKED_STATIC = Mockito - .mockStatic(KubernetesServiceInstanceMapper.class); + .mockStatic(KubernetesServiceInstanceMapper.class); @Autowired private WebClient.Builder builder; @@ -105,10 +105,10 @@ static void beforeAll() { // we mock host creation so that it becomes something like : localhost:8888 // then wiremock can catch this request, and we can assert for the result MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("service-a", "a", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("service-b", "b", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); ApiClient client = new ClientBuilder().setBasePath("http://localhost:" + wireMockServer.port()).build(); clientUtils = mockStatic(KubernetesClientUtils.class); @@ -136,21 +136,31 @@ static void afterAll() { void test() { serviceAMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); + .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); serviceBMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); - - String serviceAResult = builder.baseUrl(SERVICE_A_URL).build().method(HttpMethod.GET).retrieve() - .bodyToMono(String.class).block(); + .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); + + String serviceAResult = builder.baseUrl(SERVICE_A_URL) + .build() + .method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .block(); Assertions.assertThat(serviceAResult).isEqualTo("service-a-reached"); - String serviceBResult = builder.baseUrl(SERVICE_B_URL).build().method(HttpMethod.GET).retrieve() - .bodyToMono(String.class).block(); + String serviceBResult = builder.baseUrl(SERVICE_B_URL) + .build() + .method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .block(); Assertions.assertThat(serviceBResult).isEqualTo("service-b-reached"); CachingServiceInstanceListSupplier supplier = (CachingServiceInstanceListSupplier) loadBalancerClientFactory - .getIfAvailable().getProvider("service-a", ServiceInstanceListSupplier.class).getIfAvailable(); + .getIfAvailable() + .getProvider("service-a", ServiceInstanceListSupplier.class) + .getIfAvailable(); Assertions.assertThat(supplier.getDelegate().getClass()).isSameAs(KubernetesClientServicesListSupplier.class); } @@ -158,28 +168,36 @@ void test() { private static void mockWatchers() { V1Service serviceA = Util.service("a", "service-a", SERVICE_A_PORT); V1ServiceList serviceListA = new V1ServiceListBuilder().withKind("V1ServiceList") - .withMetadata(new V1ListMetaBuilder().withResourceVersion("0").build()) - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(serviceA).build(); + .withMetadata(new V1ListMetaBuilder().withResourceVersion("0").build()) + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(serviceA) + .build(); Util.servicesServiceMode(wireMockServer, serviceListA, "service-a"); V1Service serviceB = Util.service("b", "service-b", SERVICE_B_PORT); V1ServiceList serviceListB = new V1ServiceListBuilder().withKind("V1ServiceList") - .withMetadata(new V1ListMetaBuilder().withResourceVersion("0").build()) - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(serviceB).build(); + .withMetadata(new V1ListMetaBuilder().withResourceVersion("0").build()) + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(serviceB) + .build(); Util.servicesServiceMode(wireMockServer, serviceListB, "service-b"); V1Endpoints endpointsA = Util.endpoints("a", "service-a", SERVICE_A_PORT, "127.0.0.1"); V1EndpointsList endpointsListA = new V1EndpointsListBuilder().withKind("V1EndpointsList") - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(endpointsA).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(endpointsA) + .build(); Util.endpointsServiceMode(wireMockServer, endpointsListA, "service-a"); V1Endpoints endpointsB = Util.endpoints("b", "service-b", SERVICE_B_PORT, "127.0.0.1"); V1EndpointsList endpointsListB = new V1EndpointsListBuilder().withKind("V1EndpointsList") - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(endpointsB).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(endpointsB) + .build(); Util.endpointsServiceMode(wireMockServer, endpointsListB, "service-b"); } diff --git a/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/service/SelectiveNamespacesTest.java b/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/service/SelectiveNamespacesTest.java index cc23253b81..d66a8a888f 100644 --- a/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/service/SelectiveNamespacesTest.java +++ b/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/service/SelectiveNamespacesTest.java @@ -78,7 +78,7 @@ class SelectiveNamespacesTest { private static WireMockServer serviceCMockServer; private static final MockedStatic MOCKED_STATIC = Mockito - .mockStatic(KubernetesServiceInstanceMapper.class); + .mockStatic(KubernetesServiceInstanceMapper.class); private static MockedStatic clientUtils; @@ -111,13 +111,13 @@ static void beforeAll() { // we mock host creation so that it becomes something like : localhost:8888 // then wiremock can catch this request, and we can assert for the result MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("my-service", "a", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("my-service", "b", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("my-service", "c", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); ApiClient client = new ClientBuilder().setBasePath("http://localhost:" + wireMockServer.port()).build(); clientUtils = mockStatic(KubernetesClientUtils.class); @@ -150,19 +150,27 @@ static void afterAll() { void test() { serviceAMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); + .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); serviceBMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); + .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); serviceCMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-c-reached").withStatus(200))); - - String firstCallResult = builder.baseUrl(MY_SERVICE_URL).build().method(HttpMethod.GET).retrieve() - .bodyToMono(String.class).block(); - - String secondCallResult = builder.baseUrl(MY_SERVICE_URL).build().method(HttpMethod.GET).retrieve() - .bodyToMono(String.class).block(); + .willReturn(WireMock.aResponse().withBody("service-c-reached").withStatus(200))); + + String firstCallResult = builder.baseUrl(MY_SERVICE_URL) + .build() + .method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .block(); + + String secondCallResult = builder.baseUrl(MY_SERVICE_URL) + .build() + .method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .block(); // since selective namespaces is a Set, we need to be careful with assertion order if (firstCallResult.equals("service-a-reached")) { @@ -174,7 +182,9 @@ void test() { } CachingServiceInstanceListSupplier supplier = (CachingServiceInstanceListSupplier) loadBalancerClientFactory - .getIfAvailable().getProvider("my-service", ServiceInstanceListSupplier.class).getIfAvailable(); + .getIfAvailable() + .getProvider("my-service", ServiceInstanceListSupplier.class) + .getIfAvailable(); Assertions.assertThat(supplier.getDelegate().getClass()).isSameAs(KubernetesClientServicesListSupplier.class); } @@ -184,14 +194,20 @@ private static void mockWatchers() { V1Service serviceC = Util.service("c", "my-service", SERVICE_C_PORT); V1ServiceList serviceListA = new V1ServiceListBuilder() - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(serviceA).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(serviceA) + .build(); V1ServiceList serviceListB = new V1ServiceListBuilder() - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(serviceB).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(serviceB) + .build(); V1ServiceList serviceListC = new V1ServiceListBuilder() - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(serviceC).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(serviceC) + .build(); Util.servicesInNamespaceServiceMode(wireMockServer, serviceListA, "a", "my-service"); Util.servicesInNamespaceServiceMode(wireMockServer, serviceListB, "b", "my-service"); @@ -202,14 +218,20 @@ private static void mockWatchers() { V1Endpoints endpointsC = Util.endpoints("c", "my-service", SERVICE_C_PORT, "127.0.0.1"); V1EndpointsList endpointsListA = new V1EndpointsListBuilder() - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(endpointsA).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(endpointsA) + .build(); V1EndpointsList endpointsListB = new V1EndpointsListBuilder() - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(endpointsB).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(endpointsB) + .build(); V1EndpointsList endpointsListC = new V1EndpointsListBuilder() - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(endpointsC).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(endpointsC) + .build(); Util.endpointsInNamespaceServiceMode(wireMockServer, endpointsListA, "a", "my-service"); Util.endpointsInNamespaceServiceMode(wireMockServer, endpointsListB, "b", "my-service"); diff --git a/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/service/SpecificNamespaceTest.java b/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/service/SpecificNamespaceTest.java index 1d0675bf32..06783ef03d 100644 --- a/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/service/SpecificNamespaceTest.java +++ b/spring-cloud-kubernetes-client-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/client/loadbalancer/it/mode/service/SpecificNamespaceTest.java @@ -75,7 +75,7 @@ class SpecificNamespaceTest { private static WireMockServer serviceBMockServer; private static final MockedStatic MOCKED_STATIC = Mockito - .mockStatic(KubernetesServiceInstanceMapper.class); + .mockStatic(KubernetesServiceInstanceMapper.class); private static MockedStatic clientUtils; @@ -104,10 +104,10 @@ static void beforeAll() { // we mock host creation so that it becomes something like : localhost:8888 // then wiremock can catch this request, and we can assert for the result MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("my-service", "a", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("my-service", "b", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); ApiClient client = new ClientBuilder().setBasePath("http://localhost:" + wireMockServer.port()).build(); // we need to not mock 'getApplicationNamespace' @@ -139,17 +139,23 @@ static void afterAll() { void test() { serviceAMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); + .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); serviceBMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); - - String serviceAResult = builder.baseUrl(SERVICE_A_URL).build().method(HttpMethod.GET).retrieve() - .bodyToMono(String.class).block(); + .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); + + String serviceAResult = builder.baseUrl(SERVICE_A_URL) + .build() + .method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .block(); Assertions.assertThat(serviceAResult).isEqualTo("service-a-reached"); CachingServiceInstanceListSupplier supplier = (CachingServiceInstanceListSupplier) loadBalancerClientFactory - .getIfAvailable().getProvider("my-service", ServiceInstanceListSupplier.class).getIfAvailable(); + .getIfAvailable() + .getProvider("my-service", ServiceInstanceListSupplier.class) + .getIfAvailable(); Assertions.assertThat(supplier.getDelegate().getClass()).isSameAs(KubernetesClientServicesListSupplier.class); } @@ -158,11 +164,15 @@ private static void mockWatchers() { V1Service serviceB = Util.service("b", "my-service", SERVICE_B_PORT); V1ServiceList serviceListA = new V1ServiceListBuilder() - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(serviceA).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(serviceA) + .build(); V1ServiceList serviceListB = new V1ServiceListBuilder() - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(serviceB).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(serviceB) + .build(); Util.servicesInNamespaceServiceMode(wireMockServer, serviceListA, "a", "my-service"); Util.servicesInNamespaceServiceMode(wireMockServer, serviceListB, "b", "my-service"); @@ -171,11 +181,15 @@ private static void mockWatchers() { V1Endpoints endpointsB = Util.endpoints("b", "my-service", SERVICE_B_PORT, "127.0.0.1"); V1EndpointsList endpointsListA = new V1EndpointsListBuilder() - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(endpointsA).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(endpointsA) + .build(); V1EndpointsList endpointsListB = new V1EndpointsListBuilder() - .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()).endMetadata() - .withItems(endpointsB).build(); + .withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build()) + .endMetadata() + .withItems(endpointsB) + .build(); Util.endpointsInNamespaceServiceMode(wireMockServer, endpointsListA, "a", "my-service"); Util.endpointsInNamespaceServiceMode(wireMockServer, endpointsListB, "b", "my-service"); diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/KubernetesCommonsSanitizeAutoConfiguration.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/KubernetesCommonsSanitizeAutoConfiguration.java index 1244d1b3dd..89edd11ae4 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/KubernetesCommonsSanitizeAutoConfiguration.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/KubernetesCommonsSanitizeAutoConfiguration.java @@ -49,13 +49,13 @@ SanitizingFunction secretsPropertySourceSanitizingFunction() { PropertySource source = bootstrapPropertySource.getDelegate(); if (source instanceof SecretsPropertySource) { return new SanitizableData(propertySource, data.getKey(), data.getValue()) - .withValue(SanitizableData.SANITIZED_VALUE); + .withValue(SanitizableData.SANITIZED_VALUE); } } if (propertySource instanceof SecretsPropertySource) { return new SanitizableData(propertySource, data.getKey(), data.getValue()) - .withValue(SanitizableData.SANITIZED_VALUE); + .withValue(SanitizableData.SANITIZED_VALUE); } // at the moment, our structure is pretty simply, CompositePropertySource @@ -67,7 +67,7 @@ SanitizingFunction secretsPropertySourceSanitizingFunction() { for (PropertySource one : sources) { if (one.containsProperty(data.getKey()) && one instanceof SecretsPropertySource) { return new SanitizableData(propertySource, data.getKey(), data.getValue()) - .withValue(SanitizableData.SANITIZED_VALUE); + .withValue(SanitizableData.SANITIZED_VALUE); } } } diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/KubernetesNamespaceProvider.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/KubernetesNamespaceProvider.java index 9d639d9294..27052bc24f 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/KubernetesNamespaceProvider.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/KubernetesNamespaceProvider.java @@ -117,9 +117,9 @@ private String getServiceAccountNamespace() { // When using the binder we cannot use camelcase properties, it considers them // invalid serviceAccountNamespacePathString = binder - .bind("spring.cloud.kubernetes.client.service-account-namespace-path", Bindable.of(String.class), - bindHandler) - .orElse(SERVICE_ACCOUNT_NAMESPACE_PATH); + .bind("spring.cloud.kubernetes.client.service-account-namespace-path", Bindable.of(String.class), + bindHandler) + .orElse(SERVICE_ACCOUNT_NAMESPACE_PATH); } if (serviceAccountNamespace == null) { serviceAccountNamespace = getNamespaceFromServiceAccountFile(serviceAccountNamespacePathString); diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/ConfigDataRetryableConfigMapPropertySourceLocator.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/ConfigDataRetryableConfigMapPropertySourceLocator.java index 3abae46b88..6bb155bca9 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/ConfigDataRetryableConfigMapPropertySourceLocator.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/ConfigDataRetryableConfigMapPropertySourceLocator.java @@ -44,10 +44,11 @@ public ConfigDataRetryableConfigMapPropertySourceLocator( ConfigMapPropertySourceLocator configMapPropertySourceLocator, ConfigMapConfigProperties properties) { super(properties); this.configMapPropertySourceLocator = configMapPropertySourceLocator; - this.retryTemplate = RetryTemplate.builder().maxAttempts(properties.retry().maxAttempts()) - .exponentialBackoff(properties.retry().initialInterval(), properties.retry().multiplier(), - properties.retry().maxInterval()) - .build(); + this.retryTemplate = RetryTemplate.builder() + .maxAttempts(properties.retry().maxAttempts()) + .exponentialBackoff(properties.retry().initialInterval(), properties.retry().multiplier(), + properties.retry().maxInterval()) + .build(); } public ConfigDataRetryableConfigMapPropertySourceLocator( @@ -55,10 +56,11 @@ public ConfigDataRetryableConfigMapPropertySourceLocator( ConfigMapCache cache) { super(properties, cache); this.configMapPropertySourceLocator = configMapPropertySourceLocator; - this.retryTemplate = RetryTemplate.builder().maxAttempts(properties.retry().maxAttempts()) - .exponentialBackoff(properties.retry().initialInterval(), properties.retry().multiplier(), - properties.retry().maxInterval()) - .build(); + this.retryTemplate = RetryTemplate.builder() + .maxAttempts(properties.retry().maxAttempts()) + .exponentialBackoff(properties.retry().initialInterval(), properties.retry().multiplier(), + properties.retry().maxInterval()) + .build(); } @Override diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/ConfigDataRetryableSecretsPropertySourceLocator.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/ConfigDataRetryableSecretsPropertySourceLocator.java index 3cc71e96d5..d0c70e72f3 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/ConfigDataRetryableSecretsPropertySourceLocator.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/ConfigDataRetryableSecretsPropertySourceLocator.java @@ -43,20 +43,22 @@ public ConfigDataRetryableSecretsPropertySourceLocator(SecretsPropertySourceLoca SecretsConfigProperties secretsConfigProperties) { super(secretsConfigProperties); this.secretsPropertySourceLocator = propertySourceLocator; - this.retryTemplate = RetryTemplate.builder().maxAttempts(properties.retry().maxAttempts()) - .exponentialBackoff(properties.retry().initialInterval(), properties.retry().multiplier(), - properties.retry().maxInterval()) - .build(); + this.retryTemplate = RetryTemplate.builder() + .maxAttempts(properties.retry().maxAttempts()) + .exponentialBackoff(properties.retry().initialInterval(), properties.retry().multiplier(), + properties.retry().maxInterval()) + .build(); } public ConfigDataRetryableSecretsPropertySourceLocator(SecretsPropertySourceLocator propertySourceLocator, SecretsConfigProperties secretsConfigProperties, SecretsCache cache) { super(secretsConfigProperties, cache); this.secretsPropertySourceLocator = propertySourceLocator; - this.retryTemplate = RetryTemplate.builder().maxAttempts(properties.retry().maxAttempts()) - .exponentialBackoff(properties.retry().initialInterval(), properties.retry().multiplier(), - properties.retry().maxInterval()) - .build(); + this.retryTemplate = RetryTemplate.builder() + .maxAttempts(properties.retry().maxAttempts()) + .exponentialBackoff(properties.retry().initialInterval(), properties.retry().multiplier(), + properties.retry().maxInterval()) + .build(); } @Override diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/ConfigMapConfigProperties.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/ConfigMapConfigProperties.java index 2b3fc5ba16..beaf33d370 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/ConfigMapConfigProperties.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/ConfigMapConfigProperties.java @@ -64,14 +64,15 @@ public List determineSources(Environment environment) { return result; } - return this.sources - .stream().flatMap(s -> s.normalize(this.name, this.namespace, this.labels, - this.includeProfileSpecificSources, this.failFast, this.useNameAsPrefix, environment)) - .collect(Collectors.toList()); + return this.sources.stream() + .flatMap(s -> s.normalize(this.name, this.namespace, this.labels, this.includeProfileSpecificSources, + this.failFast, this.useNameAsPrefix, environment)) + .collect(Collectors.toList()); } /** * Config map source. + * * @param name The name of the ConfigMap. * @param namespace The namespace where the ConfigMap is found. * @param labels labels of the config map to look for against. diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/ConfigUtils.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/ConfigUtils.java index 9efc8ba77f..5f40858eab 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/ConfigUtils.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/ConfigUtils.java @@ -194,7 +194,7 @@ public static MultipleSourcesContainer processNamedData(List hashByName = strippedSources.stream() - .collect(Collectors.toMap(StrippedSourceContainer::name, Function.identity())); + .collect(Collectors.toMap(StrippedSourceContainer::name, Function.identity())); LinkedHashSet foundSourceNames = new LinkedHashSet<>(); Map data = new HashMap<>(); @@ -237,7 +237,7 @@ static boolean processSource(boolean includeDefaultProfileData, Environment envi boolean emptyActiveProfiles = activeProfiles.isEmpty(); boolean profileBasedSourceName = activeProfiles.stream() - .anyMatch(activeProfile -> sourceName.endsWith("-" + activeProfile)); + .anyMatch(activeProfile -> sourceName.endsWith("-" + activeProfile)); boolean defaultProfilePresent = activeProfiles.contains("default"); @@ -255,9 +255,12 @@ static boolean processSource(boolean includeDefaultProfileData, Environment envi */ static BooleanSupplier rawDataContainsProfileBasedSource(List activeProfiles, Map sourceRawData) { - return () -> Optional.ofNullable(sourceRawData).orElse(Map.of()).keySet().stream() - .anyMatch(keyName -> activeProfiles.stream() - .anyMatch(activeProfile -> ENDS_WITH_PROFILE_AND_EXTENSION.test(keyName, activeProfile))); + return () -> Optional.ofNullable(sourceRawData) + .orElse(Map.of()) + .keySet() + .stream() + .anyMatch(keyName -> activeProfiles.stream() + .anyMatch(activeProfile -> ENDS_WITH_PROFILE_AND_EXTENSION.test(keyName, activeProfile))); } /** @@ -293,7 +296,8 @@ public static MultipleSourcesContainer processLabeledData(List byProfile = containers.stream() - .filter(one -> sourceNamesByLabelsWithProfile.contains(one.name())).toList(); + .filter(one -> sourceNamesByLabelsWithProfile.contains(one.name())) + .toList(); // this makes sure that we first have "app" and then "app-dev" in the list List all = new ArrayList<>(byLabels.size() + byProfile.size()); @@ -329,8 +333,9 @@ public static void registerSingle(ConfigurableBootstrapContext bootstrapCont bootstrapContext.registerIfAbsent(cls, BootstrapRegistry.InstanceSupplier.of(instance)); bootstrapContext.addCloseListener(event -> { if (event.getApplicationContext().getBeanFactory().getSingleton(name) == null) { - event.getApplicationContext().getBeanFactory().registerSingleton(name, - event.getBootstrapContext().get(cls)); + event.getApplicationContext() + .getBeanFactory() + .registerSingleton(name, event.getBootstrapContext().get(cls)); } }); } diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/KubernetesBootstrapConfiguration.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/KubernetesBootstrapConfiguration.java index 48ae9f8a2d..95fef629ac 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/KubernetesBootstrapConfiguration.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/KubernetesBootstrapConfiguration.java @@ -49,9 +49,11 @@ public class KubernetesBootstrapConfiguration { public static class RetryConfiguration { public static RetryOperationsInterceptor retryOperationsInterceptor(RetryProperties retryProperties) { - return RetryInterceptorBuilder.stateless().backOffOptions(retryProperties.initialInterval(), - retryProperties.multiplier(), retryProperties.maxInterval()) - .maxAttempts(retryProperties.maxAttempts()).build(); + return RetryInterceptorBuilder.stateless() + .backOffOptions(retryProperties.initialInterval(), retryProperties.multiplier(), + retryProperties.maxInterval()) + .maxAttempts(retryProperties.maxAttempts()) + .build(); } @Bean diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/KubernetesConfigDataLocationResolver.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/KubernetesConfigDataLocationResolver.java index 9463b86b07..95907843ad 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/KubernetesConfigDataLocationResolver.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/KubernetesConfigDataLocationResolver.java @@ -162,7 +162,7 @@ private static PropertyHolder of(ConfigDataLocationResolverContext context) { String applicationName = binder.bind("spring.application.name", String.class).orElse(null); String namespace = binder.bind("spring.cloud.kubernetes.client.namespace", String.class) - .orElse(binder.bind("kubernetes.namespace", String.class).orElse("")); + .orElse(binder.bind("kubernetes.namespace", String.class).orElse("")); KubernetesClientProperties kubernetesClientProperties = clientProperties(context, namespace); ConfigMapAndSecrets both = ConfigMapAndSecrets.of(binder); @@ -176,13 +176,14 @@ private static KubernetesClientProperties clientProperties(ConfigDataLocationRes KubernetesClientProperties kubernetesClientProperties; if (context.getBootstrapContext().isRegistered(KubernetesClientProperties.class)) { - kubernetesClientProperties = context.getBootstrapContext().get(KubernetesClientProperties.class) - .withNamespace(namespace); + kubernetesClientProperties = context.getBootstrapContext() + .get(KubernetesClientProperties.class) + .withNamespace(namespace); } else { kubernetesClientProperties = context.getBinder() - .bindOrCreate(KubernetesClientProperties.PREFIX, Bindable.of(KubernetesClientProperties.class)) - .withNamespace(namespace); + .bindOrCreate(KubernetesClientProperties.PREFIX, Bindable.of(KubernetesClientProperties.class)) + .withNamespace(namespace); } return kubernetesClientProperties; diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/KubernetesConfigDataResource.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/KubernetesConfigDataResource.java index a2f958639b..d4355f8189 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/KubernetesConfigDataResource.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/KubernetesConfigDataResource.java @@ -127,8 +127,9 @@ public int hashCode() { @Override public String toString() { - return new ToStringCreator(this).append("optional", optional).append("profiles", profiles.getAccepted()) - .toString(); + return new ToStringCreator(this).append("optional", optional) + .append("profiles", profiles.getAccepted()) + .toString(); } diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/KubernetesConfigServerBootstrapper.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/KubernetesConfigServerBootstrapper.java index d804d2cc6d..c55703ec0e 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/KubernetesConfigServerBootstrapper.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/KubernetesConfigServerBootstrapper.java @@ -40,8 +40,9 @@ public static boolean hasConfigServerInstanceProvider() { public static KubernetesDiscoveryProperties createKubernetesDiscoveryProperties(Binder binder, BindHandler bindHandler) { - return binder.bind(KubernetesDiscoveryProperties.PREFIX, Bindable.of(KubernetesDiscoveryProperties.class), - bindHandler).orElseGet(() -> KubernetesDiscoveryProperties.DEFAULT); + return binder + .bind(KubernetesDiscoveryProperties.PREFIX, Bindable.of(KubernetesDiscoveryProperties.class), bindHandler) + .orElseGet(() -> KubernetesDiscoveryProperties.DEFAULT); } public static KubernetesDiscoveryProperties createKubernetesDiscoveryProperties(BootstrapContext bootstrapContext) { @@ -52,21 +53,19 @@ public static KubernetesDiscoveryProperties createKubernetesDiscoveryProperties( public static KubernetesClientProperties createKubernetesClientProperties(Binder binder, BindHandler bindHandler) { return binder.bindOrCreate(KubernetesClientProperties.PREFIX, Bindable.of(KubernetesClientProperties.class)) - .withNamespace(new KubernetesNamespaceProvider(binder, bindHandler).getNamespace()); + .withNamespace(new KubernetesNamespaceProvider(binder, bindHandler).getNamespace()); } public static KubernetesClientProperties createKubernetesClientProperties(BootstrapContext bootstrapContext) { PropertyResolver propertyResolver = getPropertyResolver(bootstrapContext); return getPropertyResolver(bootstrapContext) - .resolveOrCreateConfigurationProperties(KubernetesClientProperties.PREFIX, - KubernetesClientProperties.class) - .withNamespace( - propertyResolver.get(KubernetesNamespaceProvider.NAMESPACE_PROPERTY, String.class, null)); + .resolveOrCreateConfigurationProperties(KubernetesClientProperties.PREFIX, KubernetesClientProperties.class) + .withNamespace(propertyResolver.get(KubernetesNamespaceProvider.NAMESPACE_PROPERTY, String.class, null)); } public static Boolean getDiscoveryEnabled(Binder binder, BindHandler bindHandler) { return binder.bind(ConfigClientProperties.CONFIG_DISCOVERY_ENABLED, Bindable.of(Boolean.class), bindHandler) - .orElse(false); + .orElse(false); } public static Boolean getDiscoveryEnabled(BootstrapContext bootstrapContext) { diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/LabeledSourceData.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/LabeledSourceData.java index e8f19466c1..df4e6aab1f 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/LabeledSourceData.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/LabeledSourceData.java @@ -49,8 +49,10 @@ public final SourceData compute(Map labels, ConfigUtils.Prefix p // is using provided labels, // unlike when the data is present: when we use secret names if (data.names().isEmpty()) { - String names = labels.keySet().stream().sorted() - .collect(Collectors.joining(PROPERTY_SOURCE_NAME_SEPARATOR)); + String names = labels.keySet() + .stream() + .sorted() + .collect(Collectors.joining(PROPERTY_SOURCE_NAME_SEPARATOR)); return SourceData.emptyRecord(ConfigUtils.sourceName(target, names, namespace)); } @@ -61,8 +63,10 @@ public final SourceData compute(Map labels, ConfigUtils.Prefix p prefixToUse = prefix.prefixProvider().get(); } else { - prefixToUse = data.names().stream().sorted() - .collect(Collectors.joining(PROPERTY_SOURCE_NAME_SEPARATOR)); + prefixToUse = data.names() + .stream() + .sorted() + .collect(Collectors.joining(PROPERTY_SOURCE_NAME_SEPARATOR)); } PrefixContext prefixContext = new PrefixContext(data.data(), prefixToUse, namespace, data.names()); diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/NormalizedSource.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/NormalizedSource.java index b0500c7503..6043cbd09b 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/NormalizedSource.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/NormalizedSource.java @@ -24,7 +24,8 @@ * * @author wind57 */ -public sealed abstract class NormalizedSource permits NamedSecretNormalizedSource, LabeledSecretNormalizedSource, NamedConfigMapNormalizedSource, LabeledConfigMapNormalizedSource { +public sealed abstract class NormalizedSource permits NamedSecretNormalizedSource, LabeledSecretNormalizedSource, + NamedConfigMapNormalizedSource, LabeledConfigMapNormalizedSource { private final String namespace; diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/PropertySourceUtils.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/PropertySourceUtils.java index 55cac665df..70884f6755 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/PropertySourceUtils.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/PropertySourceUtils.java @@ -67,8 +67,9 @@ private PropertySourceUtils() { /** * Function to convert Properties to a Map. */ - public static final Function> PROPERTIES_TO_MAP = p -> p.entrySet().stream() - .collect(Collectors.toMap(e -> e.getKey().toString(), Map.Entry::getValue)); + public static final Function> PROPERTIES_TO_MAP = p -> p.entrySet() + .stream() + .collect(Collectors.toMap(e -> e.getKey().toString(), Map.Entry::getValue)); /** * Function to convert String into Properties with an environment. diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/RetryProperties.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/RetryProperties.java index e160efccc1..203a04d5af 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/RetryProperties.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/RetryProperties.java @@ -19,7 +19,6 @@ import org.springframework.boot.context.properties.bind.DefaultValue; /** - * * @author wind57 Kubernetes config retry properties. * @param initialInterval Initial retry interval in milliseconds. * @param multiplier Maximum interval for backoff. diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/SecretsConfigProperties.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/SecretsConfigProperties.java index ea48184828..baef450972 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/SecretsConfigProperties.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/SecretsConfigProperties.java @@ -65,10 +65,10 @@ public List determineSources(Environment environment) { return result; } - return this.sources - .stream().flatMap(s -> s.normalize(this.name, this.namespace, this.labels, - this.includeProfileSpecificSources, this.failFast, this.useNameAsPrefix, environment)) - .collect(Collectors.toList()); + return this.sources.stream() + .flatMap(s -> s.normalize(this.name, this.namespace, this.labels, this.includeProfileSpecificSources, + this.failFast, this.useNameAsPrefix, environment)) + .collect(Collectors.toList()); } /** diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/SecretsPropertySourceLocator.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/SecretsPropertySourceLocator.java index cb3ea66ae2..2eb33c801c 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/SecretsPropertySourceLocator.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/SecretsPropertySourceLocator.java @@ -87,7 +87,7 @@ public PropertySource locate(Environment environment) { if (this.properties.enableApi()) { uniqueSources - .forEach(s -> composite.addPropertySource(getSecretsPropertySourceForSingleSecret(env, s))); + .forEach(s -> composite.addPropertySource(getSecretsPropertySourceForSingleSecret(env, s))); } cache.discardAll(); @@ -125,8 +125,11 @@ protected void putPathConfig(CompositePropertySource composite) { LOG.warn("Error walking properties files", e); return null; } - }).filter(Objects::nonNull).filter(Files::isRegularFile).collect(new SecretsPropertySourceCollector()) - .forEach(composite::addPropertySource); + }) + .filter(Objects::nonNull) + .filter(Files::isRegularFile) + .collect(new SecretsPropertySourceCollector()) + .forEach(composite::addPropertySource); } /** diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/SourceDataEntriesProcessor.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/SourceDataEntriesProcessor.java index d54cec8764..7e313b70d1 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/SourceDataEntriesProcessor.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/SourceDataEntriesProcessor.java @@ -156,8 +156,10 @@ record WeightedEntry(Map.Entry entry, int weight) { } } - return weightedEntries.stream().sorted(Comparator.comparing(WeightedEntry::weight)).map(WeightedEntry::entry) - .toList(); + return weightedEntries.stream() + .sorted(Comparator.comparing(WeightedEntry::weight)) + .map(WeightedEntry::entry) + .toList(); } private static Map defaultProcessAllEntries(Map input, Environment environment, diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/ConfigReloadProperties.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/ConfigReloadProperties.java index e37d2d51fe..9813eb3260 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/ConfigReloadProperties.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/ConfigReloadProperties.java @@ -24,6 +24,7 @@ /** * General configuration for the configuration reload. + * * @param enabled Enables the Kubernetes configuration reload on change. * @param monitoringConfigMaps Enables monitoring on secrets to detect changes. * @param monitoringSecrets Monitor secrets or not. @@ -40,7 +41,6 @@ * avoid having all instances of the same application restart at the same time. This * property configures the maximum of amount of wait time from the moment the signal is * received that a restart is needed until the moment the restart is actually triggered - * * @author Nicola Ferraro */ @ConfigurationProperties(prefix = "spring.cloud.kubernetes.reload") diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/ConfigReloadUtil.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/ConfigReloadUtil.java index d9b0f933fa..9044815080 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/ConfigReloadUtil.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/ConfigReloadUtil.java @@ -72,8 +72,9 @@ public static > List findPropertySources(Class ConfigurableEnvironment environment) { List managedSources = new ArrayList<>(); - List> sources = environment.getPropertySources().stream() - .collect(Collectors.toCollection(ArrayList::new)); + List> sources = environment.getPropertySources() + .stream() + .collect(Collectors.toCollection(ArrayList::new)); LOG.debug(() -> "environment from findPropertySources: " + environment); LOG.debug(() -> "environment sources from findPropertySources : " + sources); diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/condition/EventReloadDetectionMode.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/condition/EventReloadDetectionMode.java index 9e685ee0bd..8fcea15e9c 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/condition/EventReloadDetectionMode.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/condition/EventReloadDetectionMode.java @@ -38,7 +38,7 @@ public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) return true; } return ConfigReloadProperties.ReloadDetectionMode.EVENT.name() - .equalsIgnoreCase(environment.getProperty(Constants.RELOAD_MODE)); + .equalsIgnoreCase(environment.getProperty(Constants.RELOAD_MODE)); } } diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/condition/PollingReloadDetectionMode.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/condition/PollingReloadDetectionMode.java index 46bc4ab418..a3ecfe803b 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/condition/PollingReloadDetectionMode.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/condition/PollingReloadDetectionMode.java @@ -38,7 +38,7 @@ public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) return false; } return ConfigReloadProperties.ReloadDetectionMode.POLLING.name() - .equalsIgnoreCase(environment.getProperty(Constants.RELOAD_MODE)); + .equalsIgnoreCase(environment.getProperty(Constants.RELOAD_MODE)); } } diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/discovery/DiscoveryClientUtils.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/discovery/DiscoveryClientUtils.java index 62d1d0a0e3..e95db15e46 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/discovery/DiscoveryClientUtils.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/discovery/DiscoveryClientUtils.java @@ -75,8 +75,9 @@ public static Map serviceInstanceMetadata(Map p } if (metadataProps.addPorts()) { - Map portsDataValueAsString = portsData.entrySet().stream() - .collect(Collectors.toMap(Map.Entry::getKey, en -> Integer.toString(en.getValue()))); + Map portsDataValueAsString = portsData.entrySet() + .stream() + .collect(Collectors.toMap(Map.Entry::getKey, en -> Integer.toString(en.getValue()))); Map portMetadata = keysWithPrefix(portsDataValueAsString, properties.metadata().portsPrefix()); if (!portMetadata.isEmpty()) { @@ -166,8 +167,8 @@ static String primaryPortName(KubernetesDiscoveryProperties properties, Map labels, Map annotations) { diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/discovery/Service.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/discovery/Service.java index 1fa2db1e30..01cdc1d5aa 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/discovery/Service.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/discovery/Service.java @@ -20,6 +20,7 @@ /** * Use for discovery service implementation. + * * @author wind57 */ public record Service(String name, List serviceInstances) { diff --git a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/profile/AbstractKubernetesProfileEnvironmentPostProcessor.java b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/profile/AbstractKubernetesProfileEnvironmentPostProcessor.java index 8bba05fdda..ae2bf0b5ed 100644 --- a/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/profile/AbstractKubernetesProfileEnvironmentPostProcessor.java +++ b/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/profile/AbstractKubernetesProfileEnvironmentPostProcessor.java @@ -95,10 +95,11 @@ private void addNamespaceFromServiceAccountFile(ConfigurableEnvironment environm String serviceAccountNamespacePathString = environment.getProperty(NAMESPACE_PATH_PROPERTY, SERVICE_ACCOUNT_NAMESPACE_PATH); String namespace = KubernetesNamespaceProvider - .getNamespaceFromServiceAccountFile(serviceAccountNamespacePathString); + .getNamespaceFromServiceAccountFile(serviceAccountNamespacePathString); if (StringUtils.hasText(namespace)) { - environment.getPropertySources().addLast(new MapPropertySource(PROPERTY_SOURCE_NAME, - Collections.singletonMap(NAMESPACE_PROPERTY, namespace))); + environment.getPropertySources() + .addLast(new MapPropertySource(PROPERTY_SOURCE_NAME, + Collections.singletonMap(NAMESPACE_PROPERTY, namespace))); } } diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/KubernetesClientPropertiesTests.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/KubernetesClientPropertiesTests.java index c7b360456b..a3ceef1ba5 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/KubernetesClientPropertiesTests.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/KubernetesClientPropertiesTests.java @@ -63,138 +63,144 @@ void testDefaults() { assertThat(properties.oauthToken()).isNull(); assertThat(properties.noProxy()).isNull(); assertThat(properties.serviceAccountNamespacePath()) - .isEqualTo("/var/run/secrets/kubernetes.io/serviceaccount/namespace"); + .isEqualTo("/var/run/secrets/kubernetes.io/serviceaccount/namespace"); assertThat(properties.userAgent()).isEqualTo("Spring-Cloud-Kubernetes-Application"); }); } @Test void testNonDefaults() { - new ApplicationContextRunner().withUserConfiguration(Config.class).withPropertyValues( - "spring.cloud.kubernetes.client.trust-certs=true", - "spring.cloud.kubernetes.client.master-url=master-url", "spring.cloud.kubernetes.client.api-version=1", - "spring.cloud.kubernetes.client.namespace=namespace", - "spring.cloud.kubernetes.client.ca-cert-file=ca-cert-file", - "spring.cloud.kubernetes.client.ca-cert-data=ca-cert-data", - "spring.cloud.kubernetes.client.client-cert-file=client-cert-file", - "spring.cloud.kubernetes.client.client-cert-data=client-cert-data", - "spring.cloud.kubernetes.client.client-key-file=client-key-file", - "spring.cloud.kubernetes.client.client-key-data=client-key-data", - "spring.cloud.kubernetes.client.client-key-algo=client-key-algo", - "spring.cloud.kubernetes.client.client-key-passphrase=client-key-passphrase", - "spring.cloud.kubernetes.client.username=username", "spring.cloud.kubernetes.client.password=password", - "spring.cloud.kubernetes.client.watch-reconnect-interval=200ms", - "spring.cloud.kubernetes.client.watch-reconnect-limit=300ms", - "spring.cloud.kubernetes.client.connection-timeout=400ms", - "spring.cloud.kubernetes.client.request-timeout=500ms", - "spring.cloud.kubernetes.client.rolling-timeout=600ms", - "spring.cloud.kubernetes.client.logging-interval=700ms", - "spring.cloud.kubernetes.client.http-proxy=http-proxy", - "spring.cloud.kubernetes.client.https-proxy=https-proxy", - "spring.cloud.kubernetes.client.proxy-username=proxy-username", - "spring.cloud.kubernetes.client.proxy-password=proxy-password", - "spring.cloud.kubernetes.client.oauth-token=oauth-token", - "spring.cloud.kubernetes.client.no-proxy[0]=a", "spring.cloud.kubernetes.client.no-proxy[1]=b", - "spring.cloud.kubernetes.client.service-account-namespace-path=path", - "spring.cloud.kubernetes.client.user-agent=user-agent").run(context -> { - KubernetesClientProperties properties = context.getBean(KubernetesClientProperties.class); - assertThat(properties).isNotNull(); - assertThat(properties.trustCerts()).isTrue(); - assertThat(properties.masterUrl()).isEqualTo("master-url"); - assertThat(properties.apiVersion()).isEqualTo("1"); - assertThat(properties.namespace()).isEqualTo("namespace"); - assertThat(properties.caCertFile()).isEqualTo("ca-cert-file"); - assertThat(properties.caCertData()).isEqualTo("ca-cert-data"); - assertThat(properties.clientCertFile()).isEqualTo("client-cert-file"); - assertThat(properties.clientCertData()).isEqualTo("client-cert-data"); - assertThat(properties.clientKeyFile()).isEqualTo("client-key-file"); - assertThat(properties.clientKeyData()).isEqualTo("client-key-data"); - assertThat(properties.clientKeyAlgo()).isEqualTo("client-key-algo"); - assertThat(properties.clientKeyPassphrase()).isEqualTo("client-key-passphrase"); - assertThat(properties.username()).isEqualTo("username"); - assertThat(properties.password()).isEqualTo("password"); - assertThat(properties.watchReconnectInterval()).isEqualTo(Duration.ofMillis(200)); - assertThat(properties.watchReconnectLimit()).isEqualTo(Duration.ofMillis(300)); - assertThat(properties.connectionTimeout()).isEqualTo(Duration.ofMillis(400)); - assertThat(properties.requestTimeout()).isEqualTo(Duration.ofMillis(500)); - assertThat(properties.rollingTimeout()).isEqualTo(Duration.ofMillis(600)); - assertThat(properties.loggingInterval()).isEqualTo(Duration.ofMillis(700)); - assertThat(properties.httpProxy()).isEqualTo("http-proxy"); - assertThat(properties.httpsProxy()).isEqualTo("https-proxy"); - assertThat(properties.proxyUsername()).isEqualTo("proxy-username"); - assertThat(properties.proxyPassword()).isEqualTo("proxy-password"); - assertThat(properties.oauthToken()).isEqualTo("oauth-token"); - assertThat(properties.noProxy().length).isEqualTo(2); - assertThat(properties.noProxy()[0]).isEqualTo("a"); - assertThat(properties.noProxy()[1]).isEqualTo("b"); - assertThat(properties.serviceAccountNamespacePath()).isEqualTo("path"); - assertThat(properties.userAgent()).isEqualTo("user-agent"); - }); + new ApplicationContextRunner().withUserConfiguration(Config.class) + .withPropertyValues("spring.cloud.kubernetes.client.trust-certs=true", + "spring.cloud.kubernetes.client.master-url=master-url", + "spring.cloud.kubernetes.client.api-version=1", + "spring.cloud.kubernetes.client.namespace=namespace", + "spring.cloud.kubernetes.client.ca-cert-file=ca-cert-file", + "spring.cloud.kubernetes.client.ca-cert-data=ca-cert-data", + "spring.cloud.kubernetes.client.client-cert-file=client-cert-file", + "spring.cloud.kubernetes.client.client-cert-data=client-cert-data", + "spring.cloud.kubernetes.client.client-key-file=client-key-file", + "spring.cloud.kubernetes.client.client-key-data=client-key-data", + "spring.cloud.kubernetes.client.client-key-algo=client-key-algo", + "spring.cloud.kubernetes.client.client-key-passphrase=client-key-passphrase", + "spring.cloud.kubernetes.client.username=username", + "spring.cloud.kubernetes.client.password=password", + "spring.cloud.kubernetes.client.watch-reconnect-interval=200ms", + "spring.cloud.kubernetes.client.watch-reconnect-limit=300ms", + "spring.cloud.kubernetes.client.connection-timeout=400ms", + "spring.cloud.kubernetes.client.request-timeout=500ms", + "spring.cloud.kubernetes.client.rolling-timeout=600ms", + "spring.cloud.kubernetes.client.logging-interval=700ms", + "spring.cloud.kubernetes.client.http-proxy=http-proxy", + "spring.cloud.kubernetes.client.https-proxy=https-proxy", + "spring.cloud.kubernetes.client.proxy-username=proxy-username", + "spring.cloud.kubernetes.client.proxy-password=proxy-password", + "spring.cloud.kubernetes.client.oauth-token=oauth-token", + "spring.cloud.kubernetes.client.no-proxy[0]=a", "spring.cloud.kubernetes.client.no-proxy[1]=b", + "spring.cloud.kubernetes.client.service-account-namespace-path=path", + "spring.cloud.kubernetes.client.user-agent=user-agent") + .run(context -> { + KubernetesClientProperties properties = context.getBean(KubernetesClientProperties.class); + assertThat(properties).isNotNull(); + assertThat(properties.trustCerts()).isTrue(); + assertThat(properties.masterUrl()).isEqualTo("master-url"); + assertThat(properties.apiVersion()).isEqualTo("1"); + assertThat(properties.namespace()).isEqualTo("namespace"); + assertThat(properties.caCertFile()).isEqualTo("ca-cert-file"); + assertThat(properties.caCertData()).isEqualTo("ca-cert-data"); + assertThat(properties.clientCertFile()).isEqualTo("client-cert-file"); + assertThat(properties.clientCertData()).isEqualTo("client-cert-data"); + assertThat(properties.clientKeyFile()).isEqualTo("client-key-file"); + assertThat(properties.clientKeyData()).isEqualTo("client-key-data"); + assertThat(properties.clientKeyAlgo()).isEqualTo("client-key-algo"); + assertThat(properties.clientKeyPassphrase()).isEqualTo("client-key-passphrase"); + assertThat(properties.username()).isEqualTo("username"); + assertThat(properties.password()).isEqualTo("password"); + assertThat(properties.watchReconnectInterval()).isEqualTo(Duration.ofMillis(200)); + assertThat(properties.watchReconnectLimit()).isEqualTo(Duration.ofMillis(300)); + assertThat(properties.connectionTimeout()).isEqualTo(Duration.ofMillis(400)); + assertThat(properties.requestTimeout()).isEqualTo(Duration.ofMillis(500)); + assertThat(properties.rollingTimeout()).isEqualTo(Duration.ofMillis(600)); + assertThat(properties.loggingInterval()).isEqualTo(Duration.ofMillis(700)); + assertThat(properties.httpProxy()).isEqualTo("http-proxy"); + assertThat(properties.httpsProxy()).isEqualTo("https-proxy"); + assertThat(properties.proxyUsername()).isEqualTo("proxy-username"); + assertThat(properties.proxyPassword()).isEqualTo("proxy-password"); + assertThat(properties.oauthToken()).isEqualTo("oauth-token"); + assertThat(properties.noProxy().length).isEqualTo(2); + assertThat(properties.noProxy()[0]).isEqualTo("a"); + assertThat(properties.noProxy()[1]).isEqualTo("b"); + assertThat(properties.serviceAccountNamespacePath()).isEqualTo("path"); + assertThat(properties.userAgent()).isEqualTo("user-agent"); + }); } @Test void testCopyWithNamespaceConstructor() { - new ApplicationContextRunner().withUserConfiguration(Config.class).withPropertyValues( - "spring.cloud.kubernetes.client.trust-certs=true", - "spring.cloud.kubernetes.client.master-url=master-url", "spring.cloud.kubernetes.client.api-version=1", - "spring.cloud.kubernetes.client.namespace=namespace", - "spring.cloud.kubernetes.client.ca-cert-file=ca-cert-file", - "spring.cloud.kubernetes.client.ca-cert-data=ca-cert-data", - "spring.cloud.kubernetes.client.client-cert-file=client-cert-file", - "spring.cloud.kubernetes.client.client-cert-data=client-cert-data", - "spring.cloud.kubernetes.client.client-key-file=client-key-file", - "spring.cloud.kubernetes.client.client-key-data=client-key-data", - "spring.cloud.kubernetes.client.client-key-algo=client-key-algo", - "spring.cloud.kubernetes.client.client-key-passphrase=client-key-passphrase", - "spring.cloud.kubernetes.client.username=username", "spring.cloud.kubernetes.client.password=password", - "spring.cloud.kubernetes.client.watch-reconnect-interval=200ms", - "spring.cloud.kubernetes.client.watch-reconnect-limit=300ms", - "spring.cloud.kubernetes.client.connection-timeout=400ms", - "spring.cloud.kubernetes.client.request-timeout=500ms", - "spring.cloud.kubernetes.client.rolling-timeout=600ms", - "spring.cloud.kubernetes.client.logging-interval=700ms", - "spring.cloud.kubernetes.client.http-proxy=http-proxy", - "spring.cloud.kubernetes.client.https-proxy=https-proxy", - "spring.cloud.kubernetes.client.proxy-username=proxy-username", - "spring.cloud.kubernetes.client.proxy-password=proxy-password", - "spring.cloud.kubernetes.client.oauth-token=oauth-token", - "spring.cloud.kubernetes.client.no-proxy[0]=a", "spring.cloud.kubernetes.client.no-proxy[1]=b", - "spring.cloud.kubernetes.client.service-account-namespace-path=path", - "spring.cloud.kubernetes.client.user-agent=user-agent").run(context -> { - KubernetesClientProperties properties = context.getBean(KubernetesClientProperties.class) - .withNamespace("non-default"); - assertThat(properties).isNotNull(); - assertThat(properties.trustCerts()).isTrue(); - assertThat(properties.masterUrl()).isEqualTo("master-url"); - assertThat(properties.apiVersion()).isEqualTo("1"); - assertThat(properties.namespace()).isEqualTo("non-default"); - assertThat(properties.caCertFile()).isEqualTo("ca-cert-file"); - assertThat(properties.caCertData()).isEqualTo("ca-cert-data"); - assertThat(properties.clientCertFile()).isEqualTo("client-cert-file"); - assertThat(properties.clientCertData()).isEqualTo("client-cert-data"); - assertThat(properties.clientKeyFile()).isEqualTo("client-key-file"); - assertThat(properties.clientKeyData()).isEqualTo("client-key-data"); - assertThat(properties.clientKeyAlgo()).isEqualTo("client-key-algo"); - assertThat(properties.clientKeyPassphrase()).isEqualTo("client-key-passphrase"); - assertThat(properties.username()).isEqualTo("username"); - assertThat(properties.password()).isEqualTo("password"); - assertThat(properties.watchReconnectInterval()).isEqualTo(Duration.ofMillis(200)); - assertThat(properties.watchReconnectLimit()).isEqualTo(Duration.ofMillis(300)); - assertThat(properties.connectionTimeout()).isEqualTo(Duration.ofMillis(400)); - assertThat(properties.requestTimeout()).isEqualTo(Duration.ofMillis(500)); - assertThat(properties.rollingTimeout()).isEqualTo(Duration.ofMillis(600)); - assertThat(properties.loggingInterval()).isEqualTo(Duration.ofMillis(700)); - assertThat(properties.httpProxy()).isEqualTo("http-proxy"); - assertThat(properties.httpsProxy()).isEqualTo("https-proxy"); - assertThat(properties.proxyUsername()).isEqualTo("proxy-username"); - assertThat(properties.proxyPassword()).isEqualTo("proxy-password"); - assertThat(properties.oauthToken()).isEqualTo("oauth-token"); - assertThat(properties.noProxy().length).isEqualTo(2); - assertThat(properties.noProxy()[0]).isEqualTo("a"); - assertThat(properties.noProxy()[1]).isEqualTo("b"); - assertThat(properties.serviceAccountNamespacePath()).isEqualTo("path"); - assertThat(properties.userAgent()).isEqualTo("user-agent"); - }); + new ApplicationContextRunner().withUserConfiguration(Config.class) + .withPropertyValues("spring.cloud.kubernetes.client.trust-certs=true", + "spring.cloud.kubernetes.client.master-url=master-url", + "spring.cloud.kubernetes.client.api-version=1", + "spring.cloud.kubernetes.client.namespace=namespace", + "spring.cloud.kubernetes.client.ca-cert-file=ca-cert-file", + "spring.cloud.kubernetes.client.ca-cert-data=ca-cert-data", + "spring.cloud.kubernetes.client.client-cert-file=client-cert-file", + "spring.cloud.kubernetes.client.client-cert-data=client-cert-data", + "spring.cloud.kubernetes.client.client-key-file=client-key-file", + "spring.cloud.kubernetes.client.client-key-data=client-key-data", + "spring.cloud.kubernetes.client.client-key-algo=client-key-algo", + "spring.cloud.kubernetes.client.client-key-passphrase=client-key-passphrase", + "spring.cloud.kubernetes.client.username=username", + "spring.cloud.kubernetes.client.password=password", + "spring.cloud.kubernetes.client.watch-reconnect-interval=200ms", + "spring.cloud.kubernetes.client.watch-reconnect-limit=300ms", + "spring.cloud.kubernetes.client.connection-timeout=400ms", + "spring.cloud.kubernetes.client.request-timeout=500ms", + "spring.cloud.kubernetes.client.rolling-timeout=600ms", + "spring.cloud.kubernetes.client.logging-interval=700ms", + "spring.cloud.kubernetes.client.http-proxy=http-proxy", + "spring.cloud.kubernetes.client.https-proxy=https-proxy", + "spring.cloud.kubernetes.client.proxy-username=proxy-username", + "spring.cloud.kubernetes.client.proxy-password=proxy-password", + "spring.cloud.kubernetes.client.oauth-token=oauth-token", + "spring.cloud.kubernetes.client.no-proxy[0]=a", "spring.cloud.kubernetes.client.no-proxy[1]=b", + "spring.cloud.kubernetes.client.service-account-namespace-path=path", + "spring.cloud.kubernetes.client.user-agent=user-agent") + .run(context -> { + KubernetesClientProperties properties = context.getBean(KubernetesClientProperties.class) + .withNamespace("non-default"); + assertThat(properties).isNotNull(); + assertThat(properties.trustCerts()).isTrue(); + assertThat(properties.masterUrl()).isEqualTo("master-url"); + assertThat(properties.apiVersion()).isEqualTo("1"); + assertThat(properties.namespace()).isEqualTo("non-default"); + assertThat(properties.caCertFile()).isEqualTo("ca-cert-file"); + assertThat(properties.caCertData()).isEqualTo("ca-cert-data"); + assertThat(properties.clientCertFile()).isEqualTo("client-cert-file"); + assertThat(properties.clientCertData()).isEqualTo("client-cert-data"); + assertThat(properties.clientKeyFile()).isEqualTo("client-key-file"); + assertThat(properties.clientKeyData()).isEqualTo("client-key-data"); + assertThat(properties.clientKeyAlgo()).isEqualTo("client-key-algo"); + assertThat(properties.clientKeyPassphrase()).isEqualTo("client-key-passphrase"); + assertThat(properties.username()).isEqualTo("username"); + assertThat(properties.password()).isEqualTo("password"); + assertThat(properties.watchReconnectInterval()).isEqualTo(Duration.ofMillis(200)); + assertThat(properties.watchReconnectLimit()).isEqualTo(Duration.ofMillis(300)); + assertThat(properties.connectionTimeout()).isEqualTo(Duration.ofMillis(400)); + assertThat(properties.requestTimeout()).isEqualTo(Duration.ofMillis(500)); + assertThat(properties.rollingTimeout()).isEqualTo(Duration.ofMillis(600)); + assertThat(properties.loggingInterval()).isEqualTo(Duration.ofMillis(700)); + assertThat(properties.httpProxy()).isEqualTo("http-proxy"); + assertThat(properties.httpsProxy()).isEqualTo("https-proxy"); + assertThat(properties.proxyUsername()).isEqualTo("proxy-username"); + assertThat(properties.proxyPassword()).isEqualTo("proxy-password"); + assertThat(properties.oauthToken()).isEqualTo("oauth-token"); + assertThat(properties.noProxy().length).isEqualTo(2); + assertThat(properties.noProxy()[0]).isEqualTo("a"); + assertThat(properties.noProxy()[1]).isEqualTo("b"); + assertThat(properties.serviceAccountNamespacePath()).isEqualTo("path"); + assertThat(properties.userAgent()).isEqualTo("user-agent"); + }); } @EnableConfigurationProperties(KubernetesClientProperties.class) diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/KubernetesCommonsAutoConfigurationTests.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/KubernetesCommonsAutoConfigurationTests.java index 13477539b5..1d6fd99604 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/KubernetesCommonsAutoConfigurationTests.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/KubernetesCommonsAutoConfigurationTests.java @@ -38,8 +38,11 @@ class KubernetesCommonsAutoConfigurationTests { void beansAreCreated() { assertThat(context.getBeansOfType(KubernetesClientProperties.class)).hasSize(1); - KubernetesClientProperties properties = context.getBeansOfType(KubernetesClientProperties.class).values() - .stream().findFirst().get(); + KubernetesClientProperties properties = context.getBeansOfType(KubernetesClientProperties.class) + .values() + .stream() + .findFirst() + .get(); assertThat(properties.password()).isEqualTo("mypassword"); assertThat(properties.proxyPassword()).isEqualTo("myproxypassword"); } diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/KubernetesCommonsSanitizeAutoConfigurationTests.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/KubernetesCommonsSanitizeAutoConfigurationTests.java index b7dd4a6f7a..3ebeb78b75 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/KubernetesCommonsSanitizeAutoConfigurationTests.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/KubernetesCommonsSanitizeAutoConfigurationTests.java @@ -34,25 +34,25 @@ class KubernetesCommonsSanitizeAutoConfigurationTests { @Test void sanitizeSecretsNotEnabled() { contextRunner(false, false) - .run(context -> assertThat(context.getBeansOfType(SanitizingFunction.class)).isEmpty()); + .run(context -> assertThat(context.getBeansOfType(SanitizingFunction.class)).isEmpty()); } @Test void sanitizeSecretsEnabled() { contextRunner(true, false) - .run(context -> assertThat(context.getBeansOfType(SanitizingFunction.class)).hasSize(1)); + .run(context -> assertThat(context.getBeansOfType(SanitizingFunction.class)).hasSize(1)); } @Test void sanitizeSecretsEnabledSanitizedClassNotPresent() { contextRunner(true, true) - .run(context -> assertThat(context.getBeansOfType(SanitizingFunction.class)).isEmpty()); + .run(context -> assertThat(context.getBeansOfType(SanitizingFunction.class)).isEmpty()); } private ApplicationContextRunner contextRunner(boolean enableSanitizeSecrets, boolean filterSanitizedDataClass) { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(KubernetesCommonsSanitizeAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(KubernetesCommonsSanitizeAutoConfiguration.class)); if (enableSanitizeSecrets) { contextRunner = contextRunner.withPropertyValues(ConditionalOnSanitizeSecrets.VALUE + "=true"); diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/LazilyInstantiateTest.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/LazilyInstantiateTest.java index 7e38bb6423..3438a77341 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/LazilyInstantiateTest.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/LazilyInstantiateTest.java @@ -46,7 +46,7 @@ public void setUp(TestInfo testInfo) throws Exception { if (!testInfo.getTags().contains(TAG)) { // common setup when(this.mockSupplier.get()).thenReturn(SINGLETON) - .thenThrow(new RuntimeException("Supplier was called more than once!")); + .thenThrow(new RuntimeException("Supplier was called more than once!")); } } diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/SanitizeTests.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/SanitizeTests.java index ba87eac7c3..b28d2c7c9b 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/SanitizeTests.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/SanitizeTests.java @@ -42,7 +42,7 @@ class SanitizeTests { private static final boolean SHOW_UNSANITIZED = true; private static final List SANITIZING_FUNCTIONS = List - .of(new KubernetesCommonsSanitizeAutoConfiguration().secretsPropertySourceSanitizingFunction()); + .of(new KubernetesCommonsSanitizeAutoConfiguration().secretsPropertySourceSanitizingFunction()); @Test void bootstrapPropertySourceNotSecrets() { @@ -108,7 +108,7 @@ void compositeOneSecretOneMount() { compositePropertySource.addFirstPropertySource( new SecretsPropertySource(new SourceData("secret-source", Map.of("secret", "xyz")))); compositePropertySource - .addFirstPropertySource(new MountConfigMapPropertySource("mount-source", Map.of("mount", "abc"))); + .addFirstPropertySource(new MountConfigMapPropertySource("mount-source", Map.of("mount", "abc"))); Sanitizer sanitizer = new Sanitizer(SANITIZING_FUNCTIONS); SanitizableData sanitizableDataSecret = new SanitizableData(compositePropertySource, "secret", "xyz"); diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/ConfigMapConfigPropertiesBindingTests.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/ConfigMapConfigPropertiesBindingTests.java index 526b70a98a..bab1e9d20d 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/ConfigMapConfigPropertiesBindingTests.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/ConfigMapConfigPropertiesBindingTests.java @@ -58,60 +58,63 @@ void testWithDefaults() { @Test void testWithNonDefaults() { - new ApplicationContextRunner().withUserConfiguration(Config.class).withPropertyValues( - "spring.cloud.kubernetes.config.enableApi=false", "spring.cloud.kubernetes.config.paths[0]=a", - "spring.cloud.kubernetes.config.paths[1]=b", "spring.cloud.kubernetes.config.sources[0].name=source-a", - "spring.cloud.kubernetes.config.sources[0].namespace=source-namespace-a", - "spring.cloud.kubernetes.config.sources[0].labels.key=source-value", - "spring.cloud.kubernetes.config.sources[0].explicit-prefix=source-prefix", - "spring.cloud.kubernetes.config.sources[0].use-name-as-prefix=true", - "spring.cloud.kubernetes.config.sources[0].include-profile-specific-sources=true", - "spring.cloud.kubernetes.config.labels.label-a=label-a", "spring.cloud.kubernetes.config.enabled=false", - "spring.cloud.kubernetes.config.name=name", "spring.cloud.kubernetes.config.namespace=namespace", - "spring.cloud.kubernetes.config.use-name-as-prefix=true", - "spring.cloud.kubernetes.config.include-profile-specific-sources=true", - "spring.cloud.kubernetes.config.fail-fast=true", - "spring.cloud.kubernetes.config.retry.initial-interval=1", - "spring.cloud.kubernetes.config.retry.multiplier=1.2", - "spring.cloud.kubernetes.config.retry.max-interval=3", - "spring.cloud.kubernetes.config.retry.max-attempts=4", - "spring.cloud.kubernetes.config.retry.enabled=false").run(context -> { - ConfigMapConfigProperties props = context.getBean(ConfigMapConfigProperties.class); - Assertions.assertNotNull(props); - Assertions.assertFalse(props.enableApi()); - - Assertions.assertEquals(props.paths().size(), 2); - Assertions.assertEquals(props.paths().get(0), "a"); - Assertions.assertEquals(props.paths().get(1), "b"); - - Assertions.assertEquals(props.sources().size(), 1); - ConfigMapConfigProperties.Source source = props.sources().get(0); - Assertions.assertEquals(source.name(), "source-a"); - Assertions.assertEquals(source.namespace(), "source-namespace-a"); - Assertions.assertEquals(source.labels().size(), 1); - Assertions.assertEquals(source.labels().get("key"), "source-value"); - Assertions.assertEquals(source.explicitPrefix(), "source-prefix"); - Assertions.assertTrue(source.useNameAsPrefix()); - Assertions.assertTrue(source.includeProfileSpecificSources()); - - Assertions.assertEquals(props.labels().size(), 1); - Assertions.assertEquals(props.labels().get("label-a"), "label-a"); - - Assertions.assertFalse(props.enabled()); - Assertions.assertEquals(props.name(), "name"); - Assertions.assertEquals(props.namespace(), "namespace"); - Assertions.assertTrue(props.useNameAsPrefix()); - Assertions.assertTrue(props.includeProfileSpecificSources()); - Assertions.assertTrue(props.failFast()); - - RetryProperties retryProperties = props.retry(); - Assertions.assertNotNull(retryProperties); - Assertions.assertEquals(retryProperties.initialInterval(), 1); - Assertions.assertEquals(retryProperties.multiplier(), 1.2); - Assertions.assertEquals(retryProperties.maxInterval(), 3); - Assertions.assertFalse(retryProperties.enabled()); - - }); + new ApplicationContextRunner().withUserConfiguration(Config.class) + .withPropertyValues("spring.cloud.kubernetes.config.enableApi=false", + "spring.cloud.kubernetes.config.paths[0]=a", "spring.cloud.kubernetes.config.paths[1]=b", + "spring.cloud.kubernetes.config.sources[0].name=source-a", + "spring.cloud.kubernetes.config.sources[0].namespace=source-namespace-a", + "spring.cloud.kubernetes.config.sources[0].labels.key=source-value", + "spring.cloud.kubernetes.config.sources[0].explicit-prefix=source-prefix", + "spring.cloud.kubernetes.config.sources[0].use-name-as-prefix=true", + "spring.cloud.kubernetes.config.sources[0].include-profile-specific-sources=true", + "spring.cloud.kubernetes.config.labels.label-a=label-a", + "spring.cloud.kubernetes.config.enabled=false", "spring.cloud.kubernetes.config.name=name", + "spring.cloud.kubernetes.config.namespace=namespace", + "spring.cloud.kubernetes.config.use-name-as-prefix=true", + "spring.cloud.kubernetes.config.include-profile-specific-sources=true", + "spring.cloud.kubernetes.config.fail-fast=true", + "spring.cloud.kubernetes.config.retry.initial-interval=1", + "spring.cloud.kubernetes.config.retry.multiplier=1.2", + "spring.cloud.kubernetes.config.retry.max-interval=3", + "spring.cloud.kubernetes.config.retry.max-attempts=4", + "spring.cloud.kubernetes.config.retry.enabled=false") + .run(context -> { + ConfigMapConfigProperties props = context.getBean(ConfigMapConfigProperties.class); + Assertions.assertNotNull(props); + Assertions.assertFalse(props.enableApi()); + + Assertions.assertEquals(props.paths().size(), 2); + Assertions.assertEquals(props.paths().get(0), "a"); + Assertions.assertEquals(props.paths().get(1), "b"); + + Assertions.assertEquals(props.sources().size(), 1); + ConfigMapConfigProperties.Source source = props.sources().get(0); + Assertions.assertEquals(source.name(), "source-a"); + Assertions.assertEquals(source.namespace(), "source-namespace-a"); + Assertions.assertEquals(source.labels().size(), 1); + Assertions.assertEquals(source.labels().get("key"), "source-value"); + Assertions.assertEquals(source.explicitPrefix(), "source-prefix"); + Assertions.assertTrue(source.useNameAsPrefix()); + Assertions.assertTrue(source.includeProfileSpecificSources()); + + Assertions.assertEquals(props.labels().size(), 1); + Assertions.assertEquals(props.labels().get("label-a"), "label-a"); + + Assertions.assertFalse(props.enabled()); + Assertions.assertEquals(props.name(), "name"); + Assertions.assertEquals(props.namespace(), "namespace"); + Assertions.assertTrue(props.useNameAsPrefix()); + Assertions.assertTrue(props.includeProfileSpecificSources()); + Assertions.assertTrue(props.failFast()); + + RetryProperties retryProperties = props.retry(); + Assertions.assertNotNull(retryProperties); + Assertions.assertEquals(retryProperties.initialInterval(), 1); + Assertions.assertEquals(retryProperties.multiplier(), 1.2); + Assertions.assertEquals(retryProperties.maxInterval(), 3); + Assertions.assertFalse(retryProperties.enabled()); + + }); } @Configuration diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/ConfigReloadPropertiesTests.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/ConfigReloadPropertiesTests.java index 9f4eae1bcc..e98d175ab4 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/ConfigReloadPropertiesTests.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/ConfigReloadPropertiesTests.java @@ -53,26 +53,25 @@ void testDefaults() { @Test void testNonDefaults() { new ApplicationContextRunner().withUserConfiguration(Config.class) - .withPropertyValues("spring.cloud.kubernetes.reload.enabled=true", - "spring.cloud.kubernetes.reload.monitoring-config-maps=false", - "spring.cloud.kubernetes.reload.monitoring-secrets=true", - "spring.cloud.kubernetes.reload.strategy=SHUTDOWN", - "spring.cloud.kubernetes.reload.mode=POLLING", "spring.cloud.kubernetes.reload.period=1000ms", - "spring.cloud.kubernetes.reload.namespaces[0]=a", - "spring.cloud.kubernetes.reload.namespaces[1]=b", - "spring.cloud.kubernetes.reload.max-wait-for-restart=5s") - .run(context -> { - ConfigReloadProperties properties = context.getBean(ConfigReloadProperties.class); - Assertions.assertNotNull(properties); - Assertions.assertTrue(properties.enabled()); - Assertions.assertFalse(properties.monitoringConfigMaps()); - Assertions.assertTrue(properties.monitoringSecrets()); - Assertions.assertEquals(ConfigReloadProperties.ReloadStrategy.SHUTDOWN, properties.strategy()); - Assertions.assertEquals(ConfigReloadProperties.ReloadDetectionMode.POLLING, properties.mode()); - Assertions.assertEquals(Duration.ofMillis(1000), properties.period()); - Assertions.assertEquals(Set.of("a", "b"), properties.namespaces()); - Assertions.assertEquals(Duration.ofSeconds(5), properties.maxWaitForRestart()); - }); + .withPropertyValues("spring.cloud.kubernetes.reload.enabled=true", + "spring.cloud.kubernetes.reload.monitoring-config-maps=false", + "spring.cloud.kubernetes.reload.monitoring-secrets=true", + "spring.cloud.kubernetes.reload.strategy=SHUTDOWN", "spring.cloud.kubernetes.reload.mode=POLLING", + "spring.cloud.kubernetes.reload.period=1000ms", "spring.cloud.kubernetes.reload.namespaces[0]=a", + "spring.cloud.kubernetes.reload.namespaces[1]=b", + "spring.cloud.kubernetes.reload.max-wait-for-restart=5s") + .run(context -> { + ConfigReloadProperties properties = context.getBean(ConfigReloadProperties.class); + Assertions.assertNotNull(properties); + Assertions.assertTrue(properties.enabled()); + Assertions.assertFalse(properties.monitoringConfigMaps()); + Assertions.assertTrue(properties.monitoringSecrets()); + Assertions.assertEquals(ConfigReloadProperties.ReloadStrategy.SHUTDOWN, properties.strategy()); + Assertions.assertEquals(ConfigReloadProperties.ReloadDetectionMode.POLLING, properties.mode()); + Assertions.assertEquals(Duration.ofMillis(1000), properties.period()); + Assertions.assertEquals(Set.of("a", "b"), properties.namespaces()); + Assertions.assertEquals(Duration.ofSeconds(5), properties.maxWaitForRestart()); + }); } @Configuration diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/ConfigUtilsProcessSourceTests.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/ConfigUtilsProcessSourceTests.java index 90a14ec7d1..59295d6d93 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/ConfigUtilsProcessSourceTests.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/ConfigUtilsProcessSourceTests.java @@ -70,7 +70,7 @@ void testProcessSourceOne() { @Test void testProcessNamedDataOne() { List strippedSources = List - .of(new StrippedSourceContainer(Map.of(), "configmap-a", Map.of("one", "1"))); + .of(new StrippedSourceContainer(Map.of(), "configmap-a", Map.of("one", "1"))); Environment environment = new MockEnvironment(); LinkedHashSet sourceNames = new LinkedHashSet<>(List.of("configmap-a")); String namespace = "namespace-a"; @@ -148,7 +148,7 @@ void testProcessNamedDataTwo(CapturedOutput output) { // @formatter:on String sourceName = "account"; List strippedSources = List - .of(new StrippedSourceContainer(Map.of(), sourceName, sourceRawData)); + .of(new StrippedSourceContainer(Map.of(), sourceName, sourceRawData)); MockEnvironment environment = new MockEnvironment().withProperty("spring.application.name", sourceName); environment.setActiveProfiles("default"); LinkedHashSet sourceNames = new LinkedHashSet<>(List.of(sourceName)); @@ -241,7 +241,7 @@ void testProcessNamedDataThree(CapturedOutput output) { // @formatter:on String sourceName = "account-default"; List strippedSources = List - .of(new StrippedSourceContainer(Map.of(), sourceName, sourceRawData)); + .of(new StrippedSourceContainer(Map.of(), sourceName, sourceRawData)); MockEnvironment environment = new MockEnvironment().withProperty("spring.application.name", "account"); environment.setActiveProfiles("default"); LinkedHashSet sourceNames = new LinkedHashSet<>(List.of(sourceName)); @@ -353,7 +353,7 @@ void testProcessNamedDataFive(CapturedOutput output) { // @formatter:on String sourceName = "account"; List strippedSources = List - .of(new StrippedSourceContainer(Map.of(), sourceName, sourceRawData)); + .of(new StrippedSourceContainer(Map.of(), sourceName, sourceRawData)); MockEnvironment environment = new MockEnvironment().withProperty("spring.application.name", sourceName); environment.setActiveProfiles("k8s"); LinkedHashSet sourceNames = new LinkedHashSet<>(List.of(sourceName)); @@ -441,7 +441,7 @@ void testProcessNamedDataSix(CapturedOutput output) { // @formatter:on String sourceName = "account-k8s"; List strippedSources = List - .of(new StrippedSourceContainer(Map.of(), sourceName, sourceRawData)); + .of(new StrippedSourceContainer(Map.of(), sourceName, sourceRawData)); MockEnvironment environment = new MockEnvironment().withProperty("spring.application.name", "account"); environment.setActiveProfiles("k8s"); LinkedHashSet sourceNames = new LinkedHashSet<>(List.of(sourceName)); diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/ConfigUtilsTests.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/ConfigUtilsTests.java index 54f30c5cb8..53fd0afb3f 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/ConfigUtilsTests.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/ConfigUtilsTests.java @@ -185,7 +185,7 @@ void testMerge() { Map.of("application.yaml", "propA: AA\npropC: C")); LinkedHashSet sourceNames = Stream.of("configmap-one", "configmap-one-kubernetes") - .collect(Collectors.toCollection(LinkedHashSet::new)); + .collect(Collectors.toCollection(LinkedHashSet::new)); MultipleSourcesContainer result = ConfigUtils.processNamedData(List.of(configMapOne, configMapOneK8s), new MockEnvironment(), sourceNames, "default", false); diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/KubernetesConfigDataLocationResolverTests.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/KubernetesConfigDataLocationResolverTests.java index 3bad5ad2bf..e830ac4a08 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/KubernetesConfigDataLocationResolverTests.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/KubernetesConfigDataLocationResolverTests.java @@ -54,7 +54,7 @@ protected void registerBeans(ConfigDataLocationResolverContext resolverContext, }; private static final ConfigDataLocationResolverContext RESOLVER_CONTEXT = Mockito - .mock(ConfigDataLocationResolverContext.class); + .mock(ConfigDataLocationResolverContext.class); @Test void testGetPrefix() { @@ -192,11 +192,11 @@ void testResolveProfileSpecificThree() { NOOP_RESOLVER.resolveProfileSpecific(RESOLVER_CONTEXT, configDataLocation, profiles); KubernetesClientProperties kubernetesClientProperties = RESOLVER_CONTEXT.getBootstrapContext() - .get(KubernetesClientProperties.class); + .get(KubernetesClientProperties.class); ConfigMapConfigProperties configMapConfigProperties = RESOLVER_CONTEXT.getBootstrapContext() - .get(ConfigMapConfigProperties.class); + .get(ConfigMapConfigProperties.class); SecretsConfigProperties secretsConfigProperties = RESOLVER_CONTEXT.getBootstrapContext() - .get(SecretsConfigProperties.class); + .get(SecretsConfigProperties.class); Assertions.assertNotNull(kubernetesClientProperties); Assertions.assertNotNull(configMapConfigProperties); @@ -231,11 +231,11 @@ void testResolveProfileSpecificFour() { null, false, false, false, null); KubernetesClientProperties kubernetesClientProperties = RESOLVER_CONTEXT.getBootstrapContext() - .get(KubernetesClientProperties.class); + .get(KubernetesClientProperties.class); ConfigMapConfigProperties configMapConfigProperties = RESOLVER_CONTEXT.getBootstrapContext() - .getOrElse(ConfigMapConfigProperties.class, one); + .getOrElse(ConfigMapConfigProperties.class, one); SecretsConfigProperties secretsConfigProperties = RESOLVER_CONTEXT.getBootstrapContext() - .getOrElse(SecretsConfigProperties.class, two); + .getOrElse(SecretsConfigProperties.class, two); Assertions.assertNotNull(kubernetesClientProperties); Assertions.assertSame(one, configMapConfigProperties); diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/SecretsConfigPropertiesBindingTests.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/SecretsConfigPropertiesBindingTests.java index 45918b702d..0e390eabde 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/SecretsConfigPropertiesBindingTests.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/SecretsConfigPropertiesBindingTests.java @@ -59,62 +59,62 @@ void testWithDefaults() { @Test void testWithNonDefaults() { new ApplicationContextRunner().withUserConfiguration(Config.class) - .withPropertyValues("spring.cloud.kubernetes.secrets.enableApi=false", - "spring.cloud.kubernetes.secrets.paths[0]=a", "spring.cloud.kubernetes.secrets.paths[1]=b", - "spring.cloud.kubernetes.secrets.sources[0].name=source-a", - "spring.cloud.kubernetes.secrets.sources[0].namespace=source-namespace-a", - "spring.cloud.kubernetes.secrets.sources[0].labels.key=source-value", - "spring.cloud.kubernetes.secrets.sources[0].explicit-prefix=source-prefix", - "spring.cloud.kubernetes.secrets.sources[0].use-name-as-prefix=true", - "spring.cloud.kubernetes.secrets.sources[0].include-profile-specific-sources=true", - "spring.cloud.kubernetes.secrets.labels.label-a=label-a", - "spring.cloud.kubernetes.secrets.enabled=false", "spring.cloud.kubernetes.secrets.name=name", - "spring.cloud.kubernetes.secrets.namespace=namespace", - "spring.cloud.kubernetes.secrets.use-name-as-prefix=true", - "spring.cloud.kubernetes.secrets.include-profile-specific-sources=true", - "spring.cloud.kubernetes.secrets.fail-fast=true", - "spring.cloud.kubernetes.secrets.retry.initial-interval=1", - "spring.cloud.kubernetes.secrets.retry.multiplier=1.2", - "spring.cloud.kubernetes.secrets.retry.max-interval=3", - "spring.cloud.kubernetes.secrets.retry.max-attempts=4", - "spring.cloud.kubernetes.secrets.retry.enabled=false") - .run(context -> { - SecretsConfigProperties props = context.getBean(SecretsConfigProperties.class); - Assertions.assertNotNull(props); - Assertions.assertFalse(props.enableApi()); - - Assertions.assertEquals(props.paths().size(), 2); - Assertions.assertEquals(props.paths().get(0), "a"); - Assertions.assertEquals(props.paths().get(1), "b"); - - Assertions.assertEquals(props.sources().size(), 1); - SecretsConfigProperties.Source source = props.sources().get(0); - Assertions.assertEquals(source.name(), "source-a"); - Assertions.assertEquals(source.namespace(), "source-namespace-a"); - Assertions.assertEquals(source.labels().size(), 1); - Assertions.assertEquals(source.labels().get("key"), "source-value"); - Assertions.assertEquals(source.explicitPrefix(), "source-prefix"); - Assertions.assertTrue(source.useNameAsPrefix()); - Assertions.assertTrue(source.includeProfileSpecificSources()); - - Assertions.assertEquals(props.labels().size(), 1); - Assertions.assertEquals(props.labels().get("label-a"), "label-a"); - - Assertions.assertFalse(props.enabled()); - Assertions.assertEquals(props.name(), "name"); - Assertions.assertEquals(props.namespace(), "namespace"); - Assertions.assertTrue(props.useNameAsPrefix()); - Assertions.assertTrue(props.includeProfileSpecificSources()); - Assertions.assertTrue(props.failFast()); - - RetryProperties retryProperties = props.retry(); - Assertions.assertNotNull(retryProperties); - Assertions.assertEquals(retryProperties.initialInterval(), 1); - Assertions.assertEquals(retryProperties.multiplier(), 1.2); - Assertions.assertEquals(retryProperties.maxInterval(), 3); - Assertions.assertFalse(retryProperties.enabled()); - - }); + .withPropertyValues("spring.cloud.kubernetes.secrets.enableApi=false", + "spring.cloud.kubernetes.secrets.paths[0]=a", "spring.cloud.kubernetes.secrets.paths[1]=b", + "spring.cloud.kubernetes.secrets.sources[0].name=source-a", + "spring.cloud.kubernetes.secrets.sources[0].namespace=source-namespace-a", + "spring.cloud.kubernetes.secrets.sources[0].labels.key=source-value", + "spring.cloud.kubernetes.secrets.sources[0].explicit-prefix=source-prefix", + "spring.cloud.kubernetes.secrets.sources[0].use-name-as-prefix=true", + "spring.cloud.kubernetes.secrets.sources[0].include-profile-specific-sources=true", + "spring.cloud.kubernetes.secrets.labels.label-a=label-a", + "spring.cloud.kubernetes.secrets.enabled=false", "spring.cloud.kubernetes.secrets.name=name", + "spring.cloud.kubernetes.secrets.namespace=namespace", + "spring.cloud.kubernetes.secrets.use-name-as-prefix=true", + "spring.cloud.kubernetes.secrets.include-profile-specific-sources=true", + "spring.cloud.kubernetes.secrets.fail-fast=true", + "spring.cloud.kubernetes.secrets.retry.initial-interval=1", + "spring.cloud.kubernetes.secrets.retry.multiplier=1.2", + "spring.cloud.kubernetes.secrets.retry.max-interval=3", + "spring.cloud.kubernetes.secrets.retry.max-attempts=4", + "spring.cloud.kubernetes.secrets.retry.enabled=false") + .run(context -> { + SecretsConfigProperties props = context.getBean(SecretsConfigProperties.class); + Assertions.assertNotNull(props); + Assertions.assertFalse(props.enableApi()); + + Assertions.assertEquals(props.paths().size(), 2); + Assertions.assertEquals(props.paths().get(0), "a"); + Assertions.assertEquals(props.paths().get(1), "b"); + + Assertions.assertEquals(props.sources().size(), 1); + SecretsConfigProperties.Source source = props.sources().get(0); + Assertions.assertEquals(source.name(), "source-a"); + Assertions.assertEquals(source.namespace(), "source-namespace-a"); + Assertions.assertEquals(source.labels().size(), 1); + Assertions.assertEquals(source.labels().get("key"), "source-value"); + Assertions.assertEquals(source.explicitPrefix(), "source-prefix"); + Assertions.assertTrue(source.useNameAsPrefix()); + Assertions.assertTrue(source.includeProfileSpecificSources()); + + Assertions.assertEquals(props.labels().size(), 1); + Assertions.assertEquals(props.labels().get("label-a"), "label-a"); + + Assertions.assertFalse(props.enabled()); + Assertions.assertEquals(props.name(), "name"); + Assertions.assertEquals(props.namespace(), "namespace"); + Assertions.assertTrue(props.useNameAsPrefix()); + Assertions.assertTrue(props.includeProfileSpecificSources()); + Assertions.assertTrue(props.failFast()); + + RetryProperties retryProperties = props.retry(); + Assertions.assertNotNull(retryProperties); + Assertions.assertEquals(retryProperties.initialInterval(), 1); + Assertions.assertEquals(retryProperties.multiplier(), 1.2); + Assertions.assertEquals(retryProperties.maxInterval(), 3); + Assertions.assertFalse(retryProperties.enabled()); + + }); } @Configuration diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/bootstrap/ConfigAndSecretsFailFastEnabledWithDefaultRetryConfiguration.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/bootstrap/ConfigAndSecretsFailFastEnabledWithDefaultRetryConfiguration.java index a9d8755d4b..a3bfb7fb3b 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/bootstrap/ConfigAndSecretsFailFastEnabledWithDefaultRetryConfiguration.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/bootstrap/ConfigAndSecretsFailFastEnabledWithDefaultRetryConfiguration.java @@ -52,7 +52,7 @@ class ConfigAndSecretsFailFastEnabledWithDefaultRetryConfiguration { @Test void shouldDefineRequiredBeans() { Map retryInterceptors = context - .getBeansOfType(RetryOperationsInterceptor.class); + .getBeansOfType(RetryOperationsInterceptor.class); assertThat(retryInterceptors.containsKey("kubernetesConfigRetryInterceptor")).isTrue(); assertThat(retryInterceptors.containsKey("kubernetesSecretsRetryInterceptor")).isTrue(); } diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/bootstrap/ConfigFailFastEnabled.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/bootstrap/ConfigFailFastEnabled.java index 9efbfcd836..5143ec5783 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/bootstrap/ConfigFailFastEnabled.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/bootstrap/ConfigFailFastEnabled.java @@ -47,7 +47,7 @@ class ConfigFailFastEnabled { @Test void shouldDefineRequiredBeans() { Map retryInterceptors = context - .getBeansOfType(RetryOperationsInterceptor.class); + .getBeansOfType(RetryOperationsInterceptor.class); assertThat(retryInterceptors.containsKey("kubernetesConfigRetryInterceptor")).isTrue(); assertThat(retryInterceptors.containsKey("kubernetesSecretsRetryInterceptor")).isTrue(); } diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/bootstrap/FailFastEnabledWithoutSpringRetryOnClasspath.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/bootstrap/FailFastEnabledWithoutSpringRetryOnClasspath.java index db9ef814dc..00d42188f6 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/bootstrap/FailFastEnabledWithoutSpringRetryOnClasspath.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/bootstrap/FailFastEnabledWithoutSpringRetryOnClasspath.java @@ -35,27 +35,27 @@ class FailFastEnabledWithoutSpringRetryOnClasspath { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(KubernetesBootstrapConfiguration.class)) - .withClassLoader(new FilteredClassLoader(Retryable.class, Aspect.class, AopAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(KubernetesBootstrapConfiguration.class)) + .withClassLoader(new FilteredClassLoader(Retryable.class, Aspect.class, AopAutoConfiguration.class)); @Test void shouldNotDefineRetryBeansWhenConfigMapFailFastEnabled() { contextRunner.withPropertyValues("spring.cloud.kubernetes.config.fail-fast=true") - .run(context -> assertThat(context.getBeansOfType(RetryOperationsInterceptor.class)).isEmpty()); + .run(context -> assertThat(context.getBeansOfType(RetryOperationsInterceptor.class)).isEmpty()); } @Test void shouldNotDefineRetryBeansWhenSecretsFailFastEnabled() { contextRunner.withPropertyValues("spring.cloud.kubernetes.secrets.fail-fast=true") - .run(context -> assertThat(context.getBeansOfType(RetryOperationsInterceptor.class)).isEmpty()); + .run(context -> assertThat(context.getBeansOfType(RetryOperationsInterceptor.class)).isEmpty()); } @Test void shouldNotDefineRetryBeansWhenConfigMapAndSecretsFailFastEnabled() { contextRunner - .withPropertyValues("spring.cloud.kubernetes.config.fail-fast=true", - "spring.cloud.kubernetes.secrets.fail-fast=true") - .run(context -> assertThat(context.getBeansOfType(RetryOperationsInterceptor.class)).isEmpty()); + .withPropertyValues("spring.cloud.kubernetes.config.fail-fast=true", + "spring.cloud.kubernetes.secrets.fail-fast=true") + .run(context -> assertThat(context.getBeansOfType(RetryOperationsInterceptor.class)).isEmpty()); } } diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/bootstrap/SecretsFailFastEnabled.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/bootstrap/SecretsFailFastEnabled.java index 8263961c27..4bc31a57a3 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/bootstrap/SecretsFailFastEnabled.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/config/bootstrap/SecretsFailFastEnabled.java @@ -47,7 +47,7 @@ class SecretsFailFastEnabled { @Test void shouldDefineRequiredBeans() { Map retryInterceptors = context - .getBeansOfType(RetryOperationsInterceptor.class); + .getBeansOfType(RetryOperationsInterceptor.class); assertThat(retryInterceptors.containsKey("kubernetesConfigRetryInterceptor")).isTrue(); assertThat(retryInterceptors.containsKey("kubernetesSecretsRetryInterceptor")).isTrue(); } diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/DiscoveryClientUtilsTests.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/DiscoveryClientUtilsTests.java index e2b402e404..2c16ced061 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/DiscoveryClientUtilsTests.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/DiscoveryClientUtilsTests.java @@ -213,7 +213,7 @@ void testServiceMetadataAddAnnotationsNoPrefix(CapturedOutput output) { Assertions.assertEquals(result.size(), 3); Assertions.assertEquals(result, Map.of("aa", "bb", "k8s_namespace", "default", "type", "ClusterIP")); Assertions - .assertTrue(output.getOut().contains("Adding annotations metadata: {aa=bb} for serviceId: my-service")); + .assertTrue(output.getOut().contains("Adding annotations metadata: {aa=bb} for serviceId: my-service")); } /** @@ -287,12 +287,18 @@ void testServiceMetadataAddLabelsAndAnnotationsWithPrefix(CapturedOutput output) Assertions.assertEquals(result, Map.of("annotation-aa", "bb", "annotation-cc", "dd", "label-a", "b", "label-c", "d", "k8s_namespace", "default", "type", "ClusterIP")); // so that result is deterministic in assertion - String labels = result.entrySet().stream().filter(en -> en.getKey().contains("label")) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)).toString(); - String annotations = result.entrySet().stream().filter(en -> en.getKey().contains("annotation")) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)).toString(); - Assertions.assertTrue( - output.getOut().contains("Adding labels metadata: " + labels + " for serviceId: my-service")); + String labels = result.entrySet() + .stream() + .filter(en -> en.getKey().contains("label")) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) + .toString(); + String annotations = result.entrySet() + .stream() + .filter(en -> en.getKey().contains("annotation")) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) + .toString(); + Assertions + .assertTrue(output.getOut().contains("Adding labels metadata: " + labels + " for serviceId: my-service")); Assertions.assertTrue( output.getOut().contains("Adding annotations metadata: " + annotations + " for serviceId: my-service")); } @@ -328,7 +334,7 @@ void testServiceMetadataAddPortsWithoutPrefix(CapturedOutput output) { Assertions.assertEquals(result.size(), 3); Assertions.assertEquals(result, Map.of("https", "8080", "k8s_namespace", "default", "type", "ClusterIP")); Assertions - .assertTrue(output.getOut().contains("Adding port metadata: {https=8080} for serviceId : my-service")); + .assertTrue(output.getOut().contains("Adding port metadata: {https=8080} for serviceId : my-service")); } /** @@ -363,7 +369,7 @@ void testServiceMetadataAddPortsWithPrefix(CapturedOutput output) { Assertions.assertEquals(result, Map.of("prefix-https", "8080", "prefix-http", "8081", "k8s_namespace", "default", "type", "ClusterIP")); Assertions.assertTrue(output.getOut() - .contains("Adding port metadata: {prefix-http=8081, prefix-https=8080} for serviceId : my-service")); + .contains("Adding port metadata: {prefix-http=8081, prefix-https=8080} for serviceId : my-service")); } /** @@ -382,8 +388,9 @@ void testPrimaryPortNameNotFound(CapturedOutput output) { String result = primaryPortName(properties, serviceLabels, "abc"); Assertions.assertNull(result); - Assertions.assertTrue(output.getOut().contains( - "did not find a primary-port-name in neither properties nor service labels for service with ID : abc")); + Assertions.assertTrue(output.getOut() + .contains( + "did not find a primary-port-name in neither properties nor service labels for service with ID : abc")); } /** @@ -512,10 +519,11 @@ void testEndpointsPortNullPrimaryPortName(CapturedOutput output) { ServicePortNameAndNumber portData = endpointsPort(endpointsPorts, serviceMetadata, properties); Assertions.assertEquals(portData.portNumber(), 8080); Assertions.assertEquals(portData.portName(), "not-null"); - Assertions.assertTrue(output.getOut().contains( - "did not find a primary-port-name in neither properties nor service labels for service with ID : spring-k8s")); Assertions.assertTrue(output.getOut() - .contains("not found primary-port-name (with value: 'null') via properties or service labels")); + .contains( + "did not find a primary-port-name in neither properties nor service labels for service with ID : spring-k8s")); + Assertions.assertTrue(output.getOut() + .contains("not found primary-port-name (with value: 'null') via properties or service labels")); Assertions.assertTrue(output.getOut().contains("not found primary-port-name via 'https' to match port")); Assertions.assertTrue(output.getOut().contains("not found primary-port-name via 'http' to match port")); Assertions.assertTrue(output.getOut().contains(""" @@ -548,10 +556,10 @@ void testEndpointsPortPrimaryPortNameIsPresentButNotFound(CapturedOutput output) ServicePortNameAndNumber portData = endpointsPort(endpointsPorts, serviceMetadata, properties); Assertions.assertEquals(portData.portNumber(), 8080); Assertions.assertEquals(portData.portName(), "one"); - Assertions.assertTrue( - output.getOut().contains("will use primaryPortName : three for service with ID = spring-k8s")); + Assertions + .assertTrue(output.getOut().contains("will use primaryPortName : three for service with ID = spring-k8s")); Assertions.assertTrue(output.getOut() - .contains("not found primary-port-name (with value: 'three') via properties or service labels")); + .contains("not found primary-port-name (with value: 'three') via properties or service labels")); Assertions.assertTrue(output.getOut().contains("not found primary-port-name via 'https' to match port")); Assertions.assertTrue(output.getOut().contains("not found primary-port-name via 'http' to match port")); Assertions.assertTrue(output.getOut().contains(""" @@ -584,10 +592,11 @@ void testEndpointsPortPrimaryPortNameFound(CapturedOutput output) { ServicePortNameAndNumber portData = endpointsPort(endpointsPorts, serviceMetadata, properties); Assertions.assertEquals(portData.portNumber(), 8081); Assertions.assertEquals(portData.portName(), "two"); - Assertions.assertTrue( - output.getOut().contains("will use primaryPortName : two for service with ID = spring-k8s")); - Assertions.assertTrue(output.getOut().contains( - "found primary-port-name (with value: 'two') via properties or service labels to match port : 8081")); + Assertions + .assertTrue(output.getOut().contains("will use primaryPortName : two for service with ID = spring-k8s")); + Assertions.assertTrue(output.getOut() + .contains( + "found primary-port-name (with value: 'two') via properties or service labels to match port : 8081")); } /** @@ -615,10 +624,11 @@ void testEndpointsPortPrimaryPortHttps(CapturedOutput output) { ServicePortNameAndNumber portData = endpointsPort(endpointsPorts, serviceMetadata, properties); Assertions.assertEquals(portData.portNumber(), 8082); Assertions.assertEquals(portData.portName(), "https"); - Assertions.assertTrue( - output.getOut().contains("will use primaryPortName : three for service with ID = spring-k8s")); - Assertions.assertTrue(output.getOut().contains( - "not found primary-port-name (with value: 'three') via properties or service labels to match port")); + Assertions + .assertTrue(output.getOut().contains("will use primaryPortName : three for service with ID = spring-k8s")); + Assertions.assertTrue(output.getOut() + .contains( + "not found primary-port-name (with value: 'three') via properties or service labels to match port")); Assertions.assertTrue(output.getOut().contains("found primary-port-name via 'https' to match port : 8082")); } @@ -647,10 +657,11 @@ void testEndpointsPortPrimaryPortHttp(CapturedOutput output) { ServicePortNameAndNumber portData = endpointsPort(endpointsPorts, serviceMetadata, properties); Assertions.assertEquals(portData.portNumber(), 8082); Assertions.assertEquals(portData.portName(), "http"); - Assertions.assertTrue( - output.getOut().contains("will use primaryPortName : three for service with ID = spring-k8s")); - Assertions.assertTrue(output.getOut().contains( - "not found primary-port-name (with value: 'three') via properties or service labels to match port")); + Assertions + .assertTrue(output.getOut().contains("will use primaryPortName : three for service with ID = spring-k8s")); + Assertions.assertTrue(output.getOut() + .contains( + "not found primary-port-name (with value: 'three') via properties or service labels to match port")); Assertions.assertTrue(output.getOut().contains("found primary-port-name via 'http' to match port : 8082")); } @@ -937,9 +948,12 @@ void testPodMetadataBothLabelsAndAnnotations(CapturedOutput output) { } private String filterOnK8sNamespaceAndType(Map result) { - return result.entrySet().stream().filter(en -> !en.getKey().contains("k8s_namespace")) - .filter(en -> !en.getKey().equals("type")) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)).toString(); + return result.entrySet() + .stream() + .filter(en -> !en.getKey().contains("k8s_namespace")) + .filter(en -> !en.getKey().equals("type")) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) + .toString(); } } diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/KubernetesDiscoveryClientHealthIndicatorInitializerTests.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/KubernetesDiscoveryClientHealthIndicatorInitializerTests.java index ab7dd8299a..51ebe45afe 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/KubernetesDiscoveryClientHealthIndicatorInitializerTests.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/KubernetesDiscoveryClientHealthIndicatorInitializerTests.java @@ -57,14 +57,15 @@ void afterEach() { @SuppressWarnings("unchecked") void testInstanceRegistrationEventPublishedWhenInsideK8s() { new ApplicationContextRunner() - .withUserConfiguration(InstanceRegistrationEventPublishedInsideK8sConfiguration.class) - .run(context -> assertThat(context).hasSingleBean(PodUtils.class)); + .withUserConfiguration(InstanceRegistrationEventPublishedInsideK8sConfiguration.class) + .run(context -> assertThat(context).hasSingleBean(PodUtils.class)); ArgumentCaptor> captor = ArgumentCaptor - .forClass(InstanceRegisteredEvent.class); + .forClass(InstanceRegisteredEvent.class); Mockito.verify(publisher, Mockito.times(1)).publishEvent(captor.capture()); KubernetesDiscoveryClientHealthIndicatorInitializer.RegisteredEventSource source = (KubernetesDiscoveryClientHealthIndicatorInitializer.RegisteredEventSource) captor - .getValue().getSource(); + .getValue() + .getSource(); assertThat(source.cloudPlatform()).isEqualTo("kubernetes"); assertThat(source.inside()).isTrue(); assertThat(source.pod()).isSameAs(POD); @@ -75,14 +76,15 @@ void testInstanceRegistrationEventPublishedWhenInsideK8s() { @SuppressWarnings("unchecked") void testInstanceRegistrationEventPublishedWhenOutsideK8s() { new ApplicationContextRunner() - .withUserConfiguration(InstanceRegistrationEventPublishedOutsideK8sConfiguration.class) - .run(context -> assertThat(context).hasSingleBean(PodUtils.class)); + .withUserConfiguration(InstanceRegistrationEventPublishedOutsideK8sConfiguration.class) + .run(context -> assertThat(context).hasSingleBean(PodUtils.class)); ArgumentCaptor> captor = ArgumentCaptor - .forClass(InstanceRegisteredEvent.class); + .forClass(InstanceRegisteredEvent.class); Mockito.verify(publisher, Mockito.times(1)).publishEvent(captor.capture()); KubernetesDiscoveryClientHealthIndicatorInitializer.RegisteredEventSource source = (KubernetesDiscoveryClientHealthIndicatorInitializer.RegisteredEventSource) captor - .getValue().getSource(); + .getValue() + .getSource(); assertThat(source.cloudPlatform()).isEqualTo("kubernetes"); assertThat(source.inside()).isFalse(); assertThat(source.pod()).isNotNull(); diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/KubernetesDiscoveryPropertiesMetadataTests.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/KubernetesDiscoveryPropertiesMetadataTests.java index a5d645d5ed..223daf143c 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/KubernetesDiscoveryPropertiesMetadataTests.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/KubernetesDiscoveryPropertiesMetadataTests.java @@ -46,18 +46,18 @@ void testDefaultConstructor() { @Test void testSpringBindingFields() { new ApplicationContextRunner().withUserConfiguration(Config.class) - .withPropertyValues("spring.cloud.kubernetes.discovery.metadata.labelsPrefix=labelsPrefix", - "spring.cloud.kubernetes.discovery.metadata.add-pod-annotations=true", - "spring.cloud.kubernetes.discovery.metadata.add-pod-labels=true") - .run(context -> { - KubernetesDiscoveryProperties props = context.getBean(KubernetesDiscoveryProperties.class); - assertThat(props).isNotNull(); - assertThat(props.metadata().labelsPrefix()).isEqualTo("labelsPrefix"); - assertThat(props.metadata().addPorts()).isTrue(); - assertThat(props.metadata().portsPrefix()).isEqualTo("port."); - assertThat(props.metadata().addPodLabels()).isTrue(); - assertThat(props.metadata().addPodAnnotations()).isTrue(); - }); + .withPropertyValues("spring.cloud.kubernetes.discovery.metadata.labelsPrefix=labelsPrefix", + "spring.cloud.kubernetes.discovery.metadata.add-pod-annotations=true", + "spring.cloud.kubernetes.discovery.metadata.add-pod-labels=true") + .run(context -> { + KubernetesDiscoveryProperties props = context.getBean(KubernetesDiscoveryProperties.class); + assertThat(props).isNotNull(); + assertThat(props.metadata().labelsPrefix()).isEqualTo("labelsPrefix"); + assertThat(props.metadata().addPorts()).isTrue(); + assertThat(props.metadata().portsPrefix()).isEqualTo("port."); + assertThat(props.metadata().addPodLabels()).isTrue(); + assertThat(props.metadata().addPodAnnotations()).isTrue(); + }); } @Configuration diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/KubernetesDiscoveryPropertiesTests.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/KubernetesDiscoveryPropertiesTests.java index 74e9f5e54e..8d6d8f3df0 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/KubernetesDiscoveryPropertiesTests.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/KubernetesDiscoveryPropertiesTests.java @@ -34,76 +34,77 @@ class KubernetesDiscoveryPropertiesTests { @Test void testBindingWhenNoPropertiesProvided() { new ApplicationContextRunner().withUserConfiguration(KubernetesDiscoveryPropertiesMetadataTests.Config.class) - .run(context -> { - KubernetesDiscoveryProperties props = context.getBean(KubernetesDiscoveryProperties.class); - assertThat(props).isNotNull(); - assertThat(props.metadata().labelsPrefix()).isNull(); - assertThat(props.metadata().addPorts()).isTrue(); - assertThat(props.metadata().portsPrefix()).isEqualTo("port."); + .run(context -> { + KubernetesDiscoveryProperties props = context.getBean(KubernetesDiscoveryProperties.class); + assertThat(props).isNotNull(); + assertThat(props.metadata().labelsPrefix()).isNull(); + assertThat(props.metadata().addPorts()).isTrue(); + assertThat(props.metadata().portsPrefix()).isEqualTo("port."); - assertThat(props.enabled()).isTrue(); - assertThat(props.allNamespaces()).isFalse(); - assertThat(props.namespaces()).isEmpty(); - assertThat(props.waitCacheReady()).isTrue(); - assertThat(props.cacheLoadingTimeoutSeconds()).isEqualTo(60); - assertThat(props.includeNotReadyAddresses()).isFalse(); - assertThat(props.filter()).isNull(); - assertThat(props.knownSecurePorts()).isEqualTo(Set.of(443, 8443)); - assertThat(props.serviceLabels()).isEmpty(); - assertThat(props.primaryPortName()).isNull(); - assertThat(props.order()).isZero(); - assertThat(props.useEndpointSlices()).isFalse(); - assertThat(props.includeExternalNameServices()).isFalse(); - assertThat(props.discoveryServerUrl()).isNull(); - }); + assertThat(props.enabled()).isTrue(); + assertThat(props.allNamespaces()).isFalse(); + assertThat(props.namespaces()).isEmpty(); + assertThat(props.waitCacheReady()).isTrue(); + assertThat(props.cacheLoadingTimeoutSeconds()).isEqualTo(60); + assertThat(props.includeNotReadyAddresses()).isFalse(); + assertThat(props.filter()).isNull(); + assertThat(props.knownSecurePorts()).isEqualTo(Set.of(443, 8443)); + assertThat(props.serviceLabels()).isEmpty(); + assertThat(props.primaryPortName()).isNull(); + assertThat(props.order()).isZero(); + assertThat(props.useEndpointSlices()).isFalse(); + assertThat(props.includeExternalNameServices()).isFalse(); + assertThat(props.discoveryServerUrl()).isNull(); + }); } @Test void testBindingWhenSomePropertiesProvided() { new ApplicationContextRunner().withUserConfiguration(KubernetesDiscoveryPropertiesMetadataTests.Config.class) - .withPropertyValues("spring.cloud.kubernetes.discovery.filter=some-filter", - "spring.cloud.kubernetes.discovery.knownSecurePorts[0]=222", - "spring.cloud.kubernetes.discovery.metadata.labelsPrefix=labelsPrefix", - "spring.cloud.kubernetes.discovery.use-endpoint-slices=true", - "spring.cloud.kubernetes.discovery.namespaces[0]=ns1", - "spring.cloud.kubernetes.discovery.namespaces[1]=ns2", - "spring.cloud.kubernetes.discovery.include-external-name-services=true", - "spring.cloud.kubernetes.discovery.discovery-server-url=http://example") - .run(context -> { - KubernetesDiscoveryProperties props = context.getBean(KubernetesDiscoveryProperties.class); - assertThat(props).isNotNull(); - assertThat(props.metadata().labelsPrefix()).isEqualTo("labelsPrefix"); - assertThat(props.metadata().addPorts()).isTrue(); - assertThat(props.metadata().portsPrefix()).isEqualTo("port."); + .withPropertyValues("spring.cloud.kubernetes.discovery.filter=some-filter", + "spring.cloud.kubernetes.discovery.knownSecurePorts[0]=222", + "spring.cloud.kubernetes.discovery.metadata.labelsPrefix=labelsPrefix", + "spring.cloud.kubernetes.discovery.use-endpoint-slices=true", + "spring.cloud.kubernetes.discovery.namespaces[0]=ns1", + "spring.cloud.kubernetes.discovery.namespaces[1]=ns2", + "spring.cloud.kubernetes.discovery.include-external-name-services=true", + "spring.cloud.kubernetes.discovery.discovery-server-url=http://example") + .run(context -> { + KubernetesDiscoveryProperties props = context.getBean(KubernetesDiscoveryProperties.class); + assertThat(props).isNotNull(); + assertThat(props.metadata().labelsPrefix()).isEqualTo("labelsPrefix"); + assertThat(props.metadata().addPorts()).isTrue(); + assertThat(props.metadata().portsPrefix()).isEqualTo("port."); - assertThat(props.enabled()).isTrue(); - assertThat(props.allNamespaces()).isFalse(); - assertThat(props.namespaces()).containsExactlyInAnyOrder("ns1", "ns2"); - assertThat(props.waitCacheReady()).isTrue(); - assertThat(props.cacheLoadingTimeoutSeconds()).isEqualTo(60); - assertThat(props.includeNotReadyAddresses()).isFalse(); - assertThat(props.filter()).isEqualTo("some-filter"); - assertThat(props.knownSecurePorts()).isEqualTo(Set.of(222)); - assertThat(props.serviceLabels()).isEmpty(); - assertThat(props.primaryPortName()).isNull(); - assertThat(props.order()).isZero(); - assertThat(props.useEndpointSlices()).isTrue(); - assertThat(props.includeExternalNameServices()).isTrue(); - assertThat(props.discoveryServerUrl()).isEqualTo("http://example"); - }); + assertThat(props.enabled()).isTrue(); + assertThat(props.allNamespaces()).isFalse(); + assertThat(props.namespaces()).containsExactlyInAnyOrder("ns1", "ns2"); + assertThat(props.waitCacheReady()).isTrue(); + assertThat(props.cacheLoadingTimeoutSeconds()).isEqualTo(60); + assertThat(props.includeNotReadyAddresses()).isFalse(); + assertThat(props.filter()).isEqualTo("some-filter"); + assertThat(props.knownSecurePorts()).isEqualTo(Set.of(222)); + assertThat(props.serviceLabels()).isEmpty(); + assertThat(props.primaryPortName()).isNull(); + assertThat(props.order()).isZero(); + assertThat(props.useEndpointSlices()).isTrue(); + assertThat(props.includeExternalNameServices()).isTrue(); + assertThat(props.discoveryServerUrl()).isEqualTo("http://example"); + }); } // when we do not specify metadata, @DefaultValue is going to be picked up @Test void metadataSetToNotNull() { new ApplicationContextRunner().withUserConfiguration(KubernetesDiscoveryPropertiesMetadataTests.Config.class) - .withPropertyValues("spring.cloud.kubernetes.discovery.filter=some-filter").run(context -> { - KubernetesDiscoveryProperties props = context.getBean(KubernetesDiscoveryProperties.class); - assertThat(props).isNotNull(); - assertThat(props.metadata().labelsPrefix()).isNull(); - assertThat(props.metadata().addPorts()).isTrue(); - assertThat(props.metadata().portsPrefix()).isEqualTo("port."); - }); + .withPropertyValues("spring.cloud.kubernetes.discovery.filter=some-filter") + .run(context -> { + KubernetesDiscoveryProperties props = context.getBean(KubernetesDiscoveryProperties.class); + assertThat(props).isNotNull(); + assertThat(props.metadata().labelsPrefix()).isNull(); + assertThat(props.metadata().addPorts()).isTrue(); + assertThat(props.metadata().portsPrefix()).isEqualTo("port."); + }); } @Configuration diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/KubernetesServiceInstanceTests.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/KubernetesServiceInstanceTests.java index 2e13e6e637..72d1d700ce 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/KubernetesServiceInstanceTests.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/KubernetesServiceInstanceTests.java @@ -82,7 +82,7 @@ void testThirdConstructor() { assertThat(instance.getNamespace()).isEqualTo("spring-k8s"); assertThat(instance.getCluster()).isEqualTo("cluster"); assertThat(instance.podMetadata()) - .isEqualTo(Map.of("labels", Map.of("a", "b"), "annotations", Map.of("c", "d"))); + .isEqualTo(Map.of("labels", Map.of("a", "b"), "annotations", Map.of("c", "d"))); } @Test diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/ServicePortSecureResolverTest.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/ServicePortSecureResolverTest.java index 7d94d04d0f..6a38edab0e 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/ServicePortSecureResolverTest.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/discovery/ServicePortSecureResolverTest.java @@ -61,17 +61,17 @@ void testPortNumbersOnly() { ServicePortSecureResolver secureResolver = new ServicePortSecureResolver(properties); assertThat(secureResolver - .resolve(new Input(new ServicePortNameAndNumber(-1, "http"), "dummy", Map.of(), Map.of()))).isFalse(); + .resolve(new Input(new ServicePortNameAndNumber(-1, "http"), "dummy", Map.of(), Map.of()))).isFalse(); assertThat(secureResolver - .resolve(new Input(new ServicePortNameAndNumber(8080, "http"), "dummy", Map.of(), Map.of()))).isFalse(); + .resolve(new Input(new ServicePortNameAndNumber(8080, "http"), "dummy", Map.of(), Map.of()))).isFalse(); assertThat(secureResolver - .resolve(new Input(new ServicePortNameAndNumber(1234, "http"), "dummy", Map.of(), Map.of()))).isFalse(); + .resolve(new Input(new ServicePortNameAndNumber(1234, "http"), "dummy", Map.of(), Map.of()))).isFalse(); assertThat(secureResolver - .resolve(new Input(new ServicePortNameAndNumber(443, "http"), "dummy", Map.of(), Map.of()))).isTrue(); + .resolve(new Input(new ServicePortNameAndNumber(443, "http"), "dummy", Map.of(), Map.of()))).isTrue(); assertThat(secureResolver - .resolve(new Input(new ServicePortNameAndNumber(8443, "http"), "dummy", Map.of(), Map.of()))).isTrue(); + .resolve(new Input(new ServicePortNameAndNumber(8443, "http"), "dummy", Map.of(), Map.of()))).isTrue(); assertThat(secureResolver - .resolve(new Input(new ServicePortNameAndNumber(12345, "http"), "dummy", Map.of(), Map.of()))).isTrue(); + .resolve(new Input(new ServicePortNameAndNumber(12345, "http"), "dummy", Map.of(), Map.of()))).isTrue(); } @Test @@ -181,7 +181,7 @@ void noConditionsMatchButPortIsHttps(CapturedOutput output) { boolean result = secureResolver.resolve(input); assertThat(result).isTrue(); assertThat(output.getOut()) - .contains("Considering service with name: dummy and port 8080 to be secure since port-name is 'https'"); + .contains("Considering service with name: dummy and port 8080 to be secure since port-name is 'https'"); } } diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/loadbalancer/KubernetesLoadBalancerPropertiesTests.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/loadbalancer/KubernetesLoadBalancerPropertiesTests.java index 5014a36a12..0ca5cf0154 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/loadbalancer/KubernetesLoadBalancerPropertiesTests.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/loadbalancer/KubernetesLoadBalancerPropertiesTests.java @@ -32,31 +32,31 @@ class KubernetesLoadBalancerPropertiesTests { @Test void testBindingWhenNoPropertiesProvided() { new ApplicationContextRunner().withUserConfiguration(KubernetesLoadBalancerPropertiesTests.Config.class) - .run(context -> { - KubernetesLoadBalancerProperties props = context.getBean(KubernetesLoadBalancerProperties.class); - assertThat(props).isNotNull(); - assertThat(props.getEnabled()).isTrue(); - assertThat(props.getMode()).isEqualTo(KubernetesLoadBalancerMode.POD); - assertThat(props.getClusterDomain()).isEqualTo("cluster.local"); - assertThat(props.getPortName()).isEqualTo("http"); - }); + .run(context -> { + KubernetesLoadBalancerProperties props = context.getBean(KubernetesLoadBalancerProperties.class); + assertThat(props).isNotNull(); + assertThat(props.getEnabled()).isTrue(); + assertThat(props.getMode()).isEqualTo(KubernetesLoadBalancerMode.POD); + assertThat(props.getClusterDomain()).isEqualTo("cluster.local"); + assertThat(props.getPortName()).isEqualTo("http"); + }); } @Test void testBindingWhenSomePropertiesProvided() { new ApplicationContextRunner().withUserConfiguration(KubernetesLoadBalancerPropertiesTests.Config.class) - .withPropertyValues("spring.cloud.kubernetes.loadbalancer.enabled=false", - "spring.cloud.kubernetes.loadbalancer.mode=SERVICE", - "spring.cloud.kubernetes.loadbalancer.clusterDomain=clusterDomain", - "spring.cloud.kubernetes.loadbalancer.portName=portName") - .run(context -> { - KubernetesLoadBalancerProperties props = context.getBean(KubernetesLoadBalancerProperties.class); - assertThat(props).isNotNull(); - assertThat(props.getEnabled()).isFalse(); - assertThat(props.getMode()).isEqualTo(KubernetesLoadBalancerMode.SERVICE); - assertThat(props.getClusterDomain()).isEqualTo("clusterDomain"); - assertThat(props.getPortName()).isEqualTo("portName"); - }); + .withPropertyValues("spring.cloud.kubernetes.loadbalancer.enabled=false", + "spring.cloud.kubernetes.loadbalancer.mode=SERVICE", + "spring.cloud.kubernetes.loadbalancer.clusterDomain=clusterDomain", + "spring.cloud.kubernetes.loadbalancer.portName=portName") + .run(context -> { + KubernetesLoadBalancerProperties props = context.getBean(KubernetesLoadBalancerProperties.class); + assertThat(props).isNotNull(); + assertThat(props.getEnabled()).isFalse(); + assertThat(props.getMode()).isEqualTo(KubernetesLoadBalancerMode.SERVICE); + assertThat(props.getClusterDomain()).isEqualTo("clusterDomain"); + assertThat(props.getPortName()).isEqualTo("portName"); + }); } @Configuration diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/profile/KubernetesProfileEnvironmentPostProcessorTest.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/profile/KubernetesProfileEnvironmentPostProcessorTest.java index aaad3614e8..487a5f36b7 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/profile/KubernetesProfileEnvironmentPostProcessorTest.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/profile/KubernetesProfileEnvironmentPostProcessorTest.java @@ -210,7 +210,7 @@ private void assertKubernetesPropertySourcePresent() { "'KUBERNETES_NAMESPACE_PROPERTY_SOURCE' source must be present when running on kubernetes"); String property = (String) kubernetesPropertySource.get() - .getProperty("spring.cloud.kubernetes.client.namespace"); + .getProperty("spring.cloud.kubernetes.client.namespace"); Assertions.assertEquals(property, FOUNT_IT, "'spring.cloud.kubernetes.client.namespace' must be set to 'foundIt'"); } @@ -240,8 +240,11 @@ private Optional kubernetesProfile() { } private Optional> kubernetesPropertySource() { - return context.getEnvironment().getPropertySources().stream() - .filter(x -> "KUBERNETES_NAMESPACE_PROPERTY_SOURCE".equals(x.getName())).findAny(); + return context.getEnvironment() + .getPropertySources() + .stream() + .filter(x -> "KUBERNETES_NAMESPACE_PROPERTY_SOURCE".equals(x.getName())) + .findAny(); } } diff --git a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/reload/ConfigReloadAutoConfigurationApplicationContextTests.java b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/reload/ConfigReloadAutoConfigurationApplicationContextTests.java index 471911b80b..31c12b2404 100644 --- a/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/reload/ConfigReloadAutoConfigurationApplicationContextTests.java +++ b/spring-cloud-kubernetes-commons/src/test/java/org/springframework/cloud/kubernetes/commons/reload/ConfigReloadAutoConfigurationApplicationContextTests.java @@ -129,10 +129,11 @@ void testConfigMapsEnabledAndSecretsSupportDisabled() { private void setup(String... properties) { applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(InfoEndpointAutoConfiguration.class, - RefreshEndpointAutoConfiguration.class, ConfigReloadPropertiesAutoConfiguration.class, - RefreshAutoConfiguration.class, ConfigReloadAutoConfiguration.class)) - .withUserConfiguration(RebinderConfig.class).withPropertyValues(properties); + .withConfiguration(AutoConfigurations.of(InfoEndpointAutoConfiguration.class, + RefreshEndpointAutoConfiguration.class, ConfigReloadPropertiesAutoConfiguration.class, + RefreshAutoConfiguration.class, ConfigReloadAutoConfiguration.class)) + .withUserConfiguration(RebinderConfig.class) + .withPropertyValues(properties); } @TestConfiguration diff --git a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configserver/src/test/java/org/springframework/cloud/kubernetes/configserver/ConfigServerAutoConfigurationKubernetesEnabledProfileIncludedSecretsApiDisabled.java b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configserver/src/test/java/org/springframework/cloud/kubernetes/configserver/ConfigServerAutoConfigurationKubernetesEnabledProfileIncludedSecretsApiDisabled.java index 6c98575b61..b8ab3ec300 100644 --- a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configserver/src/test/java/org/springframework/cloud/kubernetes/configserver/ConfigServerAutoConfigurationKubernetesEnabledProfileIncludedSecretsApiDisabled.java +++ b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configserver/src/test/java/org/springframework/cloud/kubernetes/configserver/ConfigServerAutoConfigurationKubernetesEnabledProfileIncludedSecretsApiDisabled.java @@ -40,7 +40,7 @@ void runTest() { assertThat(context.getBeanNamesForType(KubernetesEnvironmentRepository.class)).hasSize(1); assertThat(context.getBeanNamesForType(KubernetesPropertySourceSupplier.class)).hasSize(1); assertThat(context.getBeanNamesForType(KubernetesPropertySourceSupplier.class)[0]) - .isEqualTo("configMapPropertySourceSupplier"); + .isEqualTo("configMapPropertySourceSupplier"); } } diff --git a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configserver/src/test/java/org/springframework/cloud/kubernetes/configserver/KubernetesEnvironmentRepositoryTests.java b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configserver/src/test/java/org/springframework/cloud/kubernetes/configserver/KubernetesEnvironmentRepositoryTests.java index 4b18005726..c5820f91f6 100644 --- a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configserver/src/test/java/org/springframework/cloud/kubernetes/configserver/KubernetesEnvironmentRepositoryTests.java +++ b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configserver/src/test/java/org/springframework/cloud/kubernetes/configserver/KubernetesEnvironmentRepositoryTests.java @@ -60,57 +60,63 @@ class KubernetesEnvironmentRepositoryTests { private static final String DEFAULT_NAMESPACE = "default"; private static final V1ConfigMapList CONFIGMAP_ONE_LIST = new V1ConfigMapList() - .addItemsItem(new V1ConfigMapBuilder() - .withMetadata( - new V1ObjectMetaBuilder().withName("storessingle").withNamespace(DEFAULT_NAMESPACE).build()) - .addToData("storessingle.yaml", VALUE) - .addToData("storessingle-dev.yaml", - "dummy:\n property:\n string2: \"dev\"\n int2: 1\n bool2: false\n") - .addToData("storessingle-qa.yaml", - "dummy:\n property:\n string2: \"qa\"\n int2: 2\n bool2: true\n") - .addToData("storessingle-prod.yaml", - "dummy:\n property:\n string2: \"prod\"\n int2: 3\n bool2: true\n") - .build()); + .addItemsItem(new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("storessingle").withNamespace(DEFAULT_NAMESPACE).build()) + .addToData("storessingle.yaml", VALUE) + .addToData("storessingle-dev.yaml", + "dummy:\n property:\n string2: \"dev\"\n int2: 1\n bool2: false\n") + .addToData("storessingle-qa.yaml", + "dummy:\n property:\n string2: \"qa\"\n int2: 2\n bool2: true\n") + .addToData("storessingle-prod.yaml", + "dummy:\n property:\n string2: \"prod\"\n int2: 3\n bool2: true\n") + .build()); private static final V1ConfigMapList CONFIGMAP_DEFAULT_LIST = new V1ConfigMapList() - .addItemsItem(new V1ConfigMapBuilder() - .withMetadata( - new V1ObjectMetaBuilder().withName("application").withNamespace(DEFAULT_NAMESPACE).build()) - .addToData("application.yaml", VALUE).build()) - .addItemsItem(new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("stores").withNamespace(DEFAULT_NAMESPACE).build()) - .addToData("application.yaml", VALUE).build()) - .addItemsItem(new V1ConfigMapBuilder() - .withMetadata( - new V1ObjectMetaBuilder().withName("stores-dev").withNamespace(DEFAULT_NAMESPACE).build()) - .addToData("application.yaml", - "dummy:\n property:\n string1: \"a\"\n string2: \"b\"\n int2: 2\n bool2: false\n") - .build()); + .addItemsItem(new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("application").withNamespace(DEFAULT_NAMESPACE).build()) + .addToData("application.yaml", VALUE) + .build()) + .addItemsItem(new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("stores").withNamespace(DEFAULT_NAMESPACE).build()) + .addToData("application.yaml", VALUE) + .build()) + .addItemsItem(new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("stores-dev").withNamespace(DEFAULT_NAMESPACE).build()) + .addToData("application.yaml", + "dummy:\n property:\n string1: \"a\"\n string2: \"b\"\n int2: 2\n bool2: false\n") + .build()); private static final V1ConfigMapList CONFIGMAP_DEV_LIST = new V1ConfigMapList() - .addItemsItem(new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("stores").withNamespace("dev") - .withResourceVersion("1").build()) - .addToData("application.yaml", - "dummy:\n property:\n string2: \"dev\"\n int2: 1\n bool2: true\n") - .build()); + .addItemsItem(new V1ConfigMapBuilder() + .withMetadata( + new V1ObjectMetaBuilder().withName("stores").withNamespace("dev").withResourceVersion("1").build()) + .addToData("application.yaml", "dummy:\n property:\n string2: \"dev\"\n int2: 1\n bool2: true\n") + .build()); private static final V1SecretList SECRET_LIST = new V1SecretListBuilder() - .addToItems(new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("application").withResourceVersion("0") - .withNamespace("default").build()) - .addToData("password", "p455w0rd".getBytes()).addToData("username", "user".getBytes()).build()) - .addToItems(new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("stores").withResourceVersion("0") - .withNamespace("default").build()) - .addToData("password", "password-from-stores".getBytes()).addToData("username", "stores".getBytes()) + .addToItems( + new V1SecretBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("application") + .withResourceVersion("0") + .withNamespace("default") + .build()) + .addToData("password", "p455w0rd".getBytes()) + .addToData("username", "user".getBytes()) .build()) - .addToItems(new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("stores-dev").withResourceVersion("0") - .withNamespace("default").build()) - .addToData("password", "password-from-stores-dev".getBytes()) - .addToData("username", "stores-dev".getBytes()).build()) - .build(); + .addToItems(new V1SecretBuilder().withMetadata( + new V1ObjectMetaBuilder().withName("stores").withResourceVersion("0").withNamespace("default").build()) + .addToData("password", "password-from-stores".getBytes()) + .addToData("username", "stores".getBytes()) + .build()) + .addToItems(new V1SecretBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("stores-dev") + .withResourceVersion("0") + .withNamespace("default") + .build()) + .addToData("password", "password-from-stores-dev".getBytes()) + .addToData("username", "stores-dev".getBytes()) + .build()) + .build(); @BeforeAll public static void before() { @@ -152,18 +158,22 @@ public void after() { public void testApplicationCase() throws ApiException { CoreV1Api coreApi = mock(CoreV1Api.class); when(coreApi.listNamespacedConfigMap(eq("default"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), - eq(null), eq(null), eq(null), eq(null), eq(null))).thenReturn(CONFIGMAP_DEFAULT_LIST); + eq(null), eq(null), eq(null), eq(null), eq(null))) + .thenReturn(CONFIGMAP_DEFAULT_LIST); when(coreApi.listNamespacedSecret(eq("default"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), - eq(null), eq(null), eq(null), eq(null), eq(null))).thenReturn(SECRET_LIST); + eq(null), eq(null), eq(null), eq(null), eq(null))) + .thenReturn(SECRET_LIST); when(coreApi.listNamespacedConfigMap(eq("dev"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), - eq(null), eq(null), eq(null), eq(null), eq(null))).thenReturn(CONFIGMAP_DEV_LIST); + eq(null), eq(null), eq(null), eq(null), eq(null))) + .thenReturn(CONFIGMAP_DEV_LIST); KubernetesEnvironmentRepository environmentRepository = new KubernetesEnvironmentRepository(coreApi, KUBERNETES_PROPERTY_SOURCE_SUPPLIER, "default"); Environment environment = environmentRepository.findOne("application", "", ""); assertThat(environment.getPropertySources().size()).isEqualTo(2); environment.getPropertySources().forEach(propertySource -> { assertThat(propertySource.getName().equals("configmap.application.default") - || propertySource.getName().equals("secret.application.default")).isTrue(); + || propertySource.getName().equals("secret.application.default")) + .isTrue(); if (propertySource.getName().equals("configmap.application.default")) { assertThat(propertySource.getSource().size()).isEqualTo(3); assertThat(propertySource.getSource().get("dummy.property.int2")).isEqualTo(1); @@ -182,11 +192,14 @@ public void testApplicationCase() throws ApiException { public void testStoresCase() throws ApiException { CoreV1Api coreApi = mock(CoreV1Api.class); when(coreApi.listNamespacedConfigMap(eq("default"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), - eq(null), eq(null), eq(null), eq(null), eq(null))).thenReturn(CONFIGMAP_DEFAULT_LIST); + eq(null), eq(null), eq(null), eq(null), eq(null))) + .thenReturn(CONFIGMAP_DEFAULT_LIST); when(coreApi.listNamespacedConfigMap(eq("dev"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), - eq(null), eq(null), eq(null), eq(null), eq(null))).thenReturn(CONFIGMAP_DEV_LIST); + eq(null), eq(null), eq(null), eq(null), eq(null))) + .thenReturn(CONFIGMAP_DEV_LIST); when(coreApi.listNamespacedSecret(eq("default"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), - eq(null), eq(null), eq(null), eq(null), eq(null))).thenReturn(SECRET_LIST); + eq(null), eq(null), eq(null), eq(null), eq(null))) + .thenReturn(SECRET_LIST); KubernetesEnvironmentRepository environmentRepository = new KubernetesEnvironmentRepository(coreApi, KUBERNETES_PROPERTY_SOURCE_SUPPLIER, "default"); Environment environment = environmentRepository.findOne("stores", "", ""); @@ -195,7 +208,8 @@ public void testStoresCase() throws ApiException { assertThat(propertySource.getName().equals("configmap.application.default") || propertySource.getName().equals("secret.application.default") || propertySource.getName().equals("configmap.stores.default") - || propertySource.getName().equals("secret.stores.default")).isTrue(); + || propertySource.getName().equals("secret.stores.default")) + .isTrue(); if (propertySource.getName().equals("configmap.application.default")) { assertThat(propertySource.getSource().size()).isEqualTo(3); assertThat(propertySource.getSource().get("dummy.property.int2")).isEqualTo(1); @@ -225,11 +239,14 @@ public void testStoresCase() throws ApiException { public void testStoresProfileCase() throws ApiException { CoreV1Api coreApi = mock(CoreV1Api.class); when(coreApi.listNamespacedConfigMap(eq("default"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), - eq(null), eq(null), eq(null), eq(null), eq(null))).thenReturn(CONFIGMAP_DEFAULT_LIST); + eq(null), eq(null), eq(null), eq(null), eq(null))) + .thenReturn(CONFIGMAP_DEFAULT_LIST); when(coreApi.listNamespacedSecret(eq("default"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), - eq(null), eq(null), eq(null), eq(null), eq(null))).thenReturn(SECRET_LIST); + eq(null), eq(null), eq(null), eq(null), eq(null))) + .thenReturn(SECRET_LIST); when(coreApi.listNamespacedConfigMap(eq("dev"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), - eq(null), eq(null), eq(null), eq(null), eq(null))).thenReturn(CONFIGMAP_DEV_LIST); + eq(null), eq(null), eq(null), eq(null), eq(null))) + .thenReturn(CONFIGMAP_DEV_LIST); KubernetesEnvironmentRepository environmentRepository = new KubernetesEnvironmentRepository(coreApi, KUBERNETES_PROPERTY_SOURCE_SUPPLIER, "default"); Environment environment = environmentRepository.findOne("stores", "dev", ""); @@ -240,7 +257,8 @@ public void testStoresProfileCase() throws ApiException { || propertySource.getName().equals("configmap.stores.stores-dev.default") || propertySource.getName().equals("secret.stores.default") || propertySource.getName().equals("secret.stores.stores-dev.default") - || propertySource.getName().equals("configmap.stores.default")).isTrue(); + || propertySource.getName().equals("configmap.stores.default")) + .isTrue(); if (propertySource.getName().equals("configmap.application.default")) { assertThat(propertySource.getSource().size()).isEqualTo(3); assertThat(propertySource.getSource().get("dummy.property.int2")).isEqualTo(1); @@ -285,41 +303,52 @@ else if (propertySource.getName().equals("secret.stores.default")) { public void testApplicationPropertiesAnSecretsOverride() throws ApiException { CoreV1Api coreApi = mock(CoreV1Api.class); when(coreApi.listNamespacedConfigMap(eq("default"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), - eq(null), eq(null), eq(null), eq(null), eq(null))).thenReturn(CONFIGMAP_DEFAULT_LIST); + eq(null), eq(null), eq(null), eq(null), eq(null))) + .thenReturn(CONFIGMAP_DEFAULT_LIST); when(coreApi.listNamespacedSecret(eq("default"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), - eq(null), eq(null), eq(null), eq(null), eq(null))).thenReturn(SECRET_LIST); + eq(null), eq(null), eq(null), eq(null), eq(null))) + .thenReturn(SECRET_LIST); when(coreApi.listNamespacedConfigMap(eq("dev"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), - eq(null), eq(null), eq(null), eq(null), eq(null))).thenReturn(CONFIGMAP_DEV_LIST); + eq(null), eq(null), eq(null), eq(null), eq(null))) + .thenReturn(CONFIGMAP_DEV_LIST); KubernetesEnvironmentRepository environmentRepository = new KubernetesEnvironmentRepository(coreApi, KUBERNETES_PROPERTY_SOURCE_SUPPLIER, "default"); Environment environment = environmentRepository.findOne("stores-dev", "", ""); - environment.getPropertySources().stream() - .filter(propertySource -> propertySource.getName().startsWith("configmap")) - .reduce((first, second) -> second).ifPresent(propertySource -> { - assertThat(propertySource.getName()).isEqualTo("configmap.application.default"); - }); - environment.getPropertySources().stream() - .filter(propertySource -> propertySource.getName().startsWith("configmap")).findFirst() - .ifPresent(propertySource -> { - assertThat(propertySource.getSource().get("dummy.property.int2")).isEqualTo(2); - assertThat(propertySource.getSource().get("dummy.property.bool2")).isEqualTo(false); - assertThat(propertySource.getSource().get("dummy.property.string2")).isEqualTo("b"); - }); - environment.getPropertySources().stream() - .filter(propertySource -> propertySource.getName().startsWith("secrets")).findFirst() - .ifPresent(propertySource -> { - assertThat(propertySource.getSource().get("username")).isEqualTo("stores-dev"); - assertThat(propertySource.getSource().get("password")).isEqualTo("p455w0rd"); - }); + environment.getPropertySources() + .stream() + .filter(propertySource -> propertySource.getName().startsWith("configmap")) + .reduce((first, second) -> second) + .ifPresent(propertySource -> { + assertThat(propertySource.getName()).isEqualTo("configmap.application.default"); + }); + environment.getPropertySources() + .stream() + .filter(propertySource -> propertySource.getName().startsWith("configmap")) + .findFirst() + .ifPresent(propertySource -> { + assertThat(propertySource.getSource().get("dummy.property.int2")).isEqualTo(2); + assertThat(propertySource.getSource().get("dummy.property.bool2")).isEqualTo(false); + assertThat(propertySource.getSource().get("dummy.property.string2")).isEqualTo("b"); + }); + environment.getPropertySources() + .stream() + .filter(propertySource -> propertySource.getName().startsWith("secrets")) + .findFirst() + .ifPresent(propertySource -> { + assertThat(propertySource.getSource().get("username")).isEqualTo("stores-dev"); + assertThat(propertySource.getSource().get("password")).isEqualTo("p455w0rd"); + }); } @Test public void testSingleConfigMapMultipleSources() throws ApiException { CoreV1Api coreApi = mock(CoreV1Api.class); when(coreApi.listNamespacedConfigMap(eq("default"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), - eq(null), eq(null), eq(null), eq(null), eq(null))).thenReturn(CONFIGMAP_ONE_LIST); + eq(null), eq(null), eq(null), eq(null), eq(null))) + .thenReturn(CONFIGMAP_ONE_LIST); when(coreApi.listNamespacedSecret(eq("default"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), - eq(null), eq(null), eq(null), eq(null), eq(null))).thenReturn(new V1SecretList()); + eq(null), eq(null), eq(null), eq(null), eq(null))) + .thenReturn(new V1SecretList()); List suppliers = new ArrayList<>(); suppliers.add((coreV1Api, name, namespace, environment) -> { List propertySources = new ArrayList<>(); @@ -335,13 +364,13 @@ public void testSingleConfigMapMultipleSources() throws ApiException { Environment environment = environmentRepository.findOne("storessingle", "", ""); assertThat(environment.getPropertySources().size()).isEqualTo(1); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo("configmap.storessingle.default.default"); + .isEqualTo("configmap.storessingle.default.default"); environment = environmentRepository.findOne("storessingle", "dev", ""); assertThat(environment.getPropertySources().size()).isEqualTo(2); assertThat(environment.getPropertySources().get(0).getName()).isEqualTo("configmap.storessingle.default.dev"); assertThat(environment.getPropertySources().get(1).getName()) - .isEqualTo("configmap.storessingle.default.default"); + .isEqualTo("configmap.storessingle.default.default"); environment = environmentRepository.findOne("storessingle", "dev,prod", ""); assertThat(environment.getPropertySources().size()).isEqualTo(3); @@ -354,7 +383,7 @@ public void testSingleConfigMapMultipleSources() throws ApiException { assertThat(environment.getPropertySources().get(1).getSource().get("dummy.property.bool2")).isEqualTo(false); assertThat(environment.getPropertySources().get(1).getSource().get("dummy.property.string2")).isEqualTo("dev"); assertThat(environment.getPropertySources().get(2).getName()) - .isEqualTo("configmap.storessingle.default.default"); + .isEqualTo("configmap.storessingle.default.default"); assertThat(environment.getPropertySources().get(2).getSource().get("dummy.property.int2")).isEqualTo(1); assertThat(environment.getPropertySources().get(2).getSource().get("dummy.property.bool2")).isEqualTo(true); assertThat(environment.getPropertySources().get(2).getSource().get("dummy.property.string2")).isEqualTo("a"); diff --git a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configserver/src/test/java/org/springframework/cloud/kubernetes/configserver/KubernetesPropertySourceSupplierTests.java b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configserver/src/test/java/org/springframework/cloud/kubernetes/configserver/KubernetesPropertySourceSupplierTests.java index 8e7e44ce31..01e0e5d517 100644 --- a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configserver/src/test/java/org/springframework/cloud/kubernetes/configserver/KubernetesPropertySourceSupplierTests.java +++ b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configserver/src/test/java/org/springframework/cloud/kubernetes/configserver/KubernetesPropertySourceSupplierTests.java @@ -49,38 +49,47 @@ class KubernetesPropertySourceSupplierTests { private static final CoreV1Api coreApi = mock(CoreV1Api.class); private static final V1ConfigMapList CONFIGMAP_DEFAULT_LIST = new V1ConfigMapList() - .addItemsItem(buildConfigMap("gateway", "default")); + .addItemsItem(buildConfigMap("gateway", "default")); private static final V1ConfigMapList CONFIGMAP_TEAM_A_LIST = new V1ConfigMapList() - .addItemsItem(buildConfigMap("stores", "team-a")); + .addItemsItem(buildConfigMap("stores", "team-a")); private static final V1ConfigMapList CONFIGMAP_TEAM_B_LIST = new V1ConfigMapList() - .addItemsItem(buildConfigMap("orders", "team-b")); + .addItemsItem(buildConfigMap("orders", "team-b")); private static final V1SecretList SECRET_DEFAULT_LIST = new V1SecretListBuilder() - .addToItems(buildSecret("gateway", "default")).build(); + .addToItems(buildSecret("gateway", "default")) + .build(); private static final V1SecretList SECRET_TEAM_A_LIST = new V1SecretListBuilder() - .addToItems(buildSecret("stores", "team-a")).build(); + .addToItems(buildSecret("stores", "team-a")) + .build(); private static final V1SecretList SECRET_TEAM_B_LIST = new V1SecretListBuilder() - .addToItems(buildSecret("orders", "team-b")).build(); + .addToItems(buildSecret("orders", "team-b")) + .build(); @BeforeAll public static void before() throws ApiException { when(coreApi.listNamespacedConfigMap(eq("default"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), - eq(null), eq(null), eq(null), eq(null), eq(null))).thenReturn(CONFIGMAP_DEFAULT_LIST); + eq(null), eq(null), eq(null), eq(null), eq(null))) + .thenReturn(CONFIGMAP_DEFAULT_LIST); when(coreApi.listNamespacedConfigMap(eq("team-a"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), - eq(null), eq(null), eq(null), eq(null), eq(null))).thenReturn(CONFIGMAP_TEAM_A_LIST); + eq(null), eq(null), eq(null), eq(null), eq(null))) + .thenReturn(CONFIGMAP_TEAM_A_LIST); when(coreApi.listNamespacedConfigMap(eq("team-b"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), - eq(null), eq(null), eq(null), eq(null), eq(null))).thenReturn(CONFIGMAP_TEAM_B_LIST); + eq(null), eq(null), eq(null), eq(null), eq(null))) + .thenReturn(CONFIGMAP_TEAM_B_LIST); when(coreApi.listNamespacedSecret(eq("default"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), - eq(null), eq(null), eq(null), eq(null), eq(null))).thenReturn(SECRET_DEFAULT_LIST); + eq(null), eq(null), eq(null), eq(null), eq(null))) + .thenReturn(SECRET_DEFAULT_LIST); when(coreApi.listNamespacedSecret(eq("team-a"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), - eq(null), eq(null), eq(null), eq(null), eq(null))).thenReturn(SECRET_TEAM_A_LIST); + eq(null), eq(null), eq(null), eq(null), eq(null))) + .thenReturn(SECRET_TEAM_A_LIST); when(coreApi.listNamespacedSecret(eq("team-b"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), - eq(null), eq(null), eq(null), eq(null), eq(null))).thenReturn(SECRET_TEAM_B_LIST); + eq(null), eq(null), eq(null), eq(null), eq(null))) + .thenReturn(SECRET_TEAM_B_LIST); } @Test @@ -89,7 +98,7 @@ void whenCurrentAndExtraNamespacesAddedThenAllConfigMapsAreIncluded() { kubernetesConfigServerProperties.setConfigMapNamespaces("default,team-a,team-b"); KubernetesPropertySourceSupplier kubernetesPropertySourceSupplier = new KubernetesConfigServerAutoConfiguration() - .configMapPropertySourceSupplier(kubernetesConfigServerProperties); + .configMapPropertySourceSupplier(kubernetesConfigServerProperties); KubernetesEnvironmentRepository environmentRepository = new KubernetesEnvironmentRepository(coreApi, Collections.singletonList(kubernetesPropertySourceSupplier), "default"); @@ -110,7 +119,7 @@ void whenExtraNamespacesAddedThenConfigMapsInCurrentNamespaceAreNotIncluded() { kubernetesConfigServerProperties.setConfigMapNamespaces("team-a,team-b"); KubernetesPropertySourceSupplier kubernetesPropertySourceSupplier = new KubernetesConfigServerAutoConfiguration() - .configMapPropertySourceSupplier(kubernetesConfigServerProperties); + .configMapPropertySourceSupplier(kubernetesConfigServerProperties); KubernetesEnvironmentRepository environmentRepository = new KubernetesEnvironmentRepository(coreApi, Collections.singletonList(kubernetesPropertySourceSupplier), "default"); @@ -131,7 +140,7 @@ void whenCurrentAndExtraNamespacesAddedThenAllSecretsAreIncluded() { kubernetesConfigServerProperties.setSecretsNamespaces("default,team-a,team-b"); KubernetesPropertySourceSupplier kubernetesPropertySourceSupplier = new KubernetesConfigServerAutoConfiguration() - .secretsPropertySourceSupplier(kubernetesConfigServerProperties); + .secretsPropertySourceSupplier(kubernetesConfigServerProperties); KubernetesEnvironmentRepository environmentRepository = new KubernetesEnvironmentRepository(coreApi, Collections.singletonList(kubernetesPropertySourceSupplier), "default"); @@ -152,7 +161,7 @@ void whenExtraNamespacesAddedThenSecretsInCurrentNamespaceAreNotIncluded() { kubernetesConfigServerProperties.setSecretsNamespaces("team-a,team-b"); KubernetesPropertySourceSupplier kubernetesPropertySourceSupplier = new KubernetesConfigServerAutoConfiguration() - .secretsPropertySourceSupplier(kubernetesConfigServerProperties); + .secretsPropertySourceSupplier(kubernetesConfigServerProperties); KubernetesEnvironmentRepository environmentRepository = new KubernetesEnvironmentRepository(coreApi, Collections.singletonList(kubernetesPropertySourceSupplier), "default"); @@ -169,16 +178,19 @@ void whenExtraNamespacesAddedThenSecretsInCurrentNamespaceAreNotIncluded() { private static V1ConfigMap buildConfigMap(String name, String namespace) { return new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName(name).withNamespace(namespace).withResourceVersion("1") - .build()) - .addToData("application.yaml", "dummy:\n property:\n string: \"" + name + "\"\n").build(); + .withMetadata( + new V1ObjectMetaBuilder().withName(name).withNamespace(namespace).withResourceVersion("1").build()) + .addToData("application.yaml", "dummy:\n property:\n string: \"" + name + "\"\n") + .build(); } private static V1Secret buildSecret(String name, String namespace) { return new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName(name).withResourceVersion("0").withNamespace(namespace) - .build()) - .addToData("password", "p455w0rd".getBytes()).addToData("username", "user".getBytes()).build(); + .withMetadata( + new V1ObjectMetaBuilder().withName(name).withResourceVersion("0").withNamespace(namespace).build()) + .addToData("password", "p455w0rd".getBytes()) + .addToData("username", "user".getBytes()) + .build(); } } diff --git a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configserver/src/test/java/org/springframework/cloud/kubernetes/configserver/it/ConfigDataConfigServerIntegrationTest.java b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configserver/src/test/java/org/springframework/cloud/kubernetes/configserver/it/ConfigDataConfigServerIntegrationTest.java index 98847decc2..ae3765ceae 100644 --- a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configserver/src/test/java/org/springframework/cloud/kubernetes/configserver/it/ConfigDataConfigServerIntegrationTest.java +++ b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configserver/src/test/java/org/springframework/cloud/kubernetes/configserver/it/ConfigDataConfigServerIntegrationTest.java @@ -44,7 +44,7 @@ class ConfigDataConfigServerIntegrationTest extends ConfigServerIntegrationTest void setup() { clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::kubernetesApiClient) - .thenReturn(new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(wireMockServer.baseUrl()).build()); } @AfterEach diff --git a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configserver/src/test/java/org/springframework/cloud/kubernetes/configserver/it/ConfigServerIntegrationTest.java b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configserver/src/test/java/org/springframework/cloud/kubernetes/configserver/it/ConfigServerIntegrationTest.java index b103521da8..a3092e3a08 100644 --- a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configserver/src/test/java/org/springframework/cloud/kubernetes/configserver/it/ConfigServerIntegrationTest.java +++ b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configserver/src/test/java/org/springframework/cloud/kubernetes/configserver/it/ConfigServerIntegrationTest.java @@ -51,32 +51,33 @@ abstract class ConfigServerIntegrationTest { @BeforeEach void beforeEach() { - V1ConfigMapList TEST_CONFIGMAP = new V1ConfigMapList().addItemsItem(new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("test-cm").withNamespace("default") - .withResourceVersion("1").build()) - .addToData("test-cm-dev.yaml", - "dummy:\n property:\n string2: \"dev\"\n int2: 1\n bool2: false\n") - .addToData("test-cm-qa.yaml", - "dummy:\n property:\n string2: \"qa\"\n int2: 2\n bool2: true\n") - .addToData("test-cm-prod.yaml", - "dummy:\n property:\n string2: \"prod\"\n int2: 3\n bool2: true\n") - .addToData("test-cm.yaml", - "dummy:\n property:\n string2: \"default\"\n int2: 4\n bool2: true\n") - .addToData("app.name", "test").build()); + V1ConfigMapList TEST_CONFIGMAP = new V1ConfigMapList().addItemsItem(new V1ConfigMapBuilder().withMetadata( + new V1ObjectMetaBuilder().withName("test-cm").withNamespace("default").withResourceVersion("1").build()) + .addToData("test-cm-dev.yaml", "dummy:\n property:\n string2: \"dev\"\n int2: 1\n bool2: false\n") + .addToData("test-cm-qa.yaml", "dummy:\n property:\n string2: \"qa\"\n int2: 2\n bool2: true\n") + .addToData("test-cm-prod.yaml", + "dummy:\n property:\n string2: \"prod\"\n int2: 3\n bool2: true\n") + .addToData("test-cm.yaml", "dummy:\n property:\n string2: \"default\"\n int2: 4\n bool2: true\n") + .addToData("app.name", "test") + .build()); V1SecretList TEST_SECRET = new V1SecretListBuilder() - .withMetadata(new V1ListMetaBuilder().withResourceVersion("1").build()) - .addToItems(new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withName("test-cm").withResourceVersion("0") - .withNamespace("default").build()) - .addToData("password", "p455w0rd".getBytes()).addToData("username", "user".getBytes()).build()) - .build(); + .withMetadata(new V1ListMetaBuilder().withResourceVersion("1").build()) + .addToItems(new V1SecretBuilder() + .withMetadata(new V1ObjectMetaBuilder().withName("test-cm") + .withResourceVersion("0") + .withNamespace("default") + .build()) + .addToData("password", "p455w0rd".getBytes()) + .addToData("username", "user".getBytes()) + .build()) + .build(); WireMock.stubFor(get(urlMatching("^/api/v1/namespaces/default/configmaps.*")) - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(TEST_CONFIGMAP)))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(TEST_CONFIGMAP)))); WireMock.stubFor(get(urlMatching("^/api/v1/namespaces/default/secrets.*")) - .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(TEST_SECRET)))); + .willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(TEST_SECRET)))); } @Test diff --git a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/main/java/org/springframework/cloud/kubernetes/configuration/watcher/ConfigMapWatcherChangeDetector.java b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/main/java/org/springframework/cloud/kubernetes/configuration/watcher/ConfigMapWatcherChangeDetector.java index e0253761d3..06b87e7a98 100644 --- a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/main/java/org/springframework/cloud/kubernetes/configuration/watcher/ConfigMapWatcherChangeDetector.java +++ b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/main/java/org/springframework/cloud/kubernetes/configuration/watcher/ConfigMapWatcherChangeDetector.java @@ -38,8 +38,8 @@ * @author Kris Iyer */ abstract sealed class ConfigMapWatcherChangeDetector extends KubernetesClientEventBasedConfigMapChangeDetector - implements - RefreshTrigger permits BusEventBasedConfigMapWatcherChangeDetector, HttpBasedConfigMapWatchChangeDetector { + implements RefreshTrigger + permits BusEventBasedConfigMapWatcherChangeDetector, HttpBasedConfigMapWatchChangeDetector { private final ScheduledExecutorService executorService; diff --git a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/main/java/org/springframework/cloud/kubernetes/configuration/watcher/HttpRefreshTrigger.java b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/main/java/org/springframework/cloud/kubernetes/configuration/watcher/HttpRefreshTrigger.java index c7424d46d6..29ef23d3dc 100644 --- a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/main/java/org/springframework/cloud/kubernetes/configuration/watcher/HttpRefreshTrigger.java +++ b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/main/java/org/springframework/cloud/kubernetes/configuration/watcher/HttpRefreshTrigger.java @@ -58,8 +58,12 @@ public Mono triggerRefresh(KubernetesObject kubernetesObject, String appNa URI actuatorUri = getActuatorUri(si, k8SConfigurationProperties.getActuatorPath(), k8SConfigurationProperties.getActuatorPort()); LOG.debug(() -> "Sending refresh request for " + appName + " to URI " + actuatorUri); - return webClient.post().uri(actuatorUri).retrieve().toBodilessEntity() - .doOnSuccess(onSuccess(appName, actuatorUri)).doOnError(onError(appName)); + return webClient.post() + .uri(actuatorUri) + .retrieve() + .toBodilessEntity() + .doOnSuccess(onSuccess(appName, actuatorUri)) + .doOnError(onError(appName)); }).then(); } @@ -73,12 +77,13 @@ private Consumer onError(String name) { } private URI getActuatorUri(ServiceInstance si, String actuatorPath, int actuatorPort) { - String metadataUri = si.getMetadata().getOrDefault(ConfigurationWatcherConfigurationProperties.ANNOTATION_KEY, - ""); + String metadataUri = si.getMetadata() + .getOrDefault(ConfigurationWatcherConfigurationProperties.ANNOTATION_KEY, ""); LOG.debug(() -> "Metadata actuator uri is: " + metadataUri); - UriComponentsBuilder actuatorUriBuilder = UriComponentsBuilder.newInstance().scheme(si.getScheme()) - .host(si.getHost()); + UriComponentsBuilder actuatorUriBuilder = UriComponentsBuilder.newInstance() + .scheme(si.getScheme()) + .host(si.getHost()); if (StringUtils.hasText(metadataUri)) { LOG.debug(() -> "Found actuator URI in service instance metadata"); diff --git a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/main/java/org/springframework/cloud/kubernetes/configuration/watcher/RefreshTrigger.java b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/main/java/org/springframework/cloud/kubernetes/configuration/watcher/RefreshTrigger.java index f4430bba02..2053260293 100644 --- a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/main/java/org/springframework/cloud/kubernetes/configuration/watcher/RefreshTrigger.java +++ b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/main/java/org/springframework/cloud/kubernetes/configuration/watcher/RefreshTrigger.java @@ -24,7 +24,8 @@ * * @author wind57 */ -sealed interface RefreshTrigger permits BusRefreshTrigger, ConfigMapWatcherChangeDetector, HttpRefreshTrigger, SecretsWatcherChangeDetector { +sealed interface RefreshTrigger + permits BusRefreshTrigger, ConfigMapWatcherChangeDetector, HttpRefreshTrigger, SecretsWatcherChangeDetector { /** * @param kubernetesObject either a config-map or secret at the moment. diff --git a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/BusEventBasedConfigMapWatcherChangeDetectorTests.java b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/BusEventBasedConfigMapWatcherChangeDetectorTests.java index f166163927..d15ef54318 100644 --- a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/BusEventBasedConfigMapWatcherChangeDetectorTests.java +++ b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/BusEventBasedConfigMapWatcherChangeDetectorTests.java @@ -88,7 +88,7 @@ void triggerRefreshWithConfigMap() { configMap.setMetadata(objectMeta); changeDetector.triggerRefresh(configMap, configMap.getMetadata().getName()); ArgumentCaptor argumentCaptor = ArgumentCaptor - .forClass(RefreshRemoteApplicationEvent.class); + .forClass(RefreshRemoteApplicationEvent.class); verify(applicationEventPublisher).publishEvent(argumentCaptor.capture()); assertThat(argumentCaptor.getValue().getSource()).isEqualTo(configMap); assertThat(argumentCaptor.getValue().getOriginService()).isEqualTo(busProperties.getId()); diff --git a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/BusEventBasedSecretsWatcherChangeDetectorTests.java b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/BusEventBasedSecretsWatcherChangeDetectorTests.java index 5d4343e38a..b79a068b32 100644 --- a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/BusEventBasedSecretsWatcherChangeDetectorTests.java +++ b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/BusEventBasedSecretsWatcherChangeDetectorTests.java @@ -88,7 +88,7 @@ void triggerRefreshWithSecret() { secret.setMetadata(objectMeta); changeDetector.triggerRefresh(secret, secret.getMetadata().getName()); ArgumentCaptor argumentCaptor = ArgumentCaptor - .forClass(RefreshRemoteApplicationEvent.class); + .forClass(RefreshRemoteApplicationEvent.class); verify(applicationEventPublisher).publishEvent(argumentCaptor.capture()); assertThat(argumentCaptor.getValue().getSource()).isEqualTo(secret); assertThat(argumentCaptor.getValue().getOriginService()).isEqualTo(busProperties.getId()); diff --git a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/HttpBasedConfigMapWatchChangeDetectorTests.java b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/HttpBasedConfigMapWatchChangeDetectorTests.java index 0351dca5e1..7c6a3c6b5a 100644 --- a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/HttpBasedConfigMapWatchChangeDetectorTests.java +++ b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/HttpBasedConfigMapWatchChangeDetectorTests.java @@ -92,10 +92,10 @@ static void beforeAll() { WIRE_MOCK_SERVER.start(); clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::createApiClientForInformerClient) - .thenReturn(new ClientBuilder().setBasePath(WIRE_MOCK_SERVER.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(WIRE_MOCK_SERVER.baseUrl()).build()); clientUtilsMock - .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("default"); + .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn("default"); } @AfterAll @@ -131,9 +131,9 @@ void triggerConfigMapRefresh() { configMap.setMetadata(objectMeta); WireMock.configureFor("localhost", WIRE_MOCK_SERVER.port()); WireMock.stubFor(WireMock.post(WireMock.urlEqualTo("/actuator/refresh")) - .willReturn(WireMock.aResponse().withStatus(200))); + .willReturn(WireMock.aResponse().withStatus(200))); StepVerifier.create(changeDetector.triggerRefresh(configMap, configMap.getMetadata().getName())) - .verifyComplete(); + .verifyComplete(); WireMock.verify(WireMock.postRequestedFor(WireMock.urlEqualTo("/actuator/refresh"))); } @@ -147,9 +147,9 @@ void triggerConfigMapRefreshWithPropertiesBasedActuatorPath() { configMap.setMetadata(objectMeta); WireMock.configureFor("localhost", WIRE_MOCK_SERVER.port()); WireMock.stubFor(WireMock.post(WireMock.urlEqualTo("/my/custom/actuator/refresh")) - .willReturn(WireMock.aResponse().withStatus(200))); + .willReturn(WireMock.aResponse().withStatus(200))); StepVerifier.create(changeDetector.triggerRefresh(configMap, configMap.getMetadata().getName())) - .verifyComplete(); + .verifyComplete(); WireMock.verify(WireMock.postRequestedFor(WireMock.urlEqualTo("/my/custom/actuator/refresh"))); } @@ -175,9 +175,9 @@ void triggerConfigMapRefreshWithAnnotationActuatorPath() { objectMeta.setName("foo"); configMap.setMetadata(objectMeta); WireMock.stubFor(WireMock.post(WireMock.urlEqualTo("/my/custom/actuator/refresh")) - .willReturn(WireMock.aResponse().withStatus(200))); + .willReturn(WireMock.aResponse().withStatus(200))); StepVerifier.create(changeDetector.triggerRefresh(configMap, configMap.getMetadata().getName())) - .verifyComplete(); + .verifyComplete(); WireMock.verify(WireMock.postRequestedFor(WireMock.urlEqualTo("/my/custom/actuator/refresh"))); } diff --git a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/HttpBasedSecretsWatchChangeDetectorTests.java b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/HttpBasedSecretsWatchChangeDetectorTests.java index b6e20f2571..87fae0c7a0 100644 --- a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/HttpBasedSecretsWatchChangeDetectorTests.java +++ b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/HttpBasedSecretsWatchChangeDetectorTests.java @@ -108,10 +108,10 @@ static void beforeAll() { WIRE_MOCK_SERVER.start(); clientUtilsMock = mockStatic(KubernetesClientUtils.class); clientUtilsMock.when(KubernetesClientUtils::createApiClientForInformerClient) - .thenReturn(new ClientBuilder().setBasePath(WIRE_MOCK_SERVER.baseUrl()).build()); + .thenReturn(new ClientBuilder().setBasePath(WIRE_MOCK_SERVER.baseUrl()).build()); clientUtilsMock - .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("default"); + .when(() -> KubernetesClientUtils.getApplicationNamespace(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn("default"); } @AfterAll @@ -128,7 +128,7 @@ void triggerSecretRefresh() { secret.setMetadata(objectMeta); WireMock.configureFor("localhost", WIRE_MOCK_SERVER.port()); WireMock.stubFor(WireMock.post(WireMock.urlEqualTo("/actuator/refresh")) - .willReturn(WireMock.aResponse().withStatus(200))); + .willReturn(WireMock.aResponse().withStatus(200))); StepVerifier.create(changeDetector.triggerRefresh(secret, secret.getMetadata().getName())).verifyComplete(); WireMock.verify(WireMock.postRequestedFor(WireMock.urlEqualTo("/actuator/refresh"))); } @@ -143,7 +143,7 @@ void triggerSecretRefreshWithPropertiesBasedActuatorPath() { secret.setMetadata(objectMeta); WireMock.configureFor("localhost", WIRE_MOCK_SERVER.port()); WireMock.stubFor(WireMock.post(WireMock.urlEqualTo("/my/custom/actuator/refresh")) - .willReturn(WireMock.aResponse().withStatus(200))); + .willReturn(WireMock.aResponse().withStatus(200))); StepVerifier.create(changeDetector.triggerRefresh(secret, secret.getMetadata().getName())).verifyComplete(); WireMock.verify(WireMock.postRequestedFor(WireMock.urlEqualTo("/my/custom/actuator/refresh"))); } @@ -169,7 +169,7 @@ void triggerSecretRefreshWithAnnotationActuatorPath() { objectMeta.setName("foo"); secret.setMetadata(objectMeta); WireMock.stubFor(WireMock.post(WireMock.urlEqualTo("/my/custom/actuator/refresh")) - .willReturn(WireMock.aResponse().withStatus(200))); + .willReturn(WireMock.aResponse().withStatus(200))); StepVerifier.create(changeDetector.triggerRefresh(secret, secret.getMetadata().getName())).verifyComplete(); WireMock.verify(WireMock.postRequestedFor(WireMock.urlEqualTo("/my/custom/actuator/refresh"))); } diff --git a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/WatcherUtilTests.java b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/WatcherUtilTests.java index eef9c9b95d..f8d16d96b3 100644 --- a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/WatcherUtilTests.java +++ b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/WatcherUtilTests.java @@ -43,7 +43,8 @@ void isSpringCloudKubernetesConfigFalse() { @Test void isSpringCloudKubernetesConfigTrue() { V1ConfigMap configMap = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMeta().labels(Map.of(CONFIG_MAP_LABEL, "true"))).build(); + .withMetadata(new V1ObjectMeta().labels(Map.of(CONFIG_MAP_LABEL, "true"))) + .build(); boolean present = WatcherUtil.isSpringCloudKubernetes(configMap, CONFIG_MAP_LABEL); Assertions.assertTrue(present); } @@ -58,7 +59,7 @@ void isSpringCloudKubernetesSecretFalse() { @Test void isSpringCloudKubernetesSecretTrue() { V1Secret secret = new V1SecretBuilder().withMetadata(new V1ObjectMeta().labels(Map.of(SECRET_LABEL, "true"))) - .build(); + .build(); boolean present = WatcherUtil.isSpringCloudKubernetes(secret, SECRET_LABEL); Assertions.assertTrue(present); } @@ -101,7 +102,8 @@ void appsAnnotationNotFound() { @Test void appsSingleResult() { V1Secret secret = new V1SecretBuilder() - .withMetadata(new V1ObjectMeta().annotations(Map.of(SECRET_APPS_ANNOTATION, "one-app"))).build(); + .withMetadata(new V1ObjectMeta().annotations(Map.of(SECRET_APPS_ANNOTATION, "one-app"))) + .build(); Set apps = WatcherUtil.apps(secret, SECRET_APPS_ANNOTATION); Assertions.assertEquals(apps.size(), 1); Assertions.assertEquals(apps.iterator().next(), "one-app"); @@ -110,8 +112,8 @@ void appsSingleResult() { @Test void appsMultipleResults() { V1Secret secret = new V1SecretBuilder() - .withMetadata(new V1ObjectMeta().annotations(Map.of(SECRET_APPS_ANNOTATION, "one, two, three "))) - .build(); + .withMetadata(new V1ObjectMeta().annotations(Map.of(SECRET_APPS_ANNOTATION, "one, two, three "))) + .build(); Set apps = WatcherUtil.apps(secret, SECRET_APPS_ANNOTATION); Assertions.assertEquals(apps.size(), 3); Assertions.assertTrue(apps.contains("one")); diff --git a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/main/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryServerController.java b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/main/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryServerController.java index e32fdef3bc..23b1884936 100644 --- a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/main/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryServerController.java +++ b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/main/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryServerController.java @@ -42,9 +42,10 @@ public DiscoveryServerController(KubernetesInformerReactiveDiscoveryClient react @GetMapping("/apps") public Flux apps() { return reactiveDiscoveryClient.getServices() - .flatMap(service -> reactiveDiscoveryClient.getInstances(service).collectList() - .flatMap(serviceInstances -> Mono.just(new Service(service, - serviceInstances.stream().map(x -> (DefaultKubernetesServiceInstance) x).toList())))); + .flatMap(service -> reactiveDiscoveryClient.getInstances(service) + .collectList() + .flatMap(serviceInstances -> Mono.just(new Service(service, + serviceInstances.stream().map(x -> (DefaultKubernetesServiceInstance) x).toList())))); } @GetMapping("/apps/{name}") @@ -68,7 +69,8 @@ Mono appInstanceNonDeprecated(@PathVariable String name, @PathV private Mono innerAppInstance(String name, String instanceId) { return reactiveDiscoveryClient.getInstances(name) - .filter(serviceInstance -> serviceInstance.getInstanceId().equals(instanceId)).singleOrEmpty(); + .filter(serviceInstance -> serviceInstance.getInstanceId().equals(instanceId)) + .singleOrEmpty(); } } diff --git a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/test/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryCatalogWatcherControllerTests.java b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/test/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryCatalogWatcherControllerTests.java index 7964f8e5f7..d92989f55e 100644 --- a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/test/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryCatalogWatcherControllerTests.java +++ b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/test/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryCatalogWatcherControllerTests.java @@ -35,13 +35,14 @@ class DiscoveryCatalogWatcherControllerTests { @Test void test() { Mockito.when(heartBeatListener.lastState()) - .thenReturn(new AtomicReference<>(List.of(new EndpointNameAndNamespace("one", "two")))); + .thenReturn(new AtomicReference<>(List.of(new EndpointNameAndNamespace("one", "two")))); DiscoveryCatalogWatcherController catalogWatcherController = new DiscoveryCatalogWatcherController( heartBeatListener); StepVerifier.create(catalogWatcherController.state()) - .expectNext(List.of(new EndpointNameAndNamespace("one", "two"))).verifyComplete(); + .expectNext(List.of(new EndpointNameAndNamespace("one", "two"))) + .verifyComplete(); } } diff --git a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/test/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryServerControllerTests.java b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/test/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryServerControllerTests.java index abcf5f131d..23a84a5609 100644 --- a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/test/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryServerControllerTests.java +++ b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/test/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryServerControllerTests.java @@ -103,7 +103,8 @@ void apps() { void appInstances() { DiscoveryServerController controller = new DiscoveryServerController(discoveryClient); StepVerifier.create(controller.appInstances("serviceA")) - .expectNext(SERVICE_A_INSTANCE_1, SERVICE_A_INSTANCE_2, SERVICE_A_INSTANCE_3).verifyComplete(); + .expectNext(SERVICE_A_INSTANCE_1, SERVICE_A_INSTANCE_2, SERVICE_A_INSTANCE_3) + .verifyComplete(); StepVerifier.create(controller.appInstances("serviceB")).expectNext(SERVICE_B_INSTANCE_1).verifyComplete(); StepVerifier.create(controller.appInstances("serviceC")).expectNext(SERVICE_C_INSTANCE_1).verifyComplete(); StepVerifier.create(controller.appInstances("serviceD")).expectNextCount(0).verifyComplete(); @@ -112,8 +113,9 @@ void appInstances() { @Test void appInstance() { DiscoveryServerController controller = new DiscoveryServerController(discoveryClient); - StepVerifier.create(controller.appInstance("serviceA", "serviceAInstance2")).expectNext(SERVICE_A_INSTANCE_2) - .verifyComplete(); + StepVerifier.create(controller.appInstance("serviceA", "serviceAInstance2")) + .expectNext(SERVICE_A_INSTANCE_2) + .verifyComplete(); StepVerifier.create(controller.appInstance("serviceB", "doesnotexist")).expectNextCount(0).verifyComplete(); } diff --git a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/test/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryServerIntegrationAppsEndpointTest.java b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/test/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryServerIntegrationAppsEndpointTest.java index 0acd107f8c..22109008cb 100644 --- a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/test/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryServerIntegrationAppsEndpointTest.java +++ b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/test/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryServerIntegrationAppsEndpointTest.java @@ -65,24 +65,27 @@ class DiscoveryServerIntegrationAppsEndpointTest { private static final SharedInformerFactory SHARED_INFORMER_FACTORY = Mockito.mock(SharedInformerFactory.class); private static final V1Service TEST_SERVICE_A = new V1Service() - .metadata(new V1ObjectMeta().name("test-svc-1").namespace(NAMESPACE)) - .spec(new V1ServiceSpec().type("ClusterIP")); + .metadata(new V1ObjectMeta().name("test-svc-1").namespace(NAMESPACE)) + .spec(new V1ServiceSpec().type("ClusterIP")); - private static final V1Service TEST_SERVICE_B = new V1Service().metadata(new V1ObjectMeta().name("test-svc-2") - .namespace(NAMESPACE).putLabelsItem("spring", "true").putLabelsItem("k8s", "true")) - .spec(new V1ServiceSpec().type("ClusterIP")); + private static final V1Service TEST_SERVICE_B = new V1Service() + .metadata(new V1ObjectMeta().name("test-svc-2") + .namespace(NAMESPACE) + .putLabelsItem("spring", "true") + .putLabelsItem("k8s", "true")) + .spec(new V1ServiceSpec().type("ClusterIP")); private static final V1Endpoints TEST_ENDPOINTS_A = new V1Endpoints() - .metadata(new V1ObjectMeta().name("test-svc-1").namespace(NAMESPACE)) - .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(8080).name("http")) - .addAddressesItem(new V1EndpointAddress().ip("2.2.2.2") - .targetRef(new V1ObjectReferenceBuilder().withUid("uid1").build()))); + .metadata(new V1ObjectMeta().name("test-svc-1").namespace(NAMESPACE)) + .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(8080).name("http")) + .addAddressesItem(new V1EndpointAddress().ip("2.2.2.2") + .targetRef(new V1ObjectReferenceBuilder().withUid("uid1").build()))); private static final V1Endpoints TEST_ENDPOINTS_B = new V1Endpoints() - .metadata(new V1ObjectMeta().name("test-svc-2").namespace(NAMESPACE)) - .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(8080).name("http")) - .addAddressesItem(new V1EndpointAddress().ip("2.2.2.2") - .targetRef(new V1ObjectReferenceBuilder().withUid("uid2").build()))); + .metadata(new V1ObjectMeta().name("test-svc-2").namespace(NAMESPACE)) + .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(8080).name("http")) + .addAddressesItem(new V1EndpointAddress().ip("2.2.2.2") + .targetRef(new V1ObjectReferenceBuilder().withUid("uid2").build()))); @Autowired private WebTestClient webTestClient; @@ -112,11 +115,16 @@ void apps() { TEST_ENDPOINTS_B.getSubsets().get(0).getPorts().get(0).getPort(), metadataB, false, TEST_SERVICE_B.getMetadata().getNamespace(), null); - webTestClient.get().uri("/apps").exchange().expectBodyList(Util.InstanceForTest.class).hasSize(2).contains( - new Util.InstanceForTest(TEST_SERVICE_A.getMetadata().getName(), - Collections.singletonList(kubernetesServiceInstance1)), - new Util.InstanceForTest(TEST_SERVICE_B.getMetadata().getName(), - Collections.singletonList(kubernetesServiceInstance2))); + webTestClient.get() + .uri("/apps") + .exchange() + .expectBodyList(Util.InstanceForTest.class) + .hasSize(2) + .contains( + new Util.InstanceForTest(TEST_SERVICE_A.getMetadata().getName(), + Collections.singletonList(kubernetesServiceInstance1)), + new Util.InstanceForTest(TEST_SERVICE_B.getMetadata().getName(), + Collections.singletonList(kubernetesServiceInstance2))); } @TestConfiguration diff --git a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/test/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryServerIntegrationAppsNameEndpointTest.java b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/test/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryServerIntegrationAppsNameEndpointTest.java index 405a7882c4..59e0448327 100644 --- a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/test/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryServerIntegrationAppsNameEndpointTest.java +++ b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/test/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryServerIntegrationAppsNameEndpointTest.java @@ -65,15 +65,18 @@ class DiscoveryServerIntegrationAppsNameEndpointTest { private static final SharedInformerFactory SHARED_INFORMER_FACTORY = Mockito.mock(SharedInformerFactory.class); private static final V1Service TEST_SERVICE = new V1Service() - .metadata(new V1ObjectMeta().name("test-svc-3").namespace(NAMESPACE).putLabelsItem("spring", "true") - .putLabelsItem("k8s", "true")) - .spec(new V1ServiceSpec().loadBalancerIP("1.1.1.1").type("ClusterIP")).status(new V1ServiceStatus()); + .metadata(new V1ObjectMeta().name("test-svc-3") + .namespace(NAMESPACE) + .putLabelsItem("spring", "true") + .putLabelsItem("k8s", "true")) + .spec(new V1ServiceSpec().loadBalancerIP("1.1.1.1").type("ClusterIP")) + .status(new V1ServiceStatus()); private static final V1Endpoints TEST_ENDPOINTS = new V1Endpoints() - .metadata(new V1ObjectMeta().name("test-svc-3").namespace(NAMESPACE)) - .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(8080).name("http")) - .addAddressesItem(new V1EndpointAddress().ip("2.2.2.2") - .targetRef(new V1ObjectReferenceBuilder().withUid("uid2").build()))); + .metadata(new V1ObjectMeta().name("test-svc-3").namespace(NAMESPACE)) + .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(8080).name("http")) + .addAddressesItem(new V1EndpointAddress().ip("2.2.2.2") + .targetRef(new V1ObjectReferenceBuilder().withUid("uid2").build()))); @Autowired private WebTestClient webTestClient; @@ -93,8 +96,12 @@ void appsName() { TEST_ENDPOINTS.getSubsets().get(0).getPorts().get(0).getPort(), metadata, false, TEST_SERVICE.getMetadata().getNamespace(), null); - webTestClient.get().uri("/apps/test-svc-3").exchange().expectBodyList(DefaultKubernetesServiceInstance.class) - .hasSize(1).contains(kubernetesServiceInstance); + webTestClient.get() + .uri("/apps/test-svc-3") + .exchange() + .expectBodyList(DefaultKubernetesServiceInstance.class) + .hasSize(1) + .contains(kubernetesServiceInstance); } @TestConfiguration diff --git a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/test/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryServerIntegrationInstanceEndpointTest.java b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/test/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryServerIntegrationInstanceEndpointTest.java index 957dee8462..ab71654b7d 100644 --- a/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/test/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryServerIntegrationInstanceEndpointTest.java +++ b/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/test/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryServerIntegrationInstanceEndpointTest.java @@ -65,15 +65,18 @@ class DiscoveryServerIntegrationInstanceEndpointTest { private static final SharedInformerFactory SHARED_INFORMER_FACTORY = Mockito.mock(SharedInformerFactory.class); private static final V1Service TEST_SERVICE = new V1Service() - .metadata(new V1ObjectMeta().name("test-svc-3").namespace(NAMESPACE).putLabelsItem("spring", "true") - .putLabelsItem("k8s", "true")) - .spec(new V1ServiceSpec().loadBalancerIP("1.1.1.1").type("ClusterIP")).status(new V1ServiceStatus()); + .metadata(new V1ObjectMeta().name("test-svc-3") + .namespace(NAMESPACE) + .putLabelsItem("spring", "true") + .putLabelsItem("k8s", "true")) + .spec(new V1ServiceSpec().loadBalancerIP("1.1.1.1").type("ClusterIP")) + .status(new V1ServiceStatus()); private static final V1Endpoints TEST_ENDPOINTS = new V1Endpoints() - .metadata(new V1ObjectMeta().name("test-svc-3").namespace(NAMESPACE)) - .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(8080).name("http")) - .addAddressesItem(new V1EndpointAddress().ip("2.2.2.2") - .targetRef(new V1ObjectReferenceBuilder().withUid("uid2").build()))); + .metadata(new V1ObjectMeta().name("test-svc-3").namespace(NAMESPACE)) + .addSubsetsItem(new V1EndpointSubset().addPortsItem(new CoreV1EndpointPort().port(8080).name("http")) + .addAddressesItem(new V1EndpointAddress().ip("2.2.2.2") + .targetRef(new V1ObjectReferenceBuilder().withUid("uid2").build()))); @Autowired private WebTestClient webTestClient; @@ -92,8 +95,11 @@ void instanceDeprecated() { TEST_SERVICE.getMetadata().getName(), TEST_ENDPOINTS.getSubsets().get(0).getAddresses().get(0).getIp(), TEST_ENDPOINTS.getSubsets().get(0).getPorts().get(0).getPort(), metadata, false, TEST_SERVICE.getMetadata().getNamespace(), null); - webTestClient.get().uri("/app/test-svc-3/uid2").exchange().expectBody(DefaultKubernetesServiceInstance.class) - .isEqualTo(kubernetesServiceInstance); + webTestClient.get() + .uri("/app/test-svc-3/uid2") + .exchange() + .expectBody(DefaultKubernetesServiceInstance.class) + .isEqualTo(kubernetesServiceInstance); } @Test @@ -110,8 +116,11 @@ void instance() { TEST_SERVICE.getMetadata().getName(), TEST_ENDPOINTS.getSubsets().get(0).getAddresses().get(0).getIp(), TEST_ENDPOINTS.getSubsets().get(0).getPorts().get(0).getPort(), metadata, false, TEST_SERVICE.getMetadata().getNamespace(), null); - webTestClient.get().uri("/apps/test-svc-3/uid2").exchange().expectBody(DefaultKubernetesServiceInstance.class) - .isEqualTo(kubernetesServiceInstance); + webTestClient.get() + .uri("/apps/test-svc-3/uid2") + .exchange() + .expectBody(DefaultKubernetesServiceInstance.class) + .isEqualTo(kubernetesServiceInstance); } @TestConfiguration diff --git a/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/ConfigServerBootstrapper.java b/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/ConfigServerBootstrapper.java index 88b9c2c254..e078d9b67a 100644 --- a/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/ConfigServerBootstrapper.java +++ b/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/ConfigServerBootstrapper.java @@ -74,12 +74,12 @@ public List apply(String serviceId, Binder binder, BindHandler private KubernetesConfigServerInstanceProvider getInstanceProvider(Binder binder, BindHandler bindHandler) { KubernetesDiscoveryProperties kubernetesDiscoveryProperties = binder - .bind(KubernetesDiscoveryProperties.PREFIX, Bindable.of(KubernetesDiscoveryProperties.class), - bindHandler) - .orElseGet(() -> KubernetesDiscoveryProperties.DEFAULT); + .bind(KubernetesDiscoveryProperties.PREFIX, Bindable.of(KubernetesDiscoveryProperties.class), + bindHandler) + .orElseGet(() -> KubernetesDiscoveryProperties.DEFAULT); KubernetesDiscoveryClientBlockingAutoConfiguration autoConfiguration = new KubernetesDiscoveryClientBlockingAutoConfiguration(); DiscoveryClient discoveryClient = autoConfiguration - .kubernetesDiscoveryClient(autoConfiguration.restTemplateBuilder(), kubernetesDiscoveryProperties); + .kubernetesDiscoveryClient(autoConfiguration.restTemplateBuilder(), kubernetesDiscoveryProperties); return discoveryClient::getInstances; } diff --git a/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/KubernetesCatalogWatch.java b/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/KubernetesCatalogWatch.java index 05a63bb1a3..5cf264566c 100644 --- a/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/KubernetesCatalogWatch.java +++ b/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/KubernetesCatalogWatch.java @@ -65,7 +65,7 @@ public void setApplicationEventPublisher(ApplicationEventPublisher publisher) { public void catalogServicesWatch() { try { List currentState = restTemplate.exchange("/state", HttpMethod.GET, null, TYPE) - .getBody(); + .getBody(); if (!catalogState.get().equals(currentState)) { LOG.debug(() -> "Received update from kubernetes discovery http client: " + currentState); diff --git a/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryClient.java b/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryClient.java index 815ac43e18..60a128f096 100644 --- a/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryClient.java +++ b/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryClient.java @@ -71,8 +71,8 @@ public String description() { @Override public List getInstances(String serviceId) { DefaultKubernetesServiceInstance[] responseBody = rest - .getForEntity(discoveryServerUrl + "/apps/" + serviceId, DefaultKubernetesServiceInstance[].class) - .getBody(); + .getForEntity(discoveryServerUrl + "/apps/" + serviceId, DefaultKubernetesServiceInstance[].class) + .getBody(); if (responseBody != null && responseBody.length > 0) { return Arrays.stream(responseBody).filter(this::matchNamespaces).collect(Collectors.toList()); } diff --git a/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryClientAutoConfiguration.java b/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryClientAutoConfiguration.java index a6b2aa73d7..cf558be02f 100644 --- a/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryClientAutoConfiguration.java +++ b/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryClientAutoConfiguration.java @@ -78,7 +78,7 @@ public DiscoveryClient kubernetesDiscoveryClient(RestTemplate restTemplate, public InitializingBean indicatorInitializer(ApplicationEventPublisher applicationEventPublisher, ApplicationContext applicationContext) { return () -> applicationEventPublisher - .publishEvent(new InstanceRegisteredEvent<>(applicationContext.getId(), null)); + .publishEvent(new InstanceRegisteredEvent<>(applicationContext.getId(), null)); } diff --git a/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/KubernetesReactiveDiscoveryClient.java b/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/KubernetesReactiveDiscoveryClient.java index a5d346e65a..b5fd31bcbd 100644 --- a/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/KubernetesReactiveDiscoveryClient.java +++ b/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/KubernetesReactiveDiscoveryClient.java @@ -58,15 +58,17 @@ public String description() { @Override @Cacheable("serviceinstances") public Flux getInstances(String serviceId) { - return webClient.get().uri("/apps/" + serviceId) - .exchangeToFlux(clientResponse -> clientResponse.bodyToFlux(DefaultKubernetesServiceInstance.class)); + return webClient.get() + .uri("/apps/" + serviceId) + .exchangeToFlux(clientResponse -> clientResponse.bodyToFlux(DefaultKubernetesServiceInstance.class)); } @Override @Cacheable("services") public Flux getServices() { - return webClient.get().uri("/apps") - .exchangeToFlux(clientResponse -> clientResponse.bodyToFlux(Service.class).map(Service::name)); + return webClient.get() + .uri("/apps") + .exchangeToFlux(clientResponse -> clientResponse.bodyToFlux(Service.class).map(Service::name)); } } diff --git a/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/ConfigServerBootstrapperTests.java b/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/ConfigServerBootstrapperTests.java index 421afc4be6..03f4018410 100644 --- a/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/ConfigServerBootstrapperTests.java +++ b/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/ConfigServerBootstrapperTests.java @@ -82,17 +82,17 @@ void beforeAll() throws JsonProcessingException { }] """.formatted(wireMockServer.port(), wireMockServer.baseUrl()); - stubFor(get("/apps/spring-cloud-kubernetes-configserver").willReturn( - aResponse().withStatus(200).withBody(appsName).withHeader("content-type", "application/json"))); + stubFor(get("/apps/spring-cloud-kubernetes-configserver") + .willReturn(aResponse().withStatus(200).withBody(appsName).withHeader("content-type", "application/json"))); Environment environment = new Environment("test", "default"); Map properties = new HashMap<>(); properties.put("hello", "world"); PropertySource p = new PropertySource("p1", properties); environment.add(p); ObjectMapper objectMapper = new ObjectMapper(); - stubFor(get("/application/default") - .willReturn(aResponse().withStatus(200).withBody(objectMapper.writeValueAsString(environment)) - .withHeader("content-type", "application/json"))); + stubFor(get("/application/default").willReturn(aResponse().withStatus(200) + .withBody(objectMapper.writeValueAsString(environment)) + .withHeader("content-type", "application/json"))); } @AfterEach @@ -109,7 +109,7 @@ void testBootstrapper() { SpringApplicationBuilder setup(String... env) { SpringApplicationBuilder builder = new SpringApplicationBuilder(TestConfig.class) - .properties(addDefaultEnv(env)); + .properties(addDefaultEnv(env)); builder.addBootstrapRegistryInitializer(new ConfigServerBootstrapper()); return builder; } diff --git a/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesCatalogWatchAutoConfigurationTests.java b/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesCatalogWatchAutoConfigurationTests.java index 92fd404956..369ababad3 100644 --- a/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesCatalogWatchAutoConfigurationTests.java +++ b/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesCatalogWatchAutoConfigurationTests.java @@ -152,10 +152,10 @@ void disableHttpDiscoveryClientCatalogWatcher() { private void setup(String... properties) { applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(KubernetesCatalogWatchAutoConfiguration.class, - KubernetesDiscoveryClientBlockingAutoConfiguration.class, - KubernetesDiscoveryClientReactiveAutoConfiguration.class)) - .withPropertyValues(properties); + .withConfiguration(AutoConfigurations.of(KubernetesCatalogWatchAutoConfiguration.class, + KubernetesDiscoveryClientBlockingAutoConfiguration.class, + KubernetesDiscoveryClientReactiveAutoConfiguration.class)) + .withPropertyValues(properties); } } diff --git a/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesCatalogWatchTests.java b/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesCatalogWatchTests.java index 689a07e137..32fc9d283e 100644 --- a/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesCatalogWatchTests.java +++ b/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesCatalogWatchTests.java @@ -48,10 +48,10 @@ class KubernetesCatalogWatchTests { private WireMockServer wireMockServer; private static final ArgumentCaptor HEARTBEAT_EVENT_ARGUMENT_CAPTOR = ArgumentCaptor - .forClass(HeartbeatEvent.class); + .forClass(HeartbeatEvent.class); private static final ApplicationEventPublisher APPLICATION_EVENT_PUBLISHER = Mockito - .mock(ApplicationEventPublisher.class); + .mock(ApplicationEventPublisher.class); @AfterEach void afterEach() { @@ -67,7 +67,7 @@ void testSingleCycleSameAsCurrentState() { wireMockServer.start(); WireMock.configureFor(wireMockServer.port()); stubFor(get("/state") - .willReturn(aResponse().withStatus(200).withBody(body).withHeader("content-type", "application/json"))); + .willReturn(aResponse().withStatus(200).withBody(body).withHeader("content-type", "application/json"))); KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, true, Set.of(), true, 60, false, null, Set.of(), Map.of(), null, KubernetesDiscoveryProperties.Metadata.DEFAULT, 0, false, false, @@ -99,7 +99,7 @@ void testSingleCycleDifferentCurrentState() { wireMockServer.start(); WireMock.configureFor(wireMockServer.port()); stubFor(get("/state") - .willReturn(aResponse().withStatus(200).withBody(body).withHeader("content-type", "application/json"))); + .willReturn(aResponse().withStatus(200).withBody(body).withHeader("content-type", "application/json"))); KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, true, Set.of(), true, 60, false, null, Set.of(), Map.of(), null, KubernetesDiscoveryProperties.Metadata.DEFAULT, 0, false, false, @@ -147,8 +147,8 @@ void testTwoCyclesDifferentStates() { wireMockServer = new WireMockServer(options().dynamicPort()); wireMockServer.start(); WireMock.configureFor(wireMockServer.port()); - stubFor(get("/state").willReturn( - aResponse().withStatus(200).withBody(bodyOne).withHeader("content-type", "application/json"))); + stubFor(get("/state") + .willReturn(aResponse().withStatus(200).withBody(bodyOne).withHeader("content-type", "application/json"))); KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, true, Set.of(), true, 60, false, null, Set.of(), Map.of(), null, KubernetesDiscoveryProperties.Metadata.DEFAULT, 0, false, false, @@ -169,8 +169,8 @@ void testTwoCyclesDifferentStates() { Assertions.assertEquals(stateOne.get(0).namespace(), "namespaceA"); // second call - stubFor(get("/state").willReturn( - aResponse().withStatus(200).withBody(bodyTwo).withHeader("content-type", "application/json"))); + stubFor(get("/state") + .willReturn(aResponse().withStatus(200).withBody(bodyTwo).withHeader("content-type", "application/json"))); catalogWatch.catalogServicesWatch(); diff --git a/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryAutoConfigurationTests.java b/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryAutoConfigurationTests.java index b0f9ebdd18..a1f672ee8c 100644 --- a/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryAutoConfigurationTests.java +++ b/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryAutoConfigurationTests.java @@ -272,15 +272,16 @@ private void setupWithFilteredClassLoader(Class cls, String... properties) { if (cls != null) { applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(KubernetesDiscoveryClientBlockingAutoConfiguration.class, - KubernetesDiscoveryClientReactiveAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(cls)).withPropertyValues(properties); + .withConfiguration(AutoConfigurations.of(KubernetesDiscoveryClientBlockingAutoConfiguration.class, + KubernetesDiscoveryClientReactiveAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(cls)) + .withPropertyValues(properties); } else { applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(KubernetesDiscoveryClientBlockingAutoConfiguration.class, - KubernetesDiscoveryClientReactiveAutoConfiguration.class)) - .withPropertyValues(properties); + .withConfiguration(AutoConfigurations.of(KubernetesDiscoveryClientBlockingAutoConfiguration.class, + KubernetesDiscoveryClientReactiveAutoConfiguration.class)) + .withPropertyValues(properties); } } diff --git a/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryClientAutoConfigurationTests.java b/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryClientAutoConfigurationTests.java index 54fb77860e..b2fcee15c4 100644 --- a/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryClientAutoConfigurationTests.java +++ b/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryClientAutoConfigurationTests.java @@ -32,58 +32,59 @@ */ class KubernetesDiscoveryClientAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( - AutoConfigurations.of(UtilAutoConfiguration.class, ReactiveCommonsClientAutoConfiguration.class, - KubernetesDiscoveryClientReactiveAutoConfiguration.class, - KubernetesDiscoveryClientBlockingAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(UtilAutoConfiguration.class, + ReactiveCommonsClientAutoConfiguration.class, KubernetesDiscoveryClientReactiveAutoConfiguration.class, + KubernetesDiscoveryClientBlockingAutoConfiguration.class)); @Test void shouldWorkWithDefaults() { contextRunner - .withPropertyValues("spring.main.cloud-platform=KUBERNETES", - "spring.cloud.kubernetes.discovery.discovery-server-url=http://k8sdiscoveryserver") - .withClassLoader(new FilteredClassLoader("org.springframework.web.reactive")).run(context -> { - assertThat(context).hasSingleBean(KubernetesDiscoveryClient.class); - assertThat(context).doesNotHaveBean(KubernetesReactiveDiscoveryClient.class); - assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class); - }); + .withPropertyValues("spring.main.cloud-platform=KUBERNETES", + "spring.cloud.kubernetes.discovery.discovery-server-url=http://k8sdiscoveryserver") + .withClassLoader(new FilteredClassLoader("org.springframework.web.reactive")) + .run(context -> { + assertThat(context).hasSingleBean(KubernetesDiscoveryClient.class); + assertThat(context).doesNotHaveBean(KubernetesReactiveDiscoveryClient.class); + assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class); + }); } @Test void shouldNotHaveDiscoveryClientWhenDiscoveryDisabled() { contextRunner - .withPropertyValues("spring.cloud.discovery.enabled=false", - "spring.cloud.kubernetes.discovery.discovery-server-url=http://k8sdiscoveryserver") - .run(context -> { - assertThat(context).doesNotHaveBean(KubernetesReactiveDiscoveryClient.class); - assertThat(context).doesNotHaveBean(KubernetesDiscoveryClient.class); - assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class); - }); + .withPropertyValues("spring.cloud.discovery.enabled=false", + "spring.cloud.kubernetes.discovery.discovery-server-url=http://k8sdiscoveryserver") + .run(context -> { + assertThat(context).doesNotHaveBean(KubernetesReactiveDiscoveryClient.class); + assertThat(context).doesNotHaveBean(KubernetesDiscoveryClient.class); + assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class); + }); } @Test void shouldNotHaveDiscoveryClientWhenKubernetesDiscoveryDisabled() { contextRunner - .withPropertyValues("spring.cloud.kubernetes.discovery.enabled=false", - "spring.cloud.kubernetes.discovery.discovery-server-url=http://k8sdiscoveryserver") - .run(context -> { - assertThat(context).doesNotHaveBean(KubernetesReactiveDiscoveryClient.class); - assertThat(context).doesNotHaveBean(KubernetesDiscoveryClient.class); - assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class); - }); + .withPropertyValues("spring.cloud.kubernetes.discovery.enabled=false", + "spring.cloud.kubernetes.discovery.discovery-server-url=http://k8sdiscoveryserver") + .run(context -> { + assertThat(context).doesNotHaveBean(KubernetesReactiveDiscoveryClient.class); + assertThat(context).doesNotHaveBean(KubernetesDiscoveryClient.class); + assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class); + }); } @Test void shouldHaveReactiveDiscoveryClient() { contextRunner - .withPropertyValues("spring.main.cloud-platform=KUBERNETES", - "spring.cloud.discovery.blocking.enabled=false", - "spring.cloud.kubernetes.discovery.discovery-server-url=http://k8sdiscoveryserver") - .run(context -> { - assertThat(context).hasSingleBean(KubernetesReactiveDiscoveryClient.class); - assertThat(context).doesNotHaveBean(KubernetesDiscoveryClient.class); - assertThat(context).hasSingleBean(ReactiveDiscoveryClientHealthIndicator.class); - }); + .withPropertyValues("spring.main.cloud-platform=KUBERNETES", + "spring.cloud.discovery.blocking.enabled=false", + "spring.cloud.kubernetes.discovery.discovery-server-url=http://k8sdiscoveryserver") + .run(context -> { + assertThat(context).hasSingleBean(KubernetesReactiveDiscoveryClient.class); + assertThat(context).doesNotHaveBean(KubernetesDiscoveryClient.class); + assertThat(context).hasSingleBean(ReactiveDiscoveryClientHealthIndicator.class); + }); } @Test @@ -105,12 +106,13 @@ void shouldNotHaveDiscoveryClientWhenKubernetesDisabled() { @Test void worksWithoutActuator() { contextRunner - .withPropertyValues("spring.main.cloud-platform=KUBERNETES", - "spring.cloud.kubernetes.discovery.discovery-server-url=http://k8sdiscoveryserver") - .withClassLoader(new FilteredClassLoader("org.springframework.boot.actuate")).run(context -> { - assertThat(context).hasSingleBean(KubernetesReactiveDiscoveryClient.class); - assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class); - }); + .withPropertyValues("spring.main.cloud-platform=KUBERNETES", + "spring.cloud.kubernetes.discovery.discovery-server-url=http://k8sdiscoveryserver") + .withClassLoader(new FilteredClassLoader("org.springframework.boot.actuate")) + .run(context -> { + assertThat(context).hasSingleBean(KubernetesReactiveDiscoveryClient.class); + assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class); + }); } } diff --git a/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryClientTests.java b/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryClientTests.java index 2f97f56e2c..a6eafbc8db 100644 --- a/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryClientTests.java +++ b/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryClientTests.java @@ -105,11 +105,11 @@ static void beforeAll() { wireMockServer.start(); WireMock.configureFor(wireMockServer.port()); stubFor(get("/apps") - .willReturn(aResponse().withStatus(200).withBody(APPS).withHeader("content-type", "application/json"))); + .willReturn(aResponse().withStatus(200).withBody(APPS).withHeader("content-type", "application/json"))); stubFor(get("/apps/test-svc-3").willReturn( aResponse().withStatus(200).withBody(APPS_NAME).withHeader("content-type", "application/json"))); stubFor(get("/apps/does-not-exist") - .willReturn(aResponse().withStatus(200).withBody("").withHeader("content-type", "application/json"))); + .willReturn(aResponse().withStatus(200).withBody("").withHeader("content-type", "application/json"))); } @Test @@ -158,7 +158,7 @@ void getInstancesFilteredByNamespaces(Set namespaces, String serviceId, wireMockServer.baseUrl()); KubernetesDiscoveryClient discoveryClient = new KubernetesDiscoveryClient(rest, properties); assertThat(discoveryClient.getInstances(serviceId)).map(ServiceInstance::getInstanceId) - .containsExactlyInAnyOrderElementsOf(expectedInstances); + .containsExactlyInAnyOrderElementsOf(expectedInstances); } private static Stream servicesFilteredByNamespacesSource() { diff --git a/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesReactiveDiscoveryClientTests.java b/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesReactiveDiscoveryClientTests.java index 91b509baca..7f267cd87b 100644 --- a/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesReactiveDiscoveryClientTests.java +++ b/spring-cloud-kubernetes-discovery/src/test/java/org/springframework/cloud/kubernetes/discovery/KubernetesReactiveDiscoveryClientTests.java @@ -98,11 +98,11 @@ static void beforeAll() { wireMockServer.start(); WireMock.configureFor(wireMockServer.port()); stubFor(get("/apps") - .willReturn(aResponse().withStatus(200).withBody(APPS).withHeader("content-type", "application/json"))); + .willReturn(aResponse().withStatus(200).withBody(APPS).withHeader("content-type", "application/json"))); stubFor(get("/apps/test-svc-3").willReturn( aResponse().withStatus(200).withBody(APPS_NAME).withHeader("content-type", "application/json"))); stubFor(get("/apps/does-not-exist") - .willReturn(aResponse().withStatus(200).withBody("").withHeader("content-type", "application/json"))); + .willReturn(aResponse().withStatus(200).withBody("").withHeader("content-type", "application/json"))); } @Test @@ -129,9 +129,9 @@ void getServices() { metadata.put("k8s", "true"); StepVerifier.create(discoveryClient.getInstances("test-svc-3")) - .expectNext(new DefaultKubernetesServiceInstance("uid2", "test-svc-3", "2.2.2.2", 8080, metadata, false, - "namespace1", null, null)) - .verifyComplete(); + .expectNext(new DefaultKubernetesServiceInstance("uid2", "test-svc-3", "2.2.2.2", 8080, metadata, false, + "namespace1", null, null)) + .verifyComplete(); } } diff --git a/spring-cloud-kubernetes-fabric8-autoconfig/src/main/java/org/springframework/cloud/kubernetes/fabric8/Fabric8AutoConfiguration.java b/spring-cloud-kubernetes-fabric8-autoconfig/src/main/java/org/springframework/cloud/kubernetes/fabric8/Fabric8AutoConfiguration.java index 1403d54a17..509be0d32b 100644 --- a/spring-cloud-kubernetes-fabric8-autoconfig/src/main/java/org/springframework/cloud/kubernetes/fabric8/Fabric8AutoConfiguration.java +++ b/spring-cloud-kubernetes-fabric8-autoconfig/src/main/java/org/springframework/cloud/kubernetes/fabric8/Fabric8AutoConfiguration.java @@ -61,41 +61,40 @@ private static Long orDurationLong(Duration left, Long right) { public Config kubernetesClientConfig(KubernetesClientProperties kubernetesClientProperties) { Config base = Config.autoConfigure(null); ConfigBuilder builder = new ConfigBuilder(base) - // Only set values that have been explicitly specified - .withMasterUrl(or(kubernetesClientProperties.masterUrl(), base.getMasterUrl())) - .withApiVersion(or(kubernetesClientProperties.apiVersion(), base.getApiVersion())) - .withNamespace(or(kubernetesClientProperties.namespace(), base.getNamespace())) - .withUsername(or(kubernetesClientProperties.username(), base.getUsername())) - .withPassword(or(kubernetesClientProperties.password(), base.getPassword())) - - .withOauthToken(or(kubernetesClientProperties.oauthToken(), base.getOauthToken())) - .withCaCertFile(or(kubernetesClientProperties.caCertFile(), base.getCaCertFile())) - .withCaCertData(or(kubernetesClientProperties.caCertData(), base.getCaCertData())) - - .withClientKeyFile(or(kubernetesClientProperties.clientKeyFile(), base.getClientKeyFile())) - .withClientKeyData(or(kubernetesClientProperties.clientKeyData(), base.getClientKeyData())) - - .withClientCertFile(or(kubernetesClientProperties.clientCertFile(), base.getClientCertFile())) - .withClientCertData(or(kubernetesClientProperties.clientCertData(), base.getClientCertData())) - - // No magic is done for the properties below so we leave them as is. - .withClientKeyAlgo(or(kubernetesClientProperties.clientKeyAlgo(), base.getClientKeyAlgo())) - .withClientKeyPassphrase( - or(kubernetesClientProperties.clientKeyPassphrase(), base.getClientKeyPassphrase())) - .withConnectionTimeout( - orDurationInt(kubernetesClientProperties.connectionTimeout(), base.getConnectionTimeout())) - .withRequestTimeout( - orDurationInt(kubernetesClientProperties.requestTimeout(), base.getRequestTimeout())) - .withTrustCerts(or(kubernetesClientProperties.trustCerts(), base.isTrustCerts())) - .withHttpProxy(or(kubernetesClientProperties.httpProxy(), base.getHttpProxy())) - .withHttpsProxy(or(kubernetesClientProperties.httpsProxy(), base.getHttpsProxy())) - .withProxyUsername(or(kubernetesClientProperties.proxyUsername(), base.getProxyUsername())) - .withProxyPassword(or(kubernetesClientProperties.proxyPassword(), base.getProxyPassword())) - .withNoProxy(or(kubernetesClientProperties.noProxy(), base.getNoProxy())) - // Disable the built-in retry functionality since Spring Cloud Kubernetes - // provides it - // See https://github.com/fabric8io/kubernetes-client/issues/4863 - .withRequestRetryBackoffLimit(0); + // Only set values that have been explicitly specified + .withMasterUrl(or(kubernetesClientProperties.masterUrl(), base.getMasterUrl())) + .withApiVersion(or(kubernetesClientProperties.apiVersion(), base.getApiVersion())) + .withNamespace(or(kubernetesClientProperties.namespace(), base.getNamespace())) + .withUsername(or(kubernetesClientProperties.username(), base.getUsername())) + .withPassword(or(kubernetesClientProperties.password(), base.getPassword())) + + .withOauthToken(or(kubernetesClientProperties.oauthToken(), base.getOauthToken())) + .withCaCertFile(or(kubernetesClientProperties.caCertFile(), base.getCaCertFile())) + .withCaCertData(or(kubernetesClientProperties.caCertData(), base.getCaCertData())) + + .withClientKeyFile(or(kubernetesClientProperties.clientKeyFile(), base.getClientKeyFile())) + .withClientKeyData(or(kubernetesClientProperties.clientKeyData(), base.getClientKeyData())) + + .withClientCertFile(or(kubernetesClientProperties.clientCertFile(), base.getClientCertFile())) + .withClientCertData(or(kubernetesClientProperties.clientCertData(), base.getClientCertData())) + + // No magic is done for the properties below so we leave them as is. + .withClientKeyAlgo(or(kubernetesClientProperties.clientKeyAlgo(), base.getClientKeyAlgo())) + .withClientKeyPassphrase( + or(kubernetesClientProperties.clientKeyPassphrase(), base.getClientKeyPassphrase())) + .withConnectionTimeout( + orDurationInt(kubernetesClientProperties.connectionTimeout(), base.getConnectionTimeout())) + .withRequestTimeout(orDurationInt(kubernetesClientProperties.requestTimeout(), base.getRequestTimeout())) + .withTrustCerts(or(kubernetesClientProperties.trustCerts(), base.isTrustCerts())) + .withHttpProxy(or(kubernetesClientProperties.httpProxy(), base.getHttpProxy())) + .withHttpsProxy(or(kubernetesClientProperties.httpsProxy(), base.getHttpsProxy())) + .withProxyUsername(or(kubernetesClientProperties.proxyUsername(), base.getProxyUsername())) + .withProxyPassword(or(kubernetesClientProperties.proxyPassword(), base.getProxyPassword())) + .withNoProxy(or(kubernetesClientProperties.noProxy(), base.getNoProxy())) + // Disable the built-in retry functionality since Spring Cloud Kubernetes + // provides it + // See https://github.com/fabric8io/kubernetes-client/issues/4863 + .withRequestRetryBackoffLimit(0); String userAgent = or(base.getUserAgent(), KubernetesClientProperties.DEFAULT_USER_AGENT); if (!kubernetesClientProperties.userAgent().equals(KubernetesClientProperties.DEFAULT_USER_AGENT)) { diff --git a/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/Fabric8HealthIndicatorDisabledTest.java b/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/Fabric8HealthIndicatorDisabledTest.java index d17daef597..154222e590 100644 --- a/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/Fabric8HealthIndicatorDisabledTest.java +++ b/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/Fabric8HealthIndicatorDisabledTest.java @@ -54,9 +54,15 @@ static void setUpBeforeClass() { @Test void healthEndpointShouldContainKubernetes() { - this.webClient.get().uri("http://localhost:{port}/actuator/health", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("components.kubernetes").doesNotExist(); + this.webClient.get() + .uri("http://localhost:{port}/actuator/health", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("components.kubernetes") + .doesNotExist(); } } diff --git a/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/Fabric8InsideHealthIndicatorTest.java b/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/Fabric8InsideHealthIndicatorTest.java index 80d05daa2e..fd623d8273 100644 --- a/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/Fabric8InsideHealthIndicatorTest.java +++ b/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/Fabric8InsideHealthIndicatorTest.java @@ -74,17 +74,31 @@ class Fabric8InsideHealthIndicatorTest { */ @Test void test() { - this.webClient.get().uri("http://localhost:{port}/actuator/health", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("components.stubKubernetes.status").isEqualTo("UP") - .jsonPath("components.stubKubernetes.details.nodeName").isEqualTo("nodeName") - .jsonPath("components.stubKubernetes.details.podIp").isEqualTo("10.1.1.1") - .jsonPath("components.stubKubernetes.details.hostIp").isEqualTo("192.160.10.3") - .jsonPath("components.stubKubernetes.details.namespace").isEqualTo("namespace") - .jsonPath("components.stubKubernetes.details.podName").isEqualTo("pod") - .jsonPath("components.stubKubernetes.details.serviceAccount").isEqualTo("serviceAccountName") - .jsonPath("components.stubKubernetes.details.inside").isEqualTo("true") - .jsonPath("components.stubKubernetes.details.labels.labelName").isEqualTo("labelValue"); + this.webClient.get() + .uri("http://localhost:{port}/actuator/health", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("components.stubKubernetes.status") + .isEqualTo("UP") + .jsonPath("components.stubKubernetes.details.nodeName") + .isEqualTo("nodeName") + .jsonPath("components.stubKubernetes.details.podIp") + .isEqualTo("10.1.1.1") + .jsonPath("components.stubKubernetes.details.hostIp") + .isEqualTo("192.160.10.3") + .jsonPath("components.stubKubernetes.details.namespace") + .isEqualTo("namespace") + .jsonPath("components.stubKubernetes.details.podName") + .isEqualTo("pod") + .jsonPath("components.stubKubernetes.details.serviceAccount") + .isEqualTo("serviceAccountName") + .jsonPath("components.stubKubernetes.details.inside") + .isEqualTo("true") + .jsonPath("components.stubKubernetes.details.labels.labelName") + .isEqualTo("labelValue"); } private static Pod stubPod() { @@ -97,9 +111,14 @@ private static Pod stubPod() { spec.setServiceAccountName("serviceAccountName"); spec.setNodeName("nodeName"); - return new PodBuilder().withNewMetadata().withName("pod").withNamespace("namespace") - .withLabels(Collections.singletonMap("labelName", "labelValue")).endMetadata().withStatus(status) - .withSpec(spec).build(); + return new PodBuilder().withNewMetadata() + .withName("pod") + .withNamespace("namespace") + .withLabels(Collections.singletonMap("labelName", "labelValue")) + .endMetadata() + .withStatus(status) + .withSpec(spec) + .build(); } @Configuration diff --git a/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/Fabric8InsideInfoContributorTest.java b/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/Fabric8InsideInfoContributorTest.java index 5d11e0168e..fff2ecfee6 100644 --- a/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/Fabric8InsideInfoContributorTest.java +++ b/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/Fabric8InsideInfoContributorTest.java @@ -66,12 +66,27 @@ class Fabric8InsideInfoContributorTest { */ @Test void test() { - this.webClient.get().uri("http://localhost:{port}/actuator/info", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody().jsonPath("kubernetes.nodeName").isEqualTo("nodeName") - .jsonPath("kubernetes.podIp").isEqualTo("10.1.1.1").jsonPath("kubernetes.hostIp") - .isEqualTo("192.160.10.3").jsonPath("kubernetes.namespace").isEqualTo("namespace") - .jsonPath("kubernetes.podName").isEqualTo("pod").jsonPath("kubernetes.serviceAccount") - .isEqualTo("serviceAccountName").jsonPath("kubernetes.inside").isEqualTo("true"); + this.webClient.get() + .uri("http://localhost:{port}/actuator/info", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("kubernetes.nodeName") + .isEqualTo("nodeName") + .jsonPath("kubernetes.podIp") + .isEqualTo("10.1.1.1") + .jsonPath("kubernetes.hostIp") + .isEqualTo("192.160.10.3") + .jsonPath("kubernetes.namespace") + .isEqualTo("namespace") + .jsonPath("kubernetes.podName") + .isEqualTo("pod") + .jsonPath("kubernetes.serviceAccount") + .isEqualTo("serviceAccountName") + .jsonPath("kubernetes.inside") + .isEqualTo("true"); } @@ -85,8 +100,13 @@ private static Pod stubPod() { spec.setServiceAccountName("serviceAccountName"); spec.setNodeName("nodeName"); - return new PodBuilder().withNewMetadata().withName("pod").withNamespace("namespace").endMetadata() - .withStatus(status).withSpec(spec).build(); + return new PodBuilder().withNewMetadata() + .withName("pod") + .withNamespace("namespace") + .endMetadata() + .withStatus(status) + .withSpec(spec) + .build(); } @Configuration diff --git a/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/Fabric8NotInsideHealthIndicatorTest.java b/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/Fabric8NotInsideHealthIndicatorTest.java index 43ce5c8323..a328c70526 100644 --- a/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/Fabric8NotInsideHealthIndicatorTest.java +++ b/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/Fabric8NotInsideHealthIndicatorTest.java @@ -77,10 +77,17 @@ static void afterClass() { @Test void healthEndpointShouldContainKubernetes() { - this.webClient.get().uri("http://localhost:{port}/actuator/health", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("components.kubernetes.status").isEqualTo("UP") - .jsonPath("components.kubernetes.details.inside").isEqualTo("false"); + this.webClient.get() + .uri("http://localhost:{port}/actuator/health", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("components.kubernetes.status") + .isEqualTo("UP") + .jsonPath("components.kubernetes.details.inside") + .isEqualTo("false"); } diff --git a/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/Fabric8NotInsideInfoContributorTest.java b/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/Fabric8NotInsideInfoContributorTest.java index e7cda52b79..104350ef09 100644 --- a/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/Fabric8NotInsideInfoContributorTest.java +++ b/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/Fabric8NotInsideInfoContributorTest.java @@ -50,8 +50,15 @@ class Fabric8NotInsideInfoContributorTest { */ @Test void infoEndpointShouldContainKubernetes() { - this.webClient.get().uri("http://localhost:{port}/actuator/info", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody().jsonPath("kubernetes.inside").isEqualTo("false"); + this.webClient.get() + .uri("http://localhost:{port}/actuator/info", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("kubernetes.inside") + .isEqualTo("false"); } } diff --git a/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/fabric8/Fabric8UtilsMockTests.java b/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/fabric8/Fabric8UtilsMockTests.java index 2e717d2fe3..0f7cbdd868 100644 --- a/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/fabric8/Fabric8UtilsMockTests.java +++ b/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/fabric8/Fabric8UtilsMockTests.java @@ -42,7 +42,7 @@ void testNamespaceFromClient() { @Test void testNamespaceResolutionFailed() { assertThatThrownBy(() -> Fabric8Utils.getApplicationNamespace(mockClient, "", "target", null)) - .isInstanceOf(NamespaceResolutionFailedException.class); + .isInstanceOf(NamespaceResolutionFailedException.class); } } diff --git a/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/fabric8/profile/Fabric8ProfileEnvironmentPostProcessorTests.java b/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/fabric8/profile/Fabric8ProfileEnvironmentPostProcessorTests.java index b60de238e7..7388dfa0d5 100644 --- a/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/fabric8/profile/Fabric8ProfileEnvironmentPostProcessorTests.java +++ b/spring-cloud-kubernetes-fabric8-autoconfig/src/test/java/org/springframework/cloud/kubernetes/fabric8/profile/Fabric8ProfileEnvironmentPostProcessorTests.java @@ -33,8 +33,9 @@ class Fabric8ProfileEnvironmentPostProcessorTests { @Test void whenKubernetesEnvironmentAndNoApiAccessThenProfileEnabled() { ConfigurableApplicationContext context = new SpringApplicationBuilder(App.class) - .web(org.springframework.boot.WebApplicationType.NONE) - .properties("KUBERNETES_SERVICE_HOST=10.0.0.1", "spring.main.cloud-platform=KUBERNETES").run(); + .web(org.springframework.boot.WebApplicationType.NONE) + .properties("KUBERNETES_SERVICE_HOST=10.0.0.1", "spring.main.cloud-platform=KUBERNETES") + .run(); assertThat(context.getEnvironment().getActiveProfiles()).contains(KUBERNETES_PROFILE); } @@ -42,7 +43,8 @@ void whenKubernetesEnvironmentAndNoApiAccessThenProfileEnabled() { @Test void whenNoKubernetesEnvironmentAndNoApiAccessThenNoProfileEnabled() { ConfigurableApplicationContext context = new SpringApplicationBuilder(App.class) - .web(org.springframework.boot.WebApplicationType.NONE).run(); + .web(org.springframework.boot.WebApplicationType.NONE) + .run(); assertThat(context.getEnvironment().getActiveProfiles()).doesNotContain(KUBERNETES_PROFILE); } diff --git a/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapPropertySource.java b/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapPropertySource.java index 77083d9d4f..017fb111f6 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapPropertySource.java +++ b/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapPropertySource.java @@ -48,8 +48,9 @@ public final class Fabric8ConfigMapPropertySource extends SourceDataEntriesProce private static SourceData getSourceData(Fabric8ConfigContext context) { NormalizedSourceType type = context.normalizedSource().type(); - return Optional.ofNullable(STRATEGIES.get(type)).map(x -> x.apply(context)) - .orElseThrow(() -> new IllegalArgumentException("no strategy found for : " + type)); + return Optional.ofNullable(STRATEGIES.get(type)) + .map(x -> x.apply(context)) + .orElseThrow(() -> new IllegalArgumentException("no strategy found for : " + type)); } private static Fabric8ContextToSourceData namedConfigMap() { diff --git a/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapsCache.java b/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapsCache.java index 75c3b93d47..65436eb82f 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapsCache.java +++ b/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapsCache.java @@ -67,8 +67,10 @@ static List byNamespace(KubernetesClient client, String } private static List strippedConfigMaps(List configMaps) { - return configMaps.stream().map(configMap -> new StrippedSourceContainer(configMap.getMetadata().getLabels(), - configMap.getMetadata().getName(), configMap.getData())).collect(Collectors.toList()); + return configMaps.stream() + .map(configMap -> new StrippedSourceContainer(configMap.getMetadata().getLabels(), + configMap.getMetadata().getName(), configMap.getData())) + .collect(Collectors.toList()); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8SecretsCache.java b/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8SecretsCache.java index f6d79685b9..d27b8c7a84 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8SecretsCache.java +++ b/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8SecretsCache.java @@ -67,8 +67,10 @@ static List byNamespace(KubernetesClient client, String } private static List strippedSecrets(List secrets) { - return secrets.stream().map(secret -> new StrippedSourceContainer(secret.getMetadata().getLabels(), - secret.getMetadata().getName(), secret.getData())).collect(Collectors.toList()); + return secrets.stream() + .map(secret -> new StrippedSourceContainer(secret.getMetadata().getLabels(), secret.getMetadata().getName(), + secret.getData())) + .collect(Collectors.toList()); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8SecretsPropertySource.java b/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8SecretsPropertySource.java index bd1472d10f..203b43e192 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8SecretsPropertySource.java +++ b/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8SecretsPropertySource.java @@ -46,8 +46,9 @@ public final class Fabric8SecretsPropertySource extends SecretsPropertySource { private static SourceData getSourceData(Fabric8ConfigContext context) { NormalizedSourceType type = context.normalizedSource().type(); - return Optional.ofNullable(STRATEGIES.get(type)).map(x -> x.apply(context)) - .orElseThrow(() -> new IllegalArgumentException("no strategy found for : " + type)); + return Optional.ofNullable(STRATEGIES.get(type)) + .map(x -> x.apply(context)) + .orElseThrow(() -> new IllegalArgumentException("no strategy found for : " + type)); } private static Fabric8ContextToSourceData namedSecret() { diff --git a/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/reload/Fabric8EventBasedConfigMapChangeDetector.java b/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/reload/Fabric8EventBasedConfigMapChangeDetector.java index fef7de6f60..277fa9865d 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/reload/Fabric8EventBasedConfigMapChangeDetector.java +++ b/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/reload/Fabric8EventBasedConfigMapChangeDetector.java @@ -83,8 +83,10 @@ private void inform() { namespaces.forEach(namespace -> { SharedIndexInformer informer; if (enableReloadFiltering) { - informer = kubernetesClient.configMaps().inNamespace(namespace) - .withLabels(Map.of(ConfigReloadProperties.RELOAD_LABEL_FILTER, "true")).inform(); + informer = kubernetesClient.configMaps() + .inNamespace(namespace) + .withLabels(Map.of(ConfigReloadProperties.RELOAD_LABEL_FILTER, "true")) + .inform(); LOG.debug("added configmap informer for namespace : " + namespace + " with enabled filter"); } else { diff --git a/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/reload/Fabric8EventBasedSecretsChangeDetector.java b/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/reload/Fabric8EventBasedSecretsChangeDetector.java index 325b0ba0be..a98e079c91 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/reload/Fabric8EventBasedSecretsChangeDetector.java +++ b/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/reload/Fabric8EventBasedSecretsChangeDetector.java @@ -91,8 +91,10 @@ private void inform() { namespaces.forEach(namespace -> { SharedIndexInformer informer; if (enableReloadFiltering) { - informer = kubernetesClient.secrets().inNamespace(namespace) - .withLabels(Map.of(ConfigReloadProperties.RELOAD_LABEL_FILTER, "true")).inform(); + informer = kubernetesClient.secrets() + .inNamespace(namespace) + .withLabels(Map.of(ConfigReloadProperties.RELOAD_LABEL_FILTER, "true")) + .inform(); LOG.debug("added secret informer for namespace : " + namespace + " with enabled filter"); } else { diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapEnableRetryWithoutFailFastTest.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapEnableRetryWithoutFailFastTest.java index 4456b0fedd..edbdab8704 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapEnableRetryWithoutFailFastTest.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapEnableRetryWithoutFailFastTest.java @@ -66,7 +66,9 @@ protected void setup(String... env) { ConfigurationPropertiesBindingPostProcessor.class, ConfigurationPropertiesRebinderAutoConfiguration.class, Fabric8BootstrapConfiguration.class, Fabric8RetryBootstrapConfiguration.class, KubernetesBootstrapConfiguration.class) - .web(org.springframework.boot.WebApplicationType.NONE).properties(envArray).run(); + .web(org.springframework.boot.WebApplicationType.NONE) + .properties(envArray) + .run(); } @AfterEach diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsFromFilePathsTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsFromFilePathsTests.java index 0161a06d85..d43af8c2aa 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsFromFilePathsTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsFromFilePathsTests.java @@ -86,37 +86,61 @@ public static void setUpBeforeClass(KubernetesClient mockClient) throws IOExcept @AfterAll public static void teardownAfterClass() { newArrayList(FIRST_FILE_NAME_FULL_PATH, SECOND_FILE_NAME_FULL_PATH, SECOND_FILE_NAME_FULL_PATH, FILES_ROOT_PATH) - .forEach(fn -> { - try { - Files.delete(Paths.get(fn)); - } - catch (IOException ignored) { - } - }); + .forEach(fn -> { + try { + Files.delete(Paths.get(fn)); + } + catch (IOException ignored) { + } + }); } @Test public void greetingInputShouldReturnPropertyFromFirstFile() { - this.webClient.get().uri("/api/greeting").exchange().expectStatus().isOk().expectBody().jsonPath("content") - .isEqualTo("Hello from path!"); + this.webClient.get() + .uri("/api/greeting") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("content") + .isEqualTo("Hello from path!"); } @Test public void farewellInputShouldReturnPropertyFromSecondFile() { - this.webClient.get().uri("/api/farewell").exchange().expectStatus().isOk().expectBody().jsonPath("content") - .isEqualTo("Bye from path!"); + this.webClient.get() + .uri("/api/farewell") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("content") + .isEqualTo("Bye from path!"); } @Test public void morningInputShouldReturnDefaultValue() { - this.webClient.get().uri("/api/morning").exchange().expectStatus().isOk().expectBody().jsonPath("content") - .isEqualTo("Good morning, World!"); + this.webClient.get() + .uri("/api/morning") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("content") + .isEqualTo("Good morning, World!"); } @Test public void bonjourInputShouldReturnPropertyFromDuplicatedFile() { - this.webClient.get().uri("/api/bonjour").exchange().expectStatus().isOk().expectBody().jsonPath("content") - .isEqualTo("Bonjour from path!"); + this.webClient.get() + .uri("/api/bonjour") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("content") + .isEqualTo("Bonjour from path!"); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsMixedTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsMixedTests.java index ffdad69b64..4ec8cbfced 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsMixedTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsMixedTests.java @@ -63,8 +63,11 @@ public static void setUpBeforeClass(KubernetesClient mockClient) throws IOExcept HashMap data = new HashMap<>(); data.put("bean.morning", "Buenos Dias ConfigMap, %s"); - ConfigMap configMap = new ConfigMapBuilder().withNewMetadata().withName(APPLICATION_NAME).endMetadata() - .addToData(data).build(); + ConfigMap configMap = new ConfigMapBuilder().withNewMetadata() + .withName(APPLICATION_NAME) + .endMetadata() + .addToData(data) + .build(); mockClient.configMaps().inNamespace("test").resource(configMap).create(); } @@ -82,20 +85,38 @@ public static void teardownAfterClass() { @Test public void greetingInputShouldReturnPropertyFromFile() { - this.webClient.get().uri("/api/greeting").exchange().expectStatus().isOk().expectBody().jsonPath("content") - .isEqualTo("Hello ConfigMap, World from path"); + this.webClient.get() + .uri("/api/greeting") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("content") + .isEqualTo("Hello ConfigMap, World from path"); } @Test public void farewellInputShouldReturnPropertyFromFile() { - this.webClient.get().uri("/api/farewell").exchange().expectStatus().isOk().expectBody().jsonPath("content") - .isEqualTo("Bye ConfigMap, World from path"); + this.webClient.get() + .uri("/api/farewell") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("content") + .isEqualTo("Bye ConfigMap, World from path"); } @Test public void morningInputShouldReturnPropertyFromApi() { - this.webClient.get().uri("/api/morning").exchange().expectStatus().isOk().expectBody().jsonPath("content") - .isEqualTo("Buenos Dias ConfigMap, World"); + this.webClient.get() + .uri("/api/morning") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("content") + .isEqualTo("Buenos Dias ConfigMap, World"); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsTest.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsTest.java index b51d32e841..ee1093fe90 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsTest.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsTest.java @@ -47,8 +47,10 @@ void afterEach() { @Test public void testConfigMapList() { - mockClient.configMaps().inNamespace("ns1") - .resource(new ConfigMapBuilder().withNewMetadata().withName("empty").endMetadata().build()).create(); + mockClient.configMaps() + .inNamespace("ns1") + .resource(new ConfigMapBuilder().withNewMetadata().withName("empty").endMetadata().build()) + .create(); ConfigMapList configMapList = mockClient.configMaps().inNamespace("ns1").list(); assertThat(configMapList).isNotNull(); @@ -60,8 +62,11 @@ public void testConfigMapList() { @Test void testConfigMapGet() { - ConfigMap configMap = new ConfigMapBuilder().withNewMetadata().withName("reload-example").endMetadata() - .addToData("KEY", "123").build(); + ConfigMap configMap = new ConfigMapBuilder().withNewMetadata() + .withName("reload-example") + .endMetadata() + .addToData("KEY", "123") + .build(); mockClient.configMaps().inNamespace("ns2").resource(configMap).create(); @@ -76,9 +81,11 @@ void testConfigMapGet() { @Test void testConfigMapFromSingleApplicationProperties() { String configMapName = "app-properties-test"; - ConfigMap configMap = new ConfigMapBuilder().withNewMetadata().withName(configMapName).endMetadata() - .addToData("application.properties", ConfigMapTestUtil.readResourceFile("application.properties")) - .build(); + ConfigMap configMap = new ConfigMapBuilder().withNewMetadata() + .withName(configMapName) + .endMetadata() + .addToData("application.properties", ConfigMapTestUtil.readResourceFile("application.properties")) + .build(); mockClient.configMaps().inNamespace("test").resource(configMap).create(); NormalizedSource source = new NamedConfigMapNormalizedSource(configMapName, "test", false, false); @@ -94,8 +101,11 @@ void testConfigMapFromSingleApplicationProperties() { @Test void testConfigMapFromSingleApplicationYaml() { String configMapName = "app-yaml-test"; - ConfigMap configMap = new ConfigMapBuilder().withNewMetadata().withName(configMapName).endMetadata() - .addToData("application.yaml", ConfigMapTestUtil.readResourceFile("application.yaml")).build(); + ConfigMap configMap = new ConfigMapBuilder().withNewMetadata() + .withName(configMapName) + .endMetadata() + .addToData("application.yaml", ConfigMapTestUtil.readResourceFile("application.yaml")) + .build(); mockClient.configMaps().inNamespace("test").resource(configMap).create(); NormalizedSource source = new NamedConfigMapNormalizedSource(configMapName, "test", false, false); @@ -111,8 +121,11 @@ void testConfigMapFromSingleApplicationYaml() { @Test void testConfigMapFromSingleNonStandardFileName() { String configMapName = "single-non-standard-test"; - ConfigMap configMap = new ConfigMapBuilder().withNewMetadata().withName(configMapName).endMetadata() - .addToData("adhoc.yml", ConfigMapTestUtil.readResourceFile("adhoc.yml")).build(); + ConfigMap configMap = new ConfigMapBuilder().withNewMetadata() + .withName(configMapName) + .endMetadata() + .addToData("adhoc.yml", ConfigMapTestUtil.readResourceFile("adhoc.yml")) + .build(); mockClient.configMaps().inNamespace("test").resource(configMap).create(); NormalizedSource source = new NamedConfigMapNormalizedSource(configMapName, "test", false, false); @@ -128,8 +141,11 @@ void testConfigMapFromSingleNonStandardFileName() { @Test void testConfigMapFromSingleInvalidPropertiesContent() { String configMapName = "single-unparseable-properties-test"; - ConfigMap configMap = new ConfigMapBuilder().withNewMetadata().withName(configMapName).endMetadata() - .addToData("application.properties", "somevalue").build(); + ConfigMap configMap = new ConfigMapBuilder().withNewMetadata() + .withName(configMapName) + .endMetadata() + .addToData("application.properties", "somevalue") + .build(); mockClient.configMaps().inNamespace("test").resource(configMap).create(); NormalizedSource source = new NamedConfigMapNormalizedSource(configMapName, "namespace", false, false); @@ -143,8 +159,11 @@ void testConfigMapFromSingleInvalidPropertiesContent() { @Test void testConfigMapFromSingleInvalidYamlContent() { String configMapName = "single-unparseable-yaml-test"; - ConfigMap configMap = new ConfigMapBuilder().withNewMetadata().withName(configMapName).endMetadata() - .addToData("application.yaml", "somevalue").build(); + ConfigMap configMap = new ConfigMapBuilder().withNewMetadata() + .withName(configMapName) + .endMetadata() + .addToData("application.yaml", "somevalue") + .build(); mockClient.configMaps().inNamespace("test").resource(configMap).create(); NormalizedSource source = new NamedConfigMapNormalizedSource(configMapName, "namespace", false, false); @@ -158,9 +177,12 @@ void testConfigMapFromSingleInvalidYamlContent() { @Test void testConfigMapFromMultipleApplicationProperties() { String configMapName = "app-multiple-properties-test"; - ConfigMap configMap = new ConfigMapBuilder().withNewMetadata().withName(configMapName).endMetadata() - .addToData("application.properties", ConfigMapTestUtil.readResourceFile("application.properties")) - .addToData("adhoc.properties", ConfigMapTestUtil.readResourceFile("adhoc.properties")).build(); + ConfigMap configMap = new ConfigMapBuilder().withNewMetadata() + .withName(configMapName) + .endMetadata() + .addToData("application.properties", ConfigMapTestUtil.readResourceFile("application.properties")) + .addToData("adhoc.properties", ConfigMapTestUtil.readResourceFile("adhoc.properties")) + .build(); mockClient.configMaps().inNamespace("test").resource(configMap).create(); NormalizedSource source = new NamedConfigMapNormalizedSource(configMapName, "test", false, false); diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsTests.java index 2640b0a7eb..9c4a0a2bfc 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsTests.java @@ -56,8 +56,14 @@ public static void setUpBeforeClass(KubernetesClient mockClient) { HashMap data = new HashMap<>(); data.put("bean.greeting", "Hello ConfigMap, %s!"); - mockClient.configMaps().inNamespace("test").resource(new ConfigMapBuilder().withNewMetadata() - .withName(APPLICATION_NAME).endMetadata().addToData(data).build()).create(); + mockClient.configMaps() + .inNamespace("test") + .resource(new ConfigMapBuilder().withNewMetadata() + .withName(APPLICATION_NAME) + .endMetadata() + .addToData(data) + .build()) + .create(); } @Test @@ -75,8 +81,14 @@ public void testConfigMap() { @Test public void testGreetingEndpoint() { - this.webClient.get().uri("/api/greeting").exchange().expectStatus().isOk().expectBody().jsonPath("content") - .isEqualTo("Hello ConfigMap, World!"); + this.webClient.get() + .uri("/api/greeting") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("content") + .isEqualTo("Hello ConfigMap, World!"); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsWithActiveProfilesNameTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsWithActiveProfilesNameTests.java index ccda9f1cc3..bf6161c8ef 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsWithActiveProfilesNameTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsWithActiveProfilesNameTests.java @@ -52,27 +52,49 @@ public static void setUpBeforeClass(KubernetesClient mockClient) { HashMap data = new HashMap<>(); data.put("application.yml", readResourceFile("application-with-profiles.yaml")); - mockClient.configMaps().inNamespace("test").resource(new ConfigMapBuilder().withNewMetadata() - .withName(APPLICATION_NAME).endMetadata().addToData(data).build()).create(); + mockClient.configMaps() + .inNamespace("test") + .resource(new ConfigMapBuilder().withNewMetadata() + .withName(APPLICATION_NAME) + .endMetadata() + .addToData(data) + .build()) + .create(); HashMap dataWithName = new HashMap<>(); dataWithName.put("application.yml", readResourceFile("application-with-active-profiles-name.yaml")); - mockClient - .configMaps().inNamespace("test").resource(new ConfigMapBuilder().withNewMetadata() - .withName(APPLICATION_NAME + "-development").endMetadata().addToData(dataWithName).build()) - .create(); + mockClient.configMaps() + .inNamespace("test") + .resource(new ConfigMapBuilder().withNewMetadata() + .withName(APPLICATION_NAME + "-development") + .endMetadata() + .addToData(dataWithName) + .build()) + .create(); } @Test public void testGreetingEndpoint() { - this.webClient.get().uri("/api/greeting").exchange().expectStatus().isOk().expectBody().jsonPath("content") - .isEqualTo("Hello ConfigMap Active Profile Name, World!"); + this.webClient.get() + .uri("/api/greeting") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("content") + .isEqualTo("Hello ConfigMap Active Profile Name, World!"); } @Test public void testFarewellEndpoint() { - this.webClient.get().uri("/api/farewell").exchange().expectStatus().isOk().expectBody().jsonPath("content") - .isEqualTo("Goodbye ConfigMap default, World!"); + this.webClient.get() + .uri("/api/farewell") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("content") + .isEqualTo("Goodbye ConfigMap default, World!"); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsWithProfileExpressionTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsWithProfileExpressionTests.java index 103017bc38..35978cc356 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsWithProfileExpressionTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsWithProfileExpressionTests.java @@ -49,14 +49,26 @@ public static void setUpBeforeClass(KubernetesClient mockClient) { HashMap data = new HashMap<>(); data.put("application.yml", ConfigMapTestUtil.readResourceFile("application-with-profiles.yaml")); - mockClient.configMaps().inNamespace("test").resource(new ConfigMapBuilder().withNewMetadata() - .withName(APPLICATION_NAME).endMetadata().addToData(data).build()).create(); + mockClient.configMaps() + .inNamespace("test") + .resource(new ConfigMapBuilder().withNewMetadata() + .withName(APPLICATION_NAME) + .endMetadata() + .addToData(data) + .build()) + .create(); } @Test public void testGreetingEndpoint() { - this.webClient.get().uri("/api/greeting").exchange().expectStatus().isOk().expectBody().jsonPath("content") - .isEqualTo("Hello ConfigMap production and us-east, World!"); + this.webClient.get() + .uri("/api/greeting") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("content") + .isEqualTo("Hello ConfigMap production and us-east, World!"); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsWithProfilesNoActiveProfileTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsWithProfilesNoActiveProfileTests.java index 1ad2acd349..e49d409f59 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsWithProfilesNoActiveProfileTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsWithProfilesNoActiveProfileTests.java @@ -50,20 +50,38 @@ public static void setUpBeforeClass(KubernetesClient mockClient) { HashMap data = new HashMap<>(); data.put("application.yml", readResourceFile("application-with-profiles.yaml")); - mockClient.configMaps().inNamespace("test").resource(new ConfigMapBuilder().withNewMetadata() - .withName(APPLICATION_NAME).endMetadata().addToData(data).build()).create(); + mockClient.configMaps() + .inNamespace("test") + .resource(new ConfigMapBuilder().withNewMetadata() + .withName(APPLICATION_NAME) + .endMetadata() + .addToData(data) + .build()) + .create(); } @Test public void testGreetingEndpoint() { - this.webClient.get().uri("/api/greeting").exchange().expectStatus().isOk().expectBody().jsonPath("content") - .isEqualTo("Hello ConfigMap default, World!"); + this.webClient.get() + .uri("/api/greeting") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("content") + .isEqualTo("Hello ConfigMap default, World!"); } @Test public void testFarewellEndpoint() { - this.webClient.get().uri("/api/farewell").exchange().expectStatus().isOk().expectBody().jsonPath("content") - .isEqualTo("Goodbye ConfigMap default, World!"); + this.webClient.get() + .uri("/api/farewell") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("content") + .isEqualTo("Goodbye ConfigMap default, World!"); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsWithProfilesTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsWithProfilesTests.java index 7174e297ce..6486474f2a 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsWithProfilesTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsWithProfilesTests.java @@ -51,20 +51,38 @@ public static void setUpBeforeClass(KubernetesClient mockClient) { HashMap data = new HashMap<>(); data.put("application.yml", ConfigMapTestUtil.readResourceFile("application-with-profiles.yaml")); - mockClient.configMaps().inNamespace("test").resource(new ConfigMapBuilder().withNewMetadata() - .withName(APPLICATION_NAME).endMetadata().addToData(data).build()).create(); + mockClient.configMaps() + .inNamespace("test") + .resource(new ConfigMapBuilder().withNewMetadata() + .withName(APPLICATION_NAME) + .endMetadata() + .addToData(data) + .build()) + .create(); } @Test public void testGreetingEndpoint() { - this.webClient.get().uri("/api/greeting").exchange().expectStatus().isOk().expectBody().jsonPath("content") - .isEqualTo("Hello ConfigMap dev, World!"); + this.webClient.get() + .uri("/api/greeting") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("content") + .isEqualTo("Hello ConfigMap dev, World!"); } @Test public void testFarewellEndpoint() { - this.webClient.get().uri("/api/farewell").exchange().expectStatus().isOk().expectBody().jsonPath("content") - .isEqualTo("Goodbye ConfigMap default, World!"); + this.webClient.get() + .uri("/api/farewell") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("content") + .isEqualTo("Goodbye ConfigMap default, World!"); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsWithoutProfilesTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsWithoutProfilesTests.java index f4a076fb3c..811a903486 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsWithoutProfilesTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/ConfigMapsWithoutProfilesTests.java @@ -45,20 +45,38 @@ public static void setUpBeforeClass(KubernetesClient mockClient) { HashMap data = new HashMap<>(); data.put("application.yml", ConfigMapTestUtil.readResourceFile("application-without-profiles.yaml")); - mockClient.configMaps().inNamespace("test").resource(new ConfigMapBuilder().withNewMetadata() - .withName(APPLICATION_NAME).endMetadata().addToData(data).build()).create(); + mockClient.configMaps() + .inNamespace("test") + .resource(new ConfigMapBuilder().withNewMetadata() + .withName(APPLICATION_NAME) + .endMetadata() + .addToData(data) + .build()) + .create(); } @Test public void testGreetingEndpoint() { - this.webClient.get().uri("/api/greeting").exchange().expectStatus().isOk().expectBody().jsonPath("content") - .isEqualTo("Hello ConfigMap, World!"); + this.webClient.get() + .uri("/api/greeting") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("content") + .isEqualTo("Hello ConfigMap, World!"); } @Test public void testFarewellEndpoint() { - this.webClient.get().uri("/api/farewell").exchange().expectStatus().isOk().expectBody().jsonPath("content") - .isEqualTo("Goodbye ConfigMap, World!"); + this.webClient.get() + .uri("/api/farewell") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("content") + .isEqualTo("Goodbye ConfigMap, World!"); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/CoreTest.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/CoreTest.java index 8c375a2c7f..702c03191c 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/CoreTest.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/CoreTest.java @@ -44,16 +44,19 @@ public static void setUpBeforeClass(KubernetesClient mockClient) { CoreTest.mockClient = mockClient; Map data1 = new HashMap<>(); data1.put("spring.kubernetes.test.value", "value1"); - mockClient.configMaps().inNamespace("testns").resource( - new ConfigMapBuilder().withNewMetadata().withName("testapp").endMetadata().addToData(data1).build()) - .create(); + mockClient.configMaps() + .inNamespace("testns") + .resource( + new ConfigMapBuilder().withNewMetadata().withName("testapp").endMetadata().addToData(data1).build()) + .create(); Map data2 = new HashMap<>(); data2.put("amq.user", "YWRtaW4K"); data2.put("amq.pwd", "MWYyZDFlMmU2N2Rm"); - mockClient.secrets().inNamespace("testns").resource( - new SecretBuilder().withNewMetadata().withName("testapp").endMetadata().addToData(data2).build()) - .create(); + mockClient.secrets() + .inNamespace("testns") + .resource(new SecretBuilder().withNewMetadata().withName("testapp").endMetadata().addToData(data2).build()) + .create(); // Configure the kubernetes master url to point to the mock server System.setProperty(Config.KUBERNETES_MASTER_SYSTEM_PROPERTY, mockClient.getConfiguration().getMasterUrl()); diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/EventBasedConfigurationChangeDetectorTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/EventBasedConfigurationChangeDetectorTests.java index 378bf3cf87..df9534e17c 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/EventBasedConfigurationChangeDetectorTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/EventBasedConfigurationChangeDetectorTests.java @@ -72,7 +72,7 @@ void verifyConfigChangesAccountsForBootstrapPropertySources() { env.getPropertySources().addFirst(new BootstrapPropertySource<>(fabric8ConfigMapPropertySource)); List sources = ConfigReloadUtil - .findPropertySources(Fabric8ConfigMapPropertySource.class, env); + .findPropertySources(Fabric8ConfigMapPropertySource.class, env); assertThat(sources.size()).isEqualTo(1); assertThat(sources.get(0).getProperty("foo")).isEqualTo("bar"); } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigDataLocationResolverTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigDataLocationResolverTests.java index e7f4689a80..03289fad26 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigDataLocationResolverTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigDataLocationResolverTests.java @@ -48,7 +48,7 @@ class Fabric8ConfigDataLocationResolverTests { private static final DeferredLogFactory FACTORY = Supplier::get; private static final ConfigDataLocationResolverContext RESOLVER_CONTEXT = Mockito - .mock(ConfigDataLocationResolverContext.class); + .mock(ConfigDataLocationResolverContext.class); private static final Fabric8ConfigDataLocationResolver RESOLVER = new Fabric8ConfigDataLocationResolver(FACTORY); @@ -120,7 +120,7 @@ void testBothPresent() { Assertions.assertTrue(context.isRegistered(SecretsPropertySourceLocator.class)); ConfigMapPropertySourceLocator configMapPropertySourceLocator = context - .get(ConfigMapPropertySourceLocator.class); + .get(ConfigMapPropertySourceLocator.class); Assertions.assertSame(Fabric8ConfigMapPropertySourceLocator.class, configMapPropertySourceLocator.getClass()); SecretsPropertySourceLocator secretsPropertySourceLocator = context.get(SecretsPropertySourceLocator.class); @@ -162,7 +162,7 @@ void testBothPresentExplicitly() { Assertions.assertTrue(context.isRegistered(SecretsConfigProperties.class)); ConfigMapPropertySourceLocator configMapPropertySourceLocator = context - .get(ConfigMapPropertySourceLocator.class); + .get(ConfigMapPropertySourceLocator.class); Assertions.assertSame(Fabric8ConfigMapPropertySourceLocator.class, configMapPropertySourceLocator.getClass()); SecretsPropertySourceLocator secretsPropertySourceLocator = context.get(SecretsPropertySourceLocator.class); @@ -209,7 +209,7 @@ void testBothPresentAndRetryEnabled() { Assertions.assertTrue(context.isRegistered(SecretsPropertySourceLocator.class)); ConfigMapPropertySourceLocator configMapPropertySourceLocator = context - .get(ConfigMapPropertySourceLocator.class); + .get(ConfigMapPropertySourceLocator.class); Assertions.assertSame(ConfigDataRetryableConfigMapPropertySourceLocator.class, configMapPropertySourceLocator.getClass()); diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapPropertySourceLocatorMockTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapPropertySourceLocatorMockTests.java index 0ab018c479..2e9f1421a7 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapPropertySourceLocatorMockTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapPropertySourceLocatorMockTests.java @@ -54,7 +54,7 @@ void constructorWithoutClientNamespaceMustFail() { configMapConfigProperties, new KubernetesNamespaceProvider(new MockEnvironment())); NormalizedSource normalizedSource = new NamedConfigMapNormalizedSource("name", null, false, PREFIX, false); assertThatThrownBy(() -> source.getMapPropertySource(normalizedSource, new MockEnvironment())) - .isInstanceOf(NamespaceResolutionFailedException.class); + .isInstanceOf(NamespaceResolutionFailedException.class); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapPropertySourceLocatorTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapPropertySourceLocatorTests.java index 72c6923a7d..e289bbc43e 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapPropertySourceLocatorTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapPropertySourceLocatorTests.java @@ -57,7 +57,7 @@ void locateShouldThrowExceptionOnFailureWhenFailFastIsEnabled() { configMapConfigProperties, new KubernetesNamespaceProvider(new MockEnvironment())); assertThatThrownBy(() -> locator.locate(new MockEnvironment())).isInstanceOf(IllegalStateException.class) - .hasMessageContaining("api/v1/namespaces/default/configmaps. Message: Internal Server Error."); + .hasMessageContaining("api/v1/namespaces/default/configmaps. Message: Internal Server Error."); } @Test diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapPropertySourceTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapPropertySourceTests.java index 2f1983254e..482e8ba32d 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapPropertySourceTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapPropertySourceTests.java @@ -57,7 +57,7 @@ void constructorShouldThrowExceptionOnFailureWhenFailFastIsEnabled() { NormalizedSource source = new NamedConfigMapNormalizedSource(name, namespace, true, DEFAULT, true); Fabric8ConfigContext context = new Fabric8ConfigContext(mockClient, source, "default", new MockEnvironment()); assertThatThrownBy(() -> new Fabric8ConfigMapPropertySource(context)).isInstanceOf(IllegalStateException.class) - .hasMessageContaining("v1/namespaces/default/configmaps. Message: Internal Server Error."); + .hasMessageContaining("v1/namespaces/default/configmaps. Message: Internal Server Error."); } @Test diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigUtilsTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigUtilsTests.java index d0c8e2450a..ddacddc4e1 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigUtilsTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigUtilsTests.java @@ -54,10 +54,10 @@ void afterEach() { // "color=red" and do not find it. @Test void testSecretDataByLabelsSecretNotFound() { - client.secrets().inNamespace("spring-k8s") - .resource( - new SecretBuilder().withMetadata(new ObjectMetaBuilder().withName("my-secret").build()).build()) - .create(); + client.secrets() + .inNamespace("spring-k8s") + .resource(new SecretBuilder().withMetadata(new ObjectMetaBuilder().withName("my-secret").build()).build()) + .create(); MultipleSourcesContainer result = Fabric8ConfigUtils.secretsDataByLabels(client, "spring-k8s", Map.of("color", "red"), new MockEnvironment(), Set.of()); Assertions.assertEquals(Map.of(), result.data()); @@ -68,10 +68,13 @@ void testSecretDataByLabelsSecretNotFound() { // label and find it. @Test void testSecretDataByLabelsSecretFound() { - client.secrets().inNamespace("spring-k8s").resource(new SecretBuilder() + client.secrets() + .inNamespace("spring-k8s") + .resource(new SecretBuilder() .withMetadata(new ObjectMetaBuilder().withName("my-secret").withLabels(Map.of("color", "pink")).build()) - .addToData(Map.of("property", Base64.getEncoder().encodeToString("value".getBytes()))).build()) - .create(); + .addToData(Map.of("property", Base64.getEncoder().encodeToString("value".getBytes()))) + .build()) + .create(); MultipleSourcesContainer result = Fabric8ConfigUtils.secretsDataByLabels(client, "spring-k8s", Map.of("color", "pink"), new MockEnvironment(), Set.of()); @@ -84,10 +87,13 @@ void testSecretDataByLabelsSecretFound() { // it gets some special treatment. @Test void testSecretDataByLabelsSecretFoundWithPropertyFile() { - client.secrets().inNamespace("spring-k8s").resource(new SecretBuilder() + client.secrets() + .inNamespace("spring-k8s") + .resource(new SecretBuilder() .withMetadata(new ObjectMetaBuilder().withName("my-secret").withLabels(Map.of("color", "pink")).build()) .addToData(Map.of("application.yaml", Base64.getEncoder().encodeToString("key1: value1".getBytes()))) - .build()).create(); + .build()) + .create(); MultipleSourcesContainer result = Fabric8ConfigUtils.secretsDataByLabels(client, "spring-k8s", Map.of("color", "pink"), new MockEnvironment(), Set.of()); @@ -99,16 +105,22 @@ void testSecretDataByLabelsSecretFoundWithPropertyFile() { // we search for them by same label and find them. @Test void testSecretDataByLabelsTwoSecretsFound() { - client.secrets().inNamespace("spring-k8s").resource(new SecretBuilder() + client.secrets() + .inNamespace("spring-k8s") + .resource(new SecretBuilder() .withMetadata(new ObjectMetaBuilder().withName("my-secret").withLabels(Map.of("color", "pink")).build()) - .addToData(Map.of("property", Base64.getEncoder().encodeToString("value".getBytes()))).build()) - .create(); + .addToData(Map.of("property", Base64.getEncoder().encodeToString("value".getBytes()))) + .build()) + .create(); - client.secrets().inNamespace("spring-k8s").resource(new SecretBuilder() + client.secrets() + .inNamespace("spring-k8s") + .resource(new SecretBuilder() .withMetadata( new ObjectMetaBuilder().withName("my-secret-2").withLabels(Map.of("color", "pink")).build()) - .addToData(Map.of("property-2", Base64.getEncoder().encodeToString("value-2".getBytes()))).build()) - .create(); + .addToData(Map.of("property-2", Base64.getEncoder().encodeToString("value-2".getBytes()))) + .build()) + .create(); MultipleSourcesContainer result = Fabric8ConfigUtils.secretsDataByLabels(client, "spring-k8s", Map.of("color", "pink"), new MockEnvironment(), Set.of()); @@ -135,33 +147,45 @@ void testSecretDataByLabelsTwoSecretsFound() { */ @Test void testSecretDataByLabelsThreeSecretsFound() { - client.secrets().inNamespace("spring-k8s") - .resource(new SecretBuilder() - .withMetadata(new ObjectMetaBuilder().withName("blue-circle-secret") - .withLabels(Map.of("color", "blue", "shape", "circle", "tag", "fit")).build()) - .addToData(Map.of("one", Base64.getEncoder().encodeToString("1".getBytes()))).build()) - .create(); - - client.secrets().inNamespace("spring-k8s") - .resource(new SecretBuilder() - .withMetadata(new ObjectMetaBuilder().withName("blue-square-secret") - .withLabels(Map.of("color", "blue", "shape", "square", "tag", "fit")).build()) - .addToData(Map.of("two", Base64.getEncoder().encodeToString("2".getBytes()))).build()) - .create(); - - client.secrets().inNamespace("spring-k8s") - .resource(new SecretBuilder() - .withMetadata(new ObjectMetaBuilder().withName("blue-triangle-secret") - .withLabels(Map.of("color", "blue", "shape", "triangle", "tag", "no-fit")).build()) - .addToData(Map.of("three", Base64.getEncoder().encodeToString("3".getBytes()))).build()) - .create(); - - client.secrets().inNamespace("spring-k8s") - .resource(new SecretBuilder() - .withMetadata(new ObjectMetaBuilder().withName("blue-square-secret-k8s") - .withLabels(Map.of("color", "blue", "shape", "triangle", "tag", "no-fit")).build()) - .addToData(Map.of("four", Base64.getEncoder().encodeToString("4".getBytes()))).build()) - .create(); + client.secrets() + .inNamespace("spring-k8s") + .resource(new SecretBuilder() + .withMetadata(new ObjectMetaBuilder().withName("blue-circle-secret") + .withLabels(Map.of("color", "blue", "shape", "circle", "tag", "fit")) + .build()) + .addToData(Map.of("one", Base64.getEncoder().encodeToString("1".getBytes()))) + .build()) + .create(); + + client.secrets() + .inNamespace("spring-k8s") + .resource(new SecretBuilder() + .withMetadata(new ObjectMetaBuilder().withName("blue-square-secret") + .withLabels(Map.of("color", "blue", "shape", "square", "tag", "fit")) + .build()) + .addToData(Map.of("two", Base64.getEncoder().encodeToString("2".getBytes()))) + .build()) + .create(); + + client.secrets() + .inNamespace("spring-k8s") + .resource(new SecretBuilder() + .withMetadata(new ObjectMetaBuilder().withName("blue-triangle-secret") + .withLabels(Map.of("color", "blue", "shape", "triangle", "tag", "no-fit")) + .build()) + .addToData(Map.of("three", Base64.getEncoder().encodeToString("3".getBytes()))) + .build()) + .create(); + + client.secrets() + .inNamespace("spring-k8s") + .resource(new SecretBuilder() + .withMetadata(new ObjectMetaBuilder().withName("blue-square-secret-k8s") + .withLabels(Map.of("color", "blue", "shape", "triangle", "tag", "no-fit")) + .build()) + .addToData(Map.of("four", Base64.getEncoder().encodeToString("4".getBytes()))) + .build()) + .create(); MultipleSourcesContainer result = Fabric8ConfigUtils.secretsDataByLabels(client, "spring-k8s", Map.of("tag", "fit", "color", "blue"), new MockEnvironment(), Set.of("k8s")); @@ -179,10 +203,10 @@ void testSecretDataByLabelsThreeSecretsFound() { // secret "my-secret" is deployed; we search for it by name and do not find it. @Test void testSecretDataByNameSecretNotFound() { - client.secrets().inNamespace("spring-k8s") - .resource( - new SecretBuilder().withMetadata(new ObjectMetaBuilder().withName("my-secret").build()).build()) - .create(); + client.secrets() + .inNamespace("spring-k8s") + .resource(new SecretBuilder().withMetadata(new ObjectMetaBuilder().withName("my-secret").build()).build()) + .create(); LinkedHashSet names = new LinkedHashSet<>(); names.add("nope"); MultipleSourcesContainer result = Fabric8ConfigUtils.secretsDataByName(client, "spring-k8s", names, @@ -194,10 +218,12 @@ void testSecretDataByNameSecretNotFound() { // secret "my-secret" is deployed; we search for it by name and find it. @Test void testSecretDataByNameSecretFound() { - client.secrets().inNamespace("spring-k8s") - .resource(new SecretBuilder().withMetadata(new ObjectMetaBuilder().withName("my-secret").build()) - .addToData(Map.of("property", Base64.getEncoder().encodeToString("value".getBytes()))).build()) - .create(); + client.secrets() + .inNamespace("spring-k8s") + .resource(new SecretBuilder().withMetadata(new ObjectMetaBuilder().withName("my-secret").build()) + .addToData(Map.of("property", Base64.getEncoder().encodeToString("value".getBytes()))) + .build()) + .create(); LinkedHashSet names = new LinkedHashSet<>(); names.add("my-secret"); @@ -211,16 +237,19 @@ void testSecretDataByNameSecretFound() { // we search for them by name label and find them. @Test void testSecretDataByNameTwoSecretsFound() { - client.secrets().inNamespace("spring-k8s") - .resource(new SecretBuilder().withMetadata(new ObjectMetaBuilder().withName("my-secret").build()) - .addToData(Map.of("property", Base64.getEncoder().encodeToString("value".getBytes()))).build()) - .create(); - - client.secrets().inNamespace("spring-k8s") - .resource(new SecretBuilder().withMetadata(new ObjectMetaBuilder().withName("my-secret-2").build()) - .addToData(Map.of("property-2", Base64.getEncoder().encodeToString("value-2".getBytes()))) - .build()) - .create(); + client.secrets() + .inNamespace("spring-k8s") + .resource(new SecretBuilder().withMetadata(new ObjectMetaBuilder().withName("my-secret").build()) + .addToData(Map.of("property", Base64.getEncoder().encodeToString("value".getBytes()))) + .build()) + .create(); + + client.secrets() + .inNamespace("spring-k8s") + .resource(new SecretBuilder().withMetadata(new ObjectMetaBuilder().withName("my-secret-2").build()) + .addToData(Map.of("property-2", Base64.getEncoder().encodeToString("value-2".getBytes()))) + .build()) + .create(); LinkedHashSet names = new LinkedHashSet<>(); names.add("my-secret"); names.add("my-secret-2"); @@ -239,9 +268,11 @@ void testSecretDataByNameTwoSecretsFound() { // and find it; but it has no data. @Test void testConfigMapsDataByNameFoundNoData() { - client.configMaps().inNamespace("spring-k8s").resource( - new ConfigMapBuilder().withMetadata(new ObjectMetaBuilder().withName("my-config-map").build()).build()) - .create(); + client.configMaps() + .inNamespace("spring-k8s") + .resource(new ConfigMapBuilder().withMetadata(new ObjectMetaBuilder().withName("my-config-map").build()) + .build()) + .create(); LinkedHashSet names = new LinkedHashSet<>(); names.add("my-config-map"); @@ -254,9 +285,11 @@ void testConfigMapsDataByNameFoundNoData() { // config-map "my-config-map" is deployed; we search for it and do not find it. @Test void testConfigMapsDataByNameNotFound() { - client.configMaps().inNamespace("spring-k8s").resource( - new ConfigMapBuilder().withMetadata(new ObjectMetaBuilder().withName("my-config-map").build()).build()) - .create(); + client.configMaps() + .inNamespace("spring-k8s") + .resource(new ConfigMapBuilder().withMetadata(new ObjectMetaBuilder().withName("my-config-map").build()) + .build()) + .create(); LinkedHashSet names = new LinkedHashSet<>(); names.add("my-config-map-not-found"); MultipleSourcesContainer result = Fabric8ConfigUtils.configMapsDataByName(client, "spring-k8s", names, @@ -268,10 +301,12 @@ void testConfigMapsDataByNameNotFound() { // config-map "my-config-map" is deployed; we search for it and find it @Test void testConfigMapDataByNameFound() { - client.configMaps().inNamespace("spring-k8s") - .resource(new ConfigMapBuilder().withMetadata(new ObjectMetaBuilder().withName("my-config-map").build()) - .addToData(Map.of("property", "value")).build()) - .create(); + client.configMaps() + .inNamespace("spring-k8s") + .resource(new ConfigMapBuilder().withMetadata(new ObjectMetaBuilder().withName("my-config-map").build()) + .addToData(Map.of("property", "value")) + .build()) + .create(); LinkedHashSet names = new LinkedHashSet<>(); names.add("my-config-map"); @@ -286,10 +321,12 @@ void testConfigMapDataByNameFound() { // It contains a single .yaml property, as such it gets some special treatment. @Test void testConfigMapDataByNameFoundWithPropertyFile() { - client.configMaps().inNamespace("spring-k8s") - .resource(new ConfigMapBuilder().withMetadata(new ObjectMetaBuilder().withName("my-config-map").build()) - .addToData(Map.of("application.yaml", "key1: value1")).build()) - .create(); + client.configMaps() + .inNamespace("spring-k8s") + .resource(new ConfigMapBuilder().withMetadata(new ObjectMetaBuilder().withName("my-config-map").build()) + .addToData(Map.of("application.yaml", "key1: value1")) + .build()) + .create(); LinkedHashSet names = new LinkedHashSet<>(); names.add("my-config-map"); @@ -304,16 +341,19 @@ void testConfigMapDataByNameFoundWithPropertyFile() { // we search and find them. @Test void testConfigMapDataByNameTwoFound() { - client.configMaps().inNamespace("spring-k8s") - .resource(new ConfigMapBuilder().withMetadata(new ObjectMetaBuilder().withName("my-config-map").build()) - .addToData(Map.of("property", "value")).build()) - .create(); - - client.configMaps().inNamespace("spring-k8s") - .resource( - new ConfigMapBuilder().withMetadata(new ObjectMetaBuilder().withName("my-config-map-2").build()) - .addToData(Map.of("property-2", "value-2")).build()) - .create(); + client.configMaps() + .inNamespace("spring-k8s") + .resource(new ConfigMapBuilder().withMetadata(new ObjectMetaBuilder().withName("my-config-map").build()) + .addToData(Map.of("property", "value")) + .build()) + .create(); + + client.configMaps() + .inNamespace("spring-k8s") + .resource(new ConfigMapBuilder().withMetadata(new ObjectMetaBuilder().withName("my-config-map-2").build()) + .addToData(Map.of("property-2", "value-2")) + .build()) + .create(); LinkedHashSet names = new LinkedHashSet<>(); names.add("my-config-map"); diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8SecretsPropertySourceLocatorTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8SecretsPropertySourceLocatorTests.java index 871cea4f67..5223490912 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8SecretsPropertySourceLocatorTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8SecretsPropertySourceLocatorTests.java @@ -57,7 +57,7 @@ void locateShouldThrowExceptionOnFailureWhenFailFastIsEnabled() { configMapConfigProperties, new KubernetesNamespaceProvider(new MockEnvironment())); assertThatThrownBy(() -> locator.locate(new MockEnvironment())).isInstanceOf(IllegalStateException.class) - .hasMessageContaining("v1/namespaces/default/secrets. Message: Internal Server Error."); + .hasMessageContaining("v1/namespaces/default/secrets. Message: Internal Server Error."); } @Test diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8SecretsPropertySourceMockTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8SecretsPropertySourceMockTests.java index 74de092266..c048667484 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8SecretsPropertySourceMockTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8SecretsPropertySourceMockTests.java @@ -54,8 +54,8 @@ void namedStrategyShouldThrowExceptionOnFailureWhenFailFastIsEnabled() { mockServer.expect().withPath(path).andReturn(500, "Internal Server Error").always(); assertThatThrownBy(() -> new Fabric8SecretsPropertySource(context)).isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Failure executing: GET at: https://localhost:") - .hasMessageContaining("api/v1/namespaces/default/secrets. Message: Internal Server Error."); + .hasMessageContaining("Failure executing: GET at: https://localhost:") + .hasMessageContaining("api/v1/namespaces/default/secrets. Message: Internal Server Error."); } @Test @@ -69,7 +69,7 @@ void labeledStrategyShouldThrowExceptionOnFailureWhenFailFastIsEnabled() { mockServer.expect().withPath(path).andReturn(500, "Internal Server Error").always(); assertThatThrownBy(() -> new Fabric8SecretsPropertySource(context)).isInstanceOf(IllegalStateException.class) - .hasMessageContaining("api/v1/namespaces/default/secrets. Message: Internal Server Error."); + .hasMessageContaining("api/v1/namespaces/default/secrets. Message: Internal Server Error."); } @Test diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/HealthIndicatorTest.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/HealthIndicatorTest.java index 03eabf37b2..ab449cc07a 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/HealthIndicatorTest.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/HealthIndicatorTest.java @@ -56,9 +56,15 @@ static void setUpBeforeClass() { @Test void healthEndpointShouldContainKubernetes() { - this.webClient.get().uri("http://localhost:{port}/actuator/health", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("components.kubernetes").exists(); + this.webClient.get() + .uri("http://localhost:{port}/actuator/health", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("components.kubernetes") + .exists(); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/KubernetesConfigTestBase.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/KubernetesConfigTestBase.java index f0fc03ff5a..ee85ada388 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/KubernetesConfigTestBase.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/KubernetesConfigTestBase.java @@ -48,7 +48,9 @@ protected void setup(Class mockClientConfiguration, String... env) { context = new SpringApplicationBuilder(PropertyPlaceholderAutoConfiguration.class, mockClientConfiguration, BootstrapConfiguration.class, Fabric8ConfigReloadAutoConfiguration.class, ConfigReloadPropertiesAutoConfiguration.class, RefreshAutoConfiguration.class) - .web(WebApplicationType.NONE).properties(properties).run(); + .web(WebApplicationType.NONE) + .properties(properties) + .run(); } @AfterEach diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/LabeledConfigMapContextToSourceDataProviderTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/LabeledConfigMapContextToSourceDataProviderTests.java index 05431536b3..7342c4c568 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/LabeledConfigMapContextToSourceDataProviderTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/LabeledConfigMapContextToSourceDataProviderTests.java @@ -90,8 +90,12 @@ void afterEach() { @Test void singleConfigMapMatchAgainstLabels() { - ConfigMap configMap = new ConfigMapBuilder().withNewMetadata().withName("test-configmap").withLabels(LABELS) - .endMetadata().addToData("name", "value").build(); + ConfigMap configMap = new ConfigMapBuilder().withNewMetadata() + .withName("test-configmap") + .withLabels(LABELS) + .endMetadata() + .addToData("name", "value") + .build(); mockClient.configMaps().inNamespace(NAMESPACE).resource(configMap).create(); @@ -114,14 +118,26 @@ void singleConfigMapMatchAgainstLabels() { @Test void twoConfigMapsMatchAgainstLabels() { - ConfigMap redOne = new ConfigMapBuilder().withNewMetadata().withName("red-configmap").withLabels(RED_LABEL) - .endMetadata().addToData("colorOne", "really-red").build(); - - ConfigMap redTwo = new ConfigMapBuilder().withNewMetadata().withName("red-configmap-again") - .withLabels(RED_LABEL).endMetadata().addToData("colorTwo", "really-red-again").build(); - - ConfigMap blue = new ConfigMapBuilder().withNewMetadata().withName("blue-configmap").withLabels(BLUE_LABEL) - .endMetadata().addToData("color", "blue").build(); + ConfigMap redOne = new ConfigMapBuilder().withNewMetadata() + .withName("red-configmap") + .withLabels(RED_LABEL) + .endMetadata() + .addToData("colorOne", "really-red") + .build(); + + ConfigMap redTwo = new ConfigMapBuilder().withNewMetadata() + .withName("red-configmap-again") + .withLabels(RED_LABEL) + .endMetadata() + .addToData("colorTwo", "really-red-again") + .build(); + + ConfigMap blue = new ConfigMapBuilder().withNewMetadata() + .withName("blue-configmap") + .withLabels(BLUE_LABEL) + .endMetadata() + .addToData("color", "blue") + .build(); mockClient.configMaps().inNamespace(NAMESPACE).resource(redOne).create(); mockClient.configMaps().inNamespace(NAMESPACE).resource(redTwo).create(); @@ -147,8 +163,12 @@ void twoConfigMapsMatchAgainstLabels() { @Test void configMapNoMatch() { - ConfigMap pink = new ConfigMapBuilder().withNewMetadata().withName("pink-configmap").withLabels(PINK_LABEL) - .endMetadata().addToData("color", "pink").build(); + ConfigMap pink = new ConfigMapBuilder().withNewMetadata() + .withName("pink-configmap") + .withLabels(PINK_LABEL) + .endMetadata() + .addToData("color", "pink") + .build(); mockClient.configMaps().inNamespace(NAMESPACE).resource(pink).create(); @@ -172,8 +192,12 @@ void configMapNoMatch() { @Test void namespaceMatch() { - ConfigMap configMap = new ConfigMapBuilder().withNewMetadata().withName("test-configmap").withLabels(LABELS) - .endMetadata().addToData("name", "value").build(); + ConfigMap configMap = new ConfigMapBuilder().withNewMetadata() + .withName("test-configmap") + .withLabels(LABELS) + .endMetadata() + .addToData("name", "value") + .build(); mockClient.configMaps().inNamespace(NAMESPACE).resource(configMap).create(); @@ -198,9 +222,12 @@ void namespaceMatch() { */ @Test void testWithPrefix() { - ConfigMap configMap = new ConfigMapBuilder().withNewMetadata().withName("blue-configmap") - .withLabels(Collections.singletonMap("color", "blue")).endMetadata() - .addToData("what-color", "blue-color").build(); + ConfigMap configMap = new ConfigMapBuilder().withNewMetadata() + .withName("blue-configmap") + .withLabels(Collections.singletonMap("color", "blue")) + .endMetadata() + .addToData("what-color", "blue-color") + .build(); mockClient.configMaps().inNamespace(NAMESPACE).resource(configMap).create(); @@ -229,12 +256,19 @@ void testWithPrefix() { */ @Test void testTwoConfigmapsWithPrefix() { - ConfigMap blueConfigMap = new ConfigMapBuilder().withNewMetadata().withName("blue-configmap") - .withLabels(Collections.singletonMap("color", "blue")).endMetadata().addToData("first", "blue").build(); - - ConfigMap anotherBlue = new ConfigMapBuilder().withNewMetadata().withName("another-blue-configmap") - .withLabels(Collections.singletonMap("color", "blue")).endMetadata().addToData("second", "blue") - .build(); + ConfigMap blueConfigMap = new ConfigMapBuilder().withNewMetadata() + .withName("blue-configmap") + .withLabels(Collections.singletonMap("color", "blue")) + .endMetadata() + .addToData("first", "blue") + .build(); + + ConfigMap anotherBlue = new ConfigMapBuilder().withNewMetadata() + .withName("another-blue-configmap") + .withLabels(Collections.singletonMap("color", "blue")) + .endMetadata() + .addToData("second", "blue") + .build(); mockClient.configMaps().inNamespace(NAMESPACE).resource(blueConfigMap).create(); mockClient.configMaps().inNamespace(NAMESPACE).resource(anotherBlue).create(); @@ -272,11 +306,18 @@ void testTwoConfigmapsWithPrefix() { */ @Test void searchWithLabelsNoConfigmapsFound() { - ConfigMap colorConfigmap = new ConfigMapBuilder().withNewMetadata().withName("color-configmap") - .withLabels(Collections.singletonMap("color", "blue")).endMetadata().addToData("one", "1").build(); - - ConfigMap colorConfigmapK8s = new ConfigMapBuilder().withNewMetadata().withName("color-configmap-k8s") - .endMetadata().addToData("two", "2").build(); + ConfigMap colorConfigmap = new ConfigMapBuilder().withNewMetadata() + .withName("color-configmap") + .withLabels(Collections.singletonMap("color", "blue")) + .endMetadata() + .addToData("one", "1") + .build(); + + ConfigMap colorConfigmapK8s = new ConfigMapBuilder().withNewMetadata() + .withName("color-configmap-k8s") + .endMetadata() + .addToData("two", "2") + .build(); mockClient.configMaps().inNamespace(NAMESPACE).resource(colorConfigmap).create(); mockClient.configMaps().inNamespace(NAMESPACE).resource(colorConfigmapK8s).create(); @@ -302,11 +343,18 @@ void searchWithLabelsNoConfigmapsFound() { */ @Test void searchWithLabelsOneConfigMapFound() { - ConfigMap colorConfigmap = new ConfigMapBuilder().withNewMetadata().withName("color-configmap") - .withLabels(Collections.singletonMap("color", "blue")).endMetadata().addToData("one", "1").build(); - - ConfigMap shapeConfigmap = new ConfigMapBuilder().withNewMetadata().withName("shape-configmap").endMetadata() - .addToData("two", "2").build(); + ConfigMap colorConfigmap = new ConfigMapBuilder().withNewMetadata() + .withName("color-configmap") + .withLabels(Collections.singletonMap("color", "blue")) + .endMetadata() + .addToData("one", "1") + .build(); + + ConfigMap shapeConfigmap = new ConfigMapBuilder().withNewMetadata() + .withName("shape-configmap") + .endMetadata() + .addToData("two", "2") + .build(); mockClient.configMaps().inNamespace(NAMESPACE).resource(colorConfigmap).create(); mockClient.configMaps().inNamespace(NAMESPACE).resource(shapeConfigmap).create(); @@ -334,11 +382,19 @@ void searchWithLabelsOneConfigMapFound() { */ @Test void searchWithLabelsOneConfigMapFoundAndOneFromProfileFound() { - ConfigMap colorConfigmap = new ConfigMapBuilder().withNewMetadata().withName("color-configmap") - .withLabels(Collections.singletonMap("color", "blue")).endMetadata().addToData("one", "1").build(); - - ConfigMap colorConfigmapK8s = new ConfigMapBuilder().withNewMetadata().withName("color-configmap-k8s") - .withLabels(Collections.singletonMap("color", "red")).endMetadata().addToData("two", "2").build(); + ConfigMap colorConfigmap = new ConfigMapBuilder().withNewMetadata() + .withName("color-configmap") + .withLabels(Collections.singletonMap("color", "blue")) + .endMetadata() + .addToData("one", "1") + .build(); + + ConfigMap colorConfigmapK8s = new ConfigMapBuilder().withNewMetadata() + .withName("color-configmap-k8s") + .withLabels(Collections.singletonMap("color", "red")) + .endMetadata() + .addToData("two", "2") + .build(); mockClient.configMaps().inNamespace(NAMESPACE).resource(colorConfigmap).create(); mockClient.configMaps().inNamespace(NAMESPACE).resource(colorConfigmapK8s).create(); @@ -370,20 +426,40 @@ void searchWithLabelsOneConfigMapFoundAndOneFromProfileFound() { */ @Test void searchWithLabelsTwoConfigMapsFoundAndOneFromProfileFound() { - ConfigMap colorConfigMap = new ConfigMapBuilder().withNewMetadata().withName("color-configmap") - .withLabels(Collections.singletonMap("color", "blue")).endMetadata().addToData("one", "1").build(); - - ConfigMap shapeConfigmap = new ConfigMapBuilder().withNewMetadata().withName("shape-configmap") - .withLabels(Map.of("color", "blue", "shape", "round")).endMetadata().addToData("two", "2").build(); - - ConfigMap noFit = new ConfigMapBuilder().withNewMetadata().withName("no-fit") - .withLabels(Map.of("tag", "no-fit")).endMetadata().addToData("three", "3").build(); - - ConfigMap colorConfigmapK8s = new ConfigMapBuilder().withNewMetadata().withName("color-configmap-k8s") - .withLabels(Map.of("color", "red")).endMetadata().addToData("four", "4").build(); - - ConfigMap shapeConfigmapK8s = new ConfigMapBuilder().withNewMetadata().withName("shape-configmap-k8s") - .withLabels(Map.of("shape", "triangle")).endMetadata().addToData("five", "5").build(); + ConfigMap colorConfigMap = new ConfigMapBuilder().withNewMetadata() + .withName("color-configmap") + .withLabels(Collections.singletonMap("color", "blue")) + .endMetadata() + .addToData("one", "1") + .build(); + + ConfigMap shapeConfigmap = new ConfigMapBuilder().withNewMetadata() + .withName("shape-configmap") + .withLabels(Map.of("color", "blue", "shape", "round")) + .endMetadata() + .addToData("two", "2") + .build(); + + ConfigMap noFit = new ConfigMapBuilder().withNewMetadata() + .withName("no-fit") + .withLabels(Map.of("tag", "no-fit")) + .endMetadata() + .addToData("three", "3") + .build(); + + ConfigMap colorConfigmapK8s = new ConfigMapBuilder().withNewMetadata() + .withName("color-configmap-k8s") + .withLabels(Map.of("color", "red")) + .endMetadata() + .addToData("four", "4") + .build(); + + ConfigMap shapeConfigmapK8s = new ConfigMapBuilder().withNewMetadata() + .withName("shape-configmap-k8s") + .withLabels(Map.of("shape", "triangle")) + .endMetadata() + .addToData("five", "5") + .build(); mockClient.configMaps().inNamespace(NAMESPACE).resource(colorConfigMap).create(); mockClient.configMaps().inNamespace(NAMESPACE).resource(shapeConfigmap).create(); @@ -403,13 +479,13 @@ void searchWithLabelsTwoConfigMapsFoundAndOneFromProfileFound() { Assertions.assertEquals(sourceData.sourceData().size(), 4); Assertions.assertEquals(sourceData.sourceData() - .get("color-configmap.color-configmap-k8s.shape-configmap.shape-configmap-k8s.one"), "1"); + .get("color-configmap.color-configmap-k8s.shape-configmap.shape-configmap-k8s.one"), "1"); Assertions.assertEquals(sourceData.sourceData() - .get("color-configmap.color-configmap-k8s.shape-configmap.shape-configmap-k8s.two"), "2"); + .get("color-configmap.color-configmap-k8s.shape-configmap.shape-configmap-k8s.two"), "2"); Assertions.assertEquals(sourceData.sourceData() - .get("color-configmap.color-configmap-k8s.shape-configmap.shape-configmap-k8s.four"), "4"); + .get("color-configmap.color-configmap-k8s.shape-configmap.shape-configmap-k8s.four"), "4"); Assertions.assertEquals(sourceData.sourceData() - .get("color-configmap.color-configmap-k8s.shape-configmap.shape-configmap-k8s.five"), "5"); + .get("color-configmap.color-configmap-k8s.shape-configmap.shape-configmap-k8s.five"), "5"); Assertions.assertEquals(sourceData.sourceName(), "configmap.color-configmap.color-configmap-k8s.shape-configmap.shape-configmap-k8s.default"); @@ -426,11 +502,19 @@ void searchWithLabelsTwoConfigMapsFoundAndOneFromProfileFound() { */ @Test void cache(CapturedOutput output) { - ConfigMap redConfigMap = new ConfigMapBuilder().withNewMetadata().withName("red-configmap") - .withLabels(Collections.singletonMap("color", "red")).endMetadata().addToData("one", "1").build(); - - ConfigMap greenConfigmap = new ConfigMapBuilder().withNewMetadata().withName("green-configmap") - .withLabels(Map.of("color", "green")).endMetadata().addToData("two", "2").build(); + ConfigMap redConfigMap = new ConfigMapBuilder().withNewMetadata() + .withName("red-configmap") + .withLabels(Collections.singletonMap("color", "red")) + .endMetadata() + .addToData("one", "1") + .build(); + + ConfigMap greenConfigmap = new ConfigMapBuilder().withNewMetadata() + .withName("green-configmap") + .withLabels(Map.of("color", "green")) + .endMetadata() + .addToData("two", "2") + .build(); mockClient.configMaps().inNamespace(NAMESPACE).resource(redConfigMap).create(); mockClient.configMaps().inNamespace(NAMESPACE).resource(greenConfigmap).create(); diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/LabeledSecretContextToSourceDataProviderTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/LabeledSecretContextToSourceDataProviderTests.java index ccdba80917..835e831c89 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/LabeledSecretContextToSourceDataProviderTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/LabeledSecretContextToSourceDataProviderTests.java @@ -93,8 +93,12 @@ void afterEach() { @Test void singleSecretMatchAgainstLabels() { - Secret secret = new SecretBuilder().withNewMetadata().withName("test-secret").withLabels(LABELS).endMetadata() - .addToData("secretName", Base64.getEncoder().encodeToString("secretValue".getBytes())).build(); + Secret secret = new SecretBuilder().withNewMetadata() + .withName("test-secret") + .withLabels(LABELS) + .endMetadata() + .addToData("secretName", Base64.getEncoder().encodeToString("secretValue".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(secret).create(); @@ -117,15 +121,26 @@ void singleSecretMatchAgainstLabels() { @Test void twoSecretsMatchAgainstLabels() { - Secret redOne = new SecretBuilder().withNewMetadata().withName("red-secret").withLabels(RED_LABEL).endMetadata() - .addToData("colorOne", Base64.getEncoder().encodeToString("really-red".getBytes())).build(); - - Secret redTwo = new SecretBuilder().withNewMetadata().withName("red-secret-again").withLabels(RED_LABEL) - .endMetadata().addToData("colorTwo", Base64.getEncoder().encodeToString("really-red-again".getBytes())) - .build(); - - Secret blue = new SecretBuilder().withNewMetadata().withName("blue-secret").withLabels(BLUE_LABEL).endMetadata() - .addToData("color", Base64.getEncoder().encodeToString("blue".getBytes())).build(); + Secret redOne = new SecretBuilder().withNewMetadata() + .withName("red-secret") + .withLabels(RED_LABEL) + .endMetadata() + .addToData("colorOne", Base64.getEncoder().encodeToString("really-red".getBytes())) + .build(); + + Secret redTwo = new SecretBuilder().withNewMetadata() + .withName("red-secret-again") + .withLabels(RED_LABEL) + .endMetadata() + .addToData("colorTwo", Base64.getEncoder().encodeToString("really-red-again".getBytes())) + .build(); + + Secret blue = new SecretBuilder().withNewMetadata() + .withName("blue-secret") + .withLabels(BLUE_LABEL) + .endMetadata() + .addToData("color", Base64.getEncoder().encodeToString("blue".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(redOne).create(); mockClient.secrets().inNamespace(NAMESPACE).resource(redTwo).create(); @@ -151,8 +166,12 @@ void twoSecretsMatchAgainstLabels() { @Test void secretNoMatch() { - Secret pink = new SecretBuilder().withNewMetadata().withName("pink-secret").withLabels(PINK_LABEL).endMetadata() - .addToData("color", Base64.getEncoder().encodeToString("pink".getBytes())).build(); + Secret pink = new SecretBuilder().withNewMetadata() + .withName("pink-secret") + .withLabels(PINK_LABEL) + .endMetadata() + .addToData("color", Base64.getEncoder().encodeToString("pink".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(pink).create(); @@ -176,8 +195,12 @@ void secretNoMatch() { @Test void namespaceMatch() { - Secret secret = new SecretBuilder().withNewMetadata().withName("test-secret").withLabels(LABELS).endMetadata() - .addToData("secretName", Base64.getEncoder().encodeToString("secretValue".getBytes())).build(); + Secret secret = new SecretBuilder().withNewMetadata() + .withName("test-secret") + .withLabels(LABELS) + .endMetadata() + .addToData("secretName", Base64.getEncoder().encodeToString("secretValue".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(secret).create(); @@ -201,9 +224,12 @@ void namespaceMatch() { */ @Test void testWithPrefix() { - Secret secret = new SecretBuilder().withNewMetadata().withName("blue-secret") - .withLabels(Collections.singletonMap("color", "blue")).endMetadata() - .addToData("what-color", Base64.getEncoder().encodeToString("blue-color".getBytes())).build(); + Secret secret = new SecretBuilder().withNewMetadata() + .withName("blue-secret") + .withLabels(Collections.singletonMap("color", "blue")) + .endMetadata() + .addToData("what-color", Base64.getEncoder().encodeToString("blue-color".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(secret).create(); @@ -231,13 +257,19 @@ void testWithPrefix() { */ @Test void testTwoSecretsWithPrefix() { - Secret blueSecret = new SecretBuilder().withNewMetadata().withName("blue-secret") - .withLabels(Collections.singletonMap("color", "blue")).endMetadata() - .addToData("first", Base64.getEncoder().encodeToString("blue".getBytes())).build(); - - Secret anotherBlue = new SecretBuilder().withNewMetadata().withName("another-blue-secret") - .withLabels(Collections.singletonMap("color", "blue")).endMetadata() - .addToData("second", Base64.getEncoder().encodeToString("blue".getBytes())).build(); + Secret blueSecret = new SecretBuilder().withNewMetadata() + .withName("blue-secret") + .withLabels(Collections.singletonMap("color", "blue")) + .endMetadata() + .addToData("first", Base64.getEncoder().encodeToString("blue".getBytes())) + .build(); + + Secret anotherBlue = new SecretBuilder().withNewMetadata() + .withName("another-blue-secret") + .withLabels(Collections.singletonMap("color", "blue")) + .endMetadata() + .addToData("second", Base64.getEncoder().encodeToString("blue".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(blueSecret).create(); mockClient.secrets().inNamespace(NAMESPACE).resource(anotherBlue).create(); @@ -275,12 +307,18 @@ void testTwoSecretsWithPrefix() { */ @Test void searchWithLabelsNoSecretFound() { - Secret colorSecret = new SecretBuilder().withNewMetadata().withName("color-secret") - .withLabels(Collections.singletonMap("color", "blue")).endMetadata() - .addToData("one", Base64.getEncoder().encodeToString("1".getBytes())).build(); - - Secret colorSecretK8s = new SecretBuilder().withNewMetadata().withName("color-secret-k8s").endMetadata() - .addToData("two", Base64.getEncoder().encodeToString("2".getBytes())).build(); + Secret colorSecret = new SecretBuilder().withNewMetadata() + .withName("color-secret") + .withLabels(Collections.singletonMap("color", "blue")) + .endMetadata() + .addToData("one", Base64.getEncoder().encodeToString("1".getBytes())) + .build(); + + Secret colorSecretK8s = new SecretBuilder().withNewMetadata() + .withName("color-secret-k8s") + .endMetadata() + .addToData("two", Base64.getEncoder().encodeToString("2".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(colorSecret).create(); mockClient.secrets().inNamespace(NAMESPACE).resource(colorSecretK8s).create(); @@ -306,12 +344,18 @@ void searchWithLabelsNoSecretFound() { */ @Test void searchWithLabelsOneSecretFound() { - Secret colorSecret = new SecretBuilder().withNewMetadata().withName("color-secret") - .withLabels(Collections.singletonMap("color", "blue")).endMetadata() - .addToData("one", Base64.getEncoder().encodeToString("1".getBytes())).build(); - - Secret shapeSecret = new SecretBuilder().withNewMetadata().withName("shape-secret").endMetadata() - .addToData("two", Base64.getEncoder().encodeToString("2".getBytes())).build(); + Secret colorSecret = new SecretBuilder().withNewMetadata() + .withName("color-secret") + .withLabels(Collections.singletonMap("color", "blue")) + .endMetadata() + .addToData("one", Base64.getEncoder().encodeToString("1".getBytes())) + .build(); + + Secret shapeSecret = new SecretBuilder().withNewMetadata() + .withName("shape-secret") + .endMetadata() + .addToData("two", Base64.getEncoder().encodeToString("2".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(colorSecret).create(); mockClient.secrets().inNamespace(NAMESPACE).resource(shapeSecret).create(); @@ -339,13 +383,19 @@ void searchWithLabelsOneSecretFound() { */ @Test void searchWithLabelsOneSecretFoundAndOneFromProfileFound() { - Secret colorSecret = new SecretBuilder().withNewMetadata().withName("color-secret") - .withLabels(Collections.singletonMap("color", "blue")).endMetadata() - .addToData("one", Base64.getEncoder().encodeToString("1".getBytes())).build(); - - Secret colorSecretK8s = new SecretBuilder().withNewMetadata().withName("color-secret-k8s") - .withLabels(Collections.singletonMap("color", "red")).endMetadata() - .addToData("two", Base64.getEncoder().encodeToString("2".getBytes())).build(); + Secret colorSecret = new SecretBuilder().withNewMetadata() + .withName("color-secret") + .withLabels(Collections.singletonMap("color", "blue")) + .endMetadata() + .addToData("one", Base64.getEncoder().encodeToString("1".getBytes())) + .build(); + + Secret colorSecretK8s = new SecretBuilder().withNewMetadata() + .withName("color-secret-k8s") + .withLabels(Collections.singletonMap("color", "red")) + .endMetadata() + .addToData("two", Base64.getEncoder().encodeToString("2".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(colorSecret).create(); mockClient.secrets().inNamespace(NAMESPACE).resource(colorSecretK8s).create(); @@ -377,24 +427,40 @@ void searchWithLabelsOneSecretFoundAndOneFromProfileFound() { */ @Test void searchWithLabelsTwoSecretsFoundAndOneFromProfileFound() { - Secret colorSecret = new SecretBuilder().withNewMetadata().withName("color-secret") - .withLabels(Collections.singletonMap("color", "blue")).endMetadata() - .addToData("one", Base64.getEncoder().encodeToString("1".getBytes())).build(); - - Secret shapeSecret = new SecretBuilder().withNewMetadata().withName("shape-secret") - .withLabels(Map.of("color", "blue", "shape", "round")).endMetadata() - .addToData("two", Base64.getEncoder().encodeToString("2".getBytes())).build(); - - Secret noFit = new SecretBuilder().withNewMetadata().withName("no-fit").withLabels(Map.of("tag", "no-fit")) - .endMetadata().addToData("three", Base64.getEncoder().encodeToString("3".getBytes())).build(); - - Secret colorSecretK8s = new SecretBuilder().withNewMetadata().withName("color-secret-k8s") - .withLabels(Map.of("color", "red")).endMetadata() - .addToData("four", Base64.getEncoder().encodeToString("4".getBytes())).build(); - - Secret shapeSecretK8s = new SecretBuilder().withNewMetadata().withName("shape-secret-k8s") - .withLabels(Map.of("shape", "triangle")).endMetadata() - .addToData("five", Base64.getEncoder().encodeToString("5".getBytes())).build(); + Secret colorSecret = new SecretBuilder().withNewMetadata() + .withName("color-secret") + .withLabels(Collections.singletonMap("color", "blue")) + .endMetadata() + .addToData("one", Base64.getEncoder().encodeToString("1".getBytes())) + .build(); + + Secret shapeSecret = new SecretBuilder().withNewMetadata() + .withName("shape-secret") + .withLabels(Map.of("color", "blue", "shape", "round")) + .endMetadata() + .addToData("two", Base64.getEncoder().encodeToString("2".getBytes())) + .build(); + + Secret noFit = new SecretBuilder().withNewMetadata() + .withName("no-fit") + .withLabels(Map.of("tag", "no-fit")) + .endMetadata() + .addToData("three", Base64.getEncoder().encodeToString("3".getBytes())) + .build(); + + Secret colorSecretK8s = new SecretBuilder().withNewMetadata() + .withName("color-secret-k8s") + .withLabels(Map.of("color", "red")) + .endMetadata() + .addToData("four", Base64.getEncoder().encodeToString("4".getBytes())) + .build(); + + Secret shapeSecretK8s = new SecretBuilder().withNewMetadata() + .withName("shape-secret-k8s") + .withLabels(Map.of("shape", "triangle")) + .endMetadata() + .addToData("five", Base64.getEncoder().encodeToString("5".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(colorSecret).create(); mockClient.secrets().inNamespace(NAMESPACE).resource(shapeSecret).create(); @@ -432,9 +498,12 @@ void searchWithLabelsTwoSecretsFoundAndOneFromProfileFound() { */ @Test void testYaml() { - Secret colorSecret = new SecretBuilder().withNewMetadata().withName("color-secret") - .withLabels(Collections.singletonMap("color", "blue")).endMetadata() - .addToData("test.yaml", Base64.getEncoder().encodeToString("color: blue".getBytes())).build(); + Secret colorSecret = new SecretBuilder().withNewMetadata() + .withName("color-secret") + .withLabels(Collections.singletonMap("color", "blue")) + .endMetadata() + .addToData("test.yaml", Base64.getEncoder().encodeToString("color: blue".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(colorSecret).create(); @@ -461,12 +530,19 @@ void testYaml() { */ @Test void cache(CapturedOutput output) { - Secret red = new SecretBuilder().withNewMetadata().withName("red") - .withLabels(Collections.singletonMap("color", "red")).endMetadata() - .addToData("one", Base64.getEncoder().encodeToString("1".getBytes())).build(); - - Secret green = new SecretBuilder().withNewMetadata().withName("green").withLabels(Map.of("color", "green")) - .endMetadata().addToData("two", Base64.getEncoder().encodeToString("2".getBytes())).build(); + Secret red = new SecretBuilder().withNewMetadata() + .withName("red") + .withLabels(Collections.singletonMap("color", "red")) + .endMetadata() + .addToData("one", Base64.getEncoder().encodeToString("1".getBytes())) + .build(); + + Secret green = new SecretBuilder().withNewMetadata() + .withName("green") + .withLabels(Map.of("color", "green")) + .endMetadata() + .addToData("two", Base64.getEncoder().encodeToString("2".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(red).create(); mockClient.secrets().inNamespace(NAMESPACE).resource(green).create(); diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/MissingActuatorTest.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/MissingActuatorTest.java index f8a26f8d88..a812036be1 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/MissingActuatorTest.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/MissingActuatorTest.java @@ -47,9 +47,9 @@ public void unknownClassProtected(CapturedOutput capturedOutput) { "spring.cloud.kubernetes.client.namespace=default")) { String output = capturedOutput.toString(); assertThat(output) - .doesNotContain("Failed to introspect annotations on" - + " [class org.springframework.cloud.autoconfigure.RefreshEndpointAutoConfiguration") - .doesNotContain("TypeNotPresentExceptionProxy"); + .doesNotContain("Failed to introspect annotations on" + + " [class org.springframework.cloud.autoconfigure.RefreshEndpointAutoConfiguration") + .doesNotContain("TypeNotPresentExceptionProxy"); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/MultipleConfigMapsTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/MultipleConfigMapsTests.java index 322b2416dd..a502102d5c 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/MultipleConfigMapsTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/MultipleConfigMapsTests.java @@ -78,9 +78,14 @@ public static void setUpBeforeClass(KubernetesClient mockClient) { private static void createConfigmap(KubernetesClient client, String configMapName, String namespace, Map data) { - client.configMaps().inNamespace(namespace).resource( - new ConfigMapBuilder().withNewMetadata().withName(configMapName).endMetadata().addToData(data).build()) - .create(); + client.configMaps() + .inNamespace(namespace) + .resource(new ConfigMapBuilder().withNewMetadata() + .withName(configMapName) + .endMetadata() + .addToData(data) + .build()) + .create(); } // the last configmap defined in 'multiplecms.yml' has the highest priority, so @@ -106,8 +111,14 @@ public void testMessage3() { } private void assertResponse(String path, String expectedMessage) { - this.webClient.get().uri(path).exchange().expectStatus().isOk().expectBody().jsonPath("message") - .isEqualTo(expectedMessage); + this.webClient.get() + .uri(path) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("message") + .isEqualTo(expectedMessage); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/MultipleSecretsTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/MultipleSecretsTests.java index a57fdd078c..9c26498128 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/MultipleSecretsTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/MultipleSecretsTests.java @@ -58,8 +58,12 @@ public static void setUpBeforeClass(KubernetesClient mockClient) { metadata1.put("env", "env1"); metadata1.put("version", "1.0"); - Secret secret1 = new SecretBuilder().withNewMetadata().withName("name1").withLabels(metadata1).endMetadata() - .addToData("secrets.secret1", Base64.getEncoder().encodeToString(SECRET_VALUE_1.getBytes())).build(); + Secret secret1 = new SecretBuilder().withNewMetadata() + .withName("name1") + .withLabels(metadata1) + .endMetadata() + .addToData("secrets.secret1", Base64.getEncoder().encodeToString(SECRET_VALUE_1.getBytes())) + .build(); mockClient.secrets().inNamespace(DEFAULT_NAMESPACE).resource(secret1).create(); @@ -67,8 +71,12 @@ public static void setUpBeforeClass(KubernetesClient mockClient) { metadata2.put("env", "env2"); metadata2.put("version", "2.0"); - Secret secret2 = new SecretBuilder().withNewMetadata().withName("name2").withLabels(metadata2).endMetadata() - .addToData("secrets.secret2", Base64.getEncoder().encodeToString(SECRET_VALUE_2.getBytes())).build(); + Secret secret2 = new SecretBuilder().withNewMetadata() + .withName("name2") + .withLabels(metadata2) + .endMetadata() + .addToData("secrets.secret2", Base64.getEncoder().encodeToString(SECRET_VALUE_2.getBytes())) + .build(); mockClient.secrets().inNamespace(ANOTHER_NAMESPACE).resource(secret2).create(); } @@ -84,8 +92,14 @@ public void testSecret2() { } private void assertResponse(String path, String expectedMessage) { - this.webClient.get().uri(path).exchange().expectStatus().isOk().expectBody().jsonPath("secret") - .isEqualTo(expectedMessage); + this.webClient.get() + .uri(path) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("secret") + .isEqualTo(expectedMessage); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/NamedConfigMapContextToSourceDataProviderTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/NamedConfigMapContextToSourceDataProviderTests.java index 8cee57c24b..79f2f134ed 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/NamedConfigMapContextToSourceDataProviderTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/NamedConfigMapContextToSourceDataProviderTests.java @@ -83,8 +83,11 @@ void afterEach() { @Test void noMatch() { - ConfigMap configMap = new ConfigMapBuilder().withNewMetadata().withName("red").endMetadata() - .addToData(COLOR_REALLY_RED).build(); + ConfigMap configMap = new ConfigMapBuilder().withNewMetadata() + .withName("red") + .endMetadata() + .addToData(COLOR_REALLY_RED) + .build(); mockClient.configMaps().inNamespace(NAMESPACE).resource(configMap).create(); @@ -109,8 +112,11 @@ void noMatch() { @Test void match() { - ConfigMap configMap = new ConfigMapBuilder().withNewMetadata().withName("red").endMetadata() - .addToData(COLOR_REALLY_RED).build(); + ConfigMap configMap = new ConfigMapBuilder().withNewMetadata() + .withName("red") + .endMetadata() + .addToData(COLOR_REALLY_RED) + .build(); mockClient.configMaps().inNamespace(NAMESPACE).resource(configMap).create(); @@ -136,11 +142,17 @@ void match() { @Test void matchIncludeSingleProfile() { - ConfigMap red = new ConfigMapBuilder().withNewMetadata().withName("red").endMetadata() - .addToData(COLOR_REALLY_RED).build(); + ConfigMap red = new ConfigMapBuilder().withNewMetadata() + .withName("red") + .endMetadata() + .addToData(COLOR_REALLY_RED) + .build(); - ConfigMap redWithProfile = new ConfigMapBuilder().withNewMetadata().withName("red-with-profile").endMetadata() - .addToData("taste", "mango").build(); + ConfigMap redWithProfile = new ConfigMapBuilder().withNewMetadata() + .withName("red-with-profile") + .endMetadata() + .addToData("taste", "mango") + .build(); mockClient.configMaps().inNamespace(NAMESPACE).resource(red).create(); mockClient.configMaps().inNamespace(NAMESPACE).resource(redWithProfile).create(); @@ -175,11 +187,17 @@ void matchIncludeSingleProfile() { @Test void matchIncludeSingleProfileWithPrefix() { - ConfigMap red = new ConfigMapBuilder().withNewMetadata().withName("red").endMetadata() - .addToData(COLOR_REALLY_RED).build(); + ConfigMap red = new ConfigMapBuilder().withNewMetadata() + .withName("red") + .endMetadata() + .addToData(COLOR_REALLY_RED) + .build(); - ConfigMap redWithProfile = new ConfigMapBuilder().withNewMetadata().withName("red-with-profile").endMetadata() - .addToData("taste", "mango").build(); + ConfigMap redWithProfile = new ConfigMapBuilder().withNewMetadata() + .withName("red-with-profile") + .endMetadata() + .addToData("taste", "mango") + .build(); mockClient.configMaps().inNamespace(NAMESPACE).resource(red).create(); mockClient.configMaps().inNamespace(NAMESPACE).resource(redWithProfile).create(); @@ -213,14 +231,23 @@ void matchIncludeSingleProfileWithPrefix() { @Test void matchIncludeTwoProfilesWithPrefix() { - ConfigMap red = new ConfigMapBuilder().withNewMetadata().withName("red").endMetadata() - .addToData(COLOR_REALLY_RED).build(); + ConfigMap red = new ConfigMapBuilder().withNewMetadata() + .withName("red") + .endMetadata() + .addToData(COLOR_REALLY_RED) + .build(); - ConfigMap redWithTaste = new ConfigMapBuilder().withNewMetadata().withName("red-with-taste").endMetadata() - .addToData("taste", "mango").build(); + ConfigMap redWithTaste = new ConfigMapBuilder().withNewMetadata() + .withName("red-with-taste") + .endMetadata() + .addToData("taste", "mango") + .build(); - ConfigMap redWithShape = new ConfigMapBuilder().withNewMetadata().withName("red-with-shape").endMetadata() - .addToData("shape", "round").build(); + ConfigMap redWithShape = new ConfigMapBuilder().withNewMetadata() + .withName("red-with-shape") + .endMetadata() + .addToData("shape", "round") + .build(); mockClient.configMaps().inNamespace(NAMESPACE).resource(red).create(); mockClient.configMaps().inNamespace(NAMESPACE).resource(redWithTaste).create(); @@ -253,8 +280,11 @@ void matchIncludeTwoProfilesWithPrefix() { */ @Test void matchWithName() { - ConfigMap configMap = new ConfigMapBuilder().withNewMetadata().withName("application").endMetadata() - .addToData("color", "red").build(); + ConfigMap configMap = new ConfigMapBuilder().withNewMetadata() + .withName("application") + .endMetadata() + .addToData("color", "red") + .build(); mockClient.configMaps().inNamespace(NAMESPACE).resource(configMap).create(); @@ -279,8 +309,11 @@ void matchWithName() { @Test void namespaceMatch() { - ConfigMap configMap = new ConfigMapBuilder().withNewMetadata().withName("red").endMetadata() - .addToData(COLOR_REALLY_RED).build(); + ConfigMap configMap = new ConfigMapBuilder().withNewMetadata() + .withName("red") + .endMetadata() + .addToData(COLOR_REALLY_RED) + .build(); mockClient.configMaps().inNamespace(NAMESPACE).resource(configMap).create(); @@ -303,8 +336,11 @@ void namespaceMatch() { */ @Test void testSingleYaml() { - ConfigMap configMap = new ConfigMapBuilder().withNewMetadata().withName("red").endMetadata() - .addToData("single.yaml", "key: value").build(); + ConfigMap configMap = new ConfigMapBuilder().withNewMetadata() + .withName("red") + .endMetadata() + .addToData("single.yaml", "key: value") + .build(); mockClient.configMaps().inNamespace(NAMESPACE).resource(configMap).create(); @@ -329,8 +365,11 @@ void testSingleYaml() { */ @Test void testCorrectNameWithProfile() { - ConfigMap configMap = new ConfigMapBuilder().withNewMetadata().withName("one").endMetadata() - .addToData("key", "value").build(); + ConfigMap configMap = new ConfigMapBuilder().withNewMetadata() + .withName("one") + .endMetadata() + .addToData("key", "value") + .build(); mockClient.configMaps().inNamespace(NAMESPACE).resource(configMap).create(); MockEnvironment environment = new MockEnvironment(); @@ -356,11 +395,17 @@ void testCorrectNameWithProfile() { @Test void cache(CapturedOutput output) { - ConfigMap red = new ConfigMapBuilder().withNewMetadata().withName("red").endMetadata() - .addToData(COLOR_REALLY_RED).build(); - - ConfigMap green = new ConfigMapBuilder().withNewMetadata().withName("green").endMetadata() - .addToData("taste", "mango").build(); + ConfigMap red = new ConfigMapBuilder().withNewMetadata() + .withName("red") + .endMetadata() + .addToData(COLOR_REALLY_RED) + .build(); + + ConfigMap green = new ConfigMapBuilder().withNewMetadata() + .withName("green") + .endMetadata() + .addToData("taste", "mango") + .build(); mockClient.configMaps().inNamespace(NAMESPACE).resource(red).create(); mockClient.configMaps().inNamespace(NAMESPACE).resource(green).create(); diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/NamedSecretContextToSourceDataProviderTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/NamedSecretContextToSourceDataProviderTests.java index f92b338395..2888d33294 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/NamedSecretContextToSourceDataProviderTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/NamedSecretContextToSourceDataProviderTests.java @@ -79,8 +79,11 @@ void afterEach() { @Test void singleSecretMatchAgainstLabels() { - Secret secret = new SecretBuilder().withNewMetadata().withName("red").endMetadata() - .addToData("color", Base64.getEncoder().encodeToString("really-red".getBytes())).build(); + Secret secret = new SecretBuilder().withNewMetadata() + .withName("red") + .endMetadata() + .addToData("color", Base64.getEncoder().encodeToString("really-red".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(secret).create(); @@ -103,14 +106,23 @@ void singleSecretMatchAgainstLabels() { @Test void twoSecretMatchAgainstLabels() { - Secret red = new SecretBuilder().withNewMetadata().withName("red").endMetadata() - .addToData("color", Base64.getEncoder().encodeToString("really-red".getBytes())).build(); + Secret red = new SecretBuilder().withNewMetadata() + .withName("red") + .endMetadata() + .addToData("color", Base64.getEncoder().encodeToString("really-red".getBytes())) + .build(); - Secret blue = new SecretBuilder().withNewMetadata().withName("blue").endMetadata() - .addToData("color", Base64.getEncoder().encodeToString("really-blue".getBytes())).build(); + Secret blue = new SecretBuilder().withNewMetadata() + .withName("blue") + .endMetadata() + .addToData("color", Base64.getEncoder().encodeToString("really-blue".getBytes())) + .build(); - Secret yellow = new SecretBuilder().withNewMetadata().withName("yellow").endMetadata() - .addToData("color", Base64.getEncoder().encodeToString("really-yellow".getBytes())).build(); + Secret yellow = new SecretBuilder().withNewMetadata() + .withName("yellow") + .endMetadata() + .addToData("color", Base64.getEncoder().encodeToString("really-yellow".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(red).create(); mockClient.secrets().inNamespace(NAMESPACE).resource(blue).create(); @@ -135,8 +147,11 @@ void twoSecretMatchAgainstLabels() { @Test void testSecretNoMatch() { - Secret pink = new SecretBuilder().withNewMetadata().withName("pink").endMetadata() - .addToData("color", Base64.getEncoder().encodeToString("pink".getBytes())).build(); + Secret pink = new SecretBuilder().withNewMetadata() + .withName("pink") + .endMetadata() + .addToData("color", Base64.getEncoder().encodeToString("pink".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(pink).create(); @@ -160,8 +175,11 @@ void testSecretNoMatch() { @Test void namespaceMatch() { - Secret secret = new SecretBuilder().withNewMetadata().withName("red").endMetadata() - .addToData("color", Base64.getEncoder().encodeToString("really-red".getBytes())).build(); + Secret secret = new SecretBuilder().withNewMetadata() + .withName("red") + .endMetadata() + .addToData("color", Base64.getEncoder().encodeToString("really-red".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(secret).create(); @@ -184,11 +202,17 @@ void namespaceMatch() { @Test void matchIncludeSingleProfile() { - Secret red = new SecretBuilder().withNewMetadata().withName("red").endMetadata() - .addToData("color", Base64.getEncoder().encodeToString("really-red".getBytes())).build(); + Secret red = new SecretBuilder().withNewMetadata() + .withName("red") + .endMetadata() + .addToData("color", Base64.getEncoder().encodeToString("really-red".getBytes())) + .build(); - Secret redWithProfile = new SecretBuilder().withNewMetadata().withName("red-with-profile").endMetadata() - .addToData("taste", Base64.getEncoder().encodeToString("mango".getBytes())).build(); + Secret redWithProfile = new SecretBuilder().withNewMetadata() + .withName("red-with-profile") + .endMetadata() + .addToData("taste", Base64.getEncoder().encodeToString("mango".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(red).create(); mockClient.secrets().inNamespace(NAMESPACE).resource(redWithProfile).create(); @@ -219,11 +243,17 @@ void matchIncludeSingleProfile() { @Test void matchIncludeSingleProfileWithPrefix() { - Secret red = new SecretBuilder().withNewMetadata().withName("red").endMetadata() - .addToData("color", Base64.getEncoder().encodeToString("really-red".getBytes())).build(); + Secret red = new SecretBuilder().withNewMetadata() + .withName("red") + .endMetadata() + .addToData("color", Base64.getEncoder().encodeToString("really-red".getBytes())) + .build(); - Secret redWithProfile = new SecretBuilder().withNewMetadata().withName("red-with-profile").endMetadata() - .addToData("taste", Base64.getEncoder().encodeToString("mango".getBytes())).build(); + Secret redWithProfile = new SecretBuilder().withNewMetadata() + .withName("red-with-profile") + .endMetadata() + .addToData("taste", Base64.getEncoder().encodeToString("mango".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(red).create(); mockClient.secrets().inNamespace(NAMESPACE).resource(redWithProfile).create(); @@ -255,14 +285,23 @@ void matchIncludeSingleProfileWithPrefix() { @Test void matchIncludeTwoProfilesWithPrefix() { - Secret red = new SecretBuilder().withNewMetadata().withName("red").endMetadata() - .addToData("color", Base64.getEncoder().encodeToString("really-red".getBytes())).build(); + Secret red = new SecretBuilder().withNewMetadata() + .withName("red") + .endMetadata() + .addToData("color", Base64.getEncoder().encodeToString("really-red".getBytes())) + .build(); - Secret redWithTaste = new SecretBuilder().withNewMetadata().withName("red-with-taste").endMetadata() - .addToData("taste", Base64.getEncoder().encodeToString("mango".getBytes())).build(); + Secret redWithTaste = new SecretBuilder().withNewMetadata() + .withName("red-with-taste") + .endMetadata() + .addToData("taste", Base64.getEncoder().encodeToString("mango".getBytes())) + .build(); - Secret redWithShape = new SecretBuilder().withNewMetadata().withName("red-with-shape").endMetadata() - .addToData("shape", Base64.getEncoder().encodeToString("round".getBytes())).build(); + Secret redWithShape = new SecretBuilder().withNewMetadata() + .withName("red-with-shape") + .endMetadata() + .addToData("shape", Base64.getEncoder().encodeToString("round".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(red).create(); mockClient.secrets().inNamespace(NAMESPACE).resource(redWithTaste).create(); @@ -295,8 +334,11 @@ void matchIncludeTwoProfilesWithPrefix() { */ @Test void testSingleYaml() { - Secret secret = new SecretBuilder().withNewMetadata().withName("single-yaml").endMetadata() - .addToData("single.yaml", Base64.getEncoder().encodeToString("key: value".getBytes())).build(); + Secret secret = new SecretBuilder().withNewMetadata() + .withName("single-yaml") + .endMetadata() + .addToData("single.yaml", Base64.getEncoder().encodeToString("key: value".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(secret).create(); @@ -322,11 +364,17 @@ void testSingleYaml() { @Test void cache(CapturedOutput output) { - Secret red = new SecretBuilder().withNewMetadata().withName("red").endMetadata() - .addToData("color", Base64.getEncoder().encodeToString("red".getBytes())).build(); - - Secret green = new SecretBuilder().withNewMetadata().withName("green").endMetadata() - .addToData("taste", Base64.getEncoder().encodeToString("mango".getBytes())).build(); + Secret red = new SecretBuilder().withNewMetadata() + .withName("red") + .endMetadata() + .addToData("color", Base64.getEncoder().encodeToString("red".getBytes())) + .build(); + + Secret green = new SecretBuilder().withNewMetadata() + .withName("green") + .endMetadata() + .addToData("taste", Base64.getEncoder().encodeToString("mango".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(red).create(); mockClient.secrets().inNamespace(NAMESPACE).resource(green).create(); diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/SecretsEnableRetryWithoutFailFastTest.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/SecretsEnableRetryWithoutFailFastTest.java index 55564adb1f..69b5e7cf3b 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/SecretsEnableRetryWithoutFailFastTest.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/SecretsEnableRetryWithoutFailFastTest.java @@ -63,7 +63,9 @@ protected void setup(String... env) { ConfigurationPropertiesBindingPostProcessor.class, ConfigurationPropertiesRebinderAutoConfiguration.class, Fabric8BootstrapConfiguration.class, Fabric8RetryBootstrapConfiguration.class, KubernetesBootstrapConfiguration.class) - .web(org.springframework.boot.WebApplicationType.NONE).properties(envArray).run(); + .web(org.springframework.boot.WebApplicationType.NONE) + .properties(envArray) + .run(); } @AfterEach diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/actuator/DisabledHealthTest.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/actuator/DisabledHealthTest.java index 3dfc1cc401..972ab3c40d 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/actuator/DisabledHealthTest.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/actuator/DisabledHealthTest.java @@ -47,9 +47,15 @@ class DisabledHealthTest { @Test void healthEndpointShouldContainKubernetes() { - this.webClient.get().uri("http://localhost:{port}/actuator/health", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("components.kubernetes").doesNotExist(); + this.webClient.get() + .uri("http://localhost:{port}/actuator/health", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("components.kubernetes") + .doesNotExist(); Assertions.assertNull(registry.getContributor("kubernetes"), "reactive kubernetes contributor must NOT be present when 'management.health.kubernetes.enabled=false'"); diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/actuator/EnabledHealthTest.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/actuator/EnabledHealthTest.java index 7058e34b8a..20c834a787 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/actuator/EnabledHealthTest.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/actuator/EnabledHealthTest.java @@ -48,9 +48,15 @@ class EnabledHealthTest { @Test void healthEndpointShouldContainKubernetes() { - this.webClient.get().uri("http://localhost:{port}/actuator/health", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("components.kubernetes").exists(); + this.webClient.get() + .uri("http://localhost:{port}/actuator/health", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("components.kubernetes") + .exists(); Assertions.assertNotNull(registry.getContributor("kubernetes"), "reactive kubernetes contributor must be present when 'management.health.kubernetes.enabled=true'"); diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/labeled_config_map_with_prefix/LabeledConfigMapWithPrefixTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/labeled_config_map_with_prefix/LabeledConfigMapWithPrefixTests.java index b08ce3c280..e18517252f 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/labeled_config_map_with_prefix/LabeledConfigMapWithPrefixTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/labeled_config_map_with_prefix/LabeledConfigMapWithPrefixTests.java @@ -63,8 +63,15 @@ static void setUpBeforeClass(KubernetesClient mockClient) { } private static void createConfigMap(String name, Map data, Map labels) { - mockClient.configMaps().inNamespace("spring-k8s").resource(new ConfigMapBuilder().withNewMetadata() - .withName(name).withLabels(labels).endMetadata().addToData(data).build()).create(); + mockClient.configMaps() + .inNamespace("spring-k8s") + .resource(new ConfigMapBuilder().withNewMetadata() + .withName(name) + .withLabels(labels) + .endMetadata() + .addToData(data) + .build()) + .create(); } /** @@ -78,8 +85,13 @@ private static void createConfigMap(String name, Map data, Map data, Map labels) { - mockClient.configMaps().inNamespace("spring-k8s").resource(new ConfigMapBuilder().withNewMetadata() - .withName(name).withLabels(labels).endMetadata().addToData(data).build()).create(); + mockClient.configMaps() + .inNamespace("spring-k8s") + .resource(new ConfigMapBuilder().withNewMetadata() + .withName(name) + .withLabels(labels) + .endMetadata() + .addToData(data) + .build()) + .create(); } /** @@ -116,8 +123,13 @@ private static void createConfigMap(String name, Map data, Map data, Map labels) { - mockClient.secrets().inNamespace("spring-k8s").resource(new SecretBuilder().withNewMetadata().withName(name) - .withLabels(labels).endMetadata().addToData(data).build()).create(); + mockClient.secrets() + .inNamespace("spring-k8s") + .resource(new SecretBuilder().withNewMetadata() + .withName(name) + .withLabels(labels) + .endMetadata() + .addToData(data) + .build()) + .create(); } /** @@ -85,8 +92,13 @@ private static void createSecret(String name, Map data, Map data, Map labels) { - mockClient.secrets().inNamespace("spring-k8s").resource(new SecretBuilder().withNewMetadata().withName(name) - .withLabels(labels).endMetadata().addToData(data).build()).create(); + mockClient.secrets() + .inNamespace("spring-k8s") + .resource(new SecretBuilder().withNewMetadata() + .withName(name) + .withLabels(labels) + .endMetadata() + .addToData(data) + .build()) + .create(); } /** @@ -127,8 +134,13 @@ private static void createSecret(String name, Map data, Map psl.locate(new MockEnvironment())).isInstanceOf(IllegalStateException.class) - .hasMessageContaining("v1/namespaces/default/configmaps. Message: Internal Server Error"); + .hasMessageContaining("v1/namespaces/default/configmaps. Message: Internal Server Error"); // verify that propertySourceLocator.locate is called only once verify(psl, times(1)).locate(any()); diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/locator_retry/config_retry_enabled/ConfigRetryEnabled.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/locator_retry/config_retry_enabled/ConfigRetryEnabled.java index 27ecd4e670..5cdd49819b 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/locator_retry/config_retry_enabled/ConfigRetryEnabled.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/locator_retry/config_retry_enabled/ConfigRetryEnabled.java @@ -73,10 +73,17 @@ void locateShouldNotRetryWhenThereIsNoFailure() { data.put("some.number", "0"); // return config map without failing - mockServer - .expect().withPath(API).andReturn(200, new ConfigMapListBuilder().withItems(new ConfigMapBuilder() - .withNewMetadata().withName("application").endMetadata().addToData(data).build()).build()) - .once(); + mockServer.expect() + .withPath(API) + .andReturn(200, + new ConfigMapListBuilder() + .withItems(new ConfigMapBuilder().withNewMetadata() + .withName("application") + .endMetadata() + .addToData(data) + .build()) + .build()) + .once(); PropertySource propertySource = Assertions.assertDoesNotThrow(() -> psl.locate(new MockEnvironment())); @@ -96,10 +103,17 @@ void locateShouldRetryAndRecover() { // fail 3 times then succeed at the 4th call mockServer.expect().withPath(API).andReturn(500, "Internal Server Error").times(3); - mockServer - .expect().withPath(API).andReturn(200, new ConfigMapListBuilder().withItems(new ConfigMapBuilder() - .withNewMetadata().withName("application").endMetadata().addToData(data).build()).build()) - .once(); + mockServer.expect() + .withPath(API) + .andReturn(200, + new ConfigMapListBuilder() + .withItems(new ConfigMapBuilder().withNewMetadata() + .withName("application") + .endMetadata() + .addToData(data) + .build()) + .build()) + .once(); PropertySource propertySource = Assertions.assertDoesNotThrow(() -> psl.locate(new MockEnvironment())); @@ -117,7 +131,7 @@ void locateShouldRetryAndFail() { mockServer.expect().withPath(API).andReturn(500, "Internal Server Error").times(5); assertThatThrownBy(() -> psl.locate(new MockEnvironment())).isInstanceOf(IllegalStateException.class) - .hasMessageContaining("api/v1/namespaces/default/configmaps. Message: Internal Server Error"); + .hasMessageContaining("api/v1/namespaces/default/configmaps. Message: Internal Server Error"); // verify retried 5 times until failure verify(verifiablePsl, times(5)).locate(any()); diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/locator_retry/fail_fast_enabled_retry_disabled/ConfigFailFastEnabledButRetryDisabled.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/locator_retry/fail_fast_enabled_retry_disabled/ConfigFailFastEnabledButRetryDisabled.java index 5ee02b5874..a1aaccd076 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/locator_retry/fail_fast_enabled_retry_disabled/ConfigFailFastEnabledButRetryDisabled.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/locator_retry/fail_fast_enabled_retry_disabled/ConfigFailFastEnabledButRetryDisabled.java @@ -74,8 +74,8 @@ void locateShouldFailWithoutRetrying() { assertThat(context.containsBean("kubernetesConfigRetryInterceptor")).isFalse(); assertThatThrownBy(() -> propertySourceLocator.locate(new MockEnvironment())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("api/v1/namespaces/default/configmaps. Message: Not Found."); + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("api/v1/namespaces/default/configmaps. Message: Not Found."); // verify that propertySourceLocator.locate is called only once verify(propertySourceLocator, times(1)).locate(any()); diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/named_config_map_with_prefix/NamedConfigMapWithPrefixTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/named_config_map_with_prefix/NamedConfigMapWithPrefixTests.java index 3e1c672073..d3eb6bc409 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/named_config_map_with_prefix/NamedConfigMapWithPrefixTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/named_config_map_with_prefix/NamedConfigMapWithPrefixTests.java @@ -64,9 +64,10 @@ static void setUpBeforeClass(KubernetesClient mockClient) { } static void createConfigmap(String name, Map data) { - mockClient.configMaps().inNamespace("spring-k8s") - .resource(new ConfigMapBuilder().withNewMetadata().withName(name).endMetadata().addToData(data).build()) - .create(); + mockClient.configMaps() + .inNamespace("spring-k8s") + .resource(new ConfigMapBuilder().withNewMetadata().withName(name).endMetadata().addToData(data).build()) + .create(); } /** @@ -80,8 +81,13 @@ static void createConfigmap(String name, Map data) { */ @Test void testOne() { - this.webClient.get().uri("/named-config-map/prefix/one").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("one")); + this.webClient.get() + .uri("/named-config-map/prefix/one") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("one")); } /** @@ -95,8 +101,13 @@ void testOne() { */ @Test void testTwo() { - this.webClient.get().uri("/named-config-map/prefix/two").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("two")); + this.webClient.get() + .uri("/named-config-map/prefix/two") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("two")); } /** @@ -110,8 +121,13 @@ void testTwo() { */ @Test void testThree() { - this.webClient.get().uri("/named-config-map/prefix/three").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("three")); + this.webClient.get() + .uri("/named-config-map/prefix/three") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("three")); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/named_config_map_with_profile/NamedConfigMapWithProfileTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/named_config_map_with_profile/NamedConfigMapWithProfileTests.java index e0f99ff660..1f2dade4cc 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/named_config_map_with_profile/NamedConfigMapWithProfileTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/named_config_map_with_profile/NamedConfigMapWithProfileTests.java @@ -72,9 +72,10 @@ static void setUpBeforeClass(KubernetesClient mockClient) { } static void createConfigmap(String name, Map data) { - mockClient.configMaps().inNamespace("spring-k8s") - .resource(new ConfigMapBuilder().withNewMetadata().withName(name).endMetadata().addToData(data).build()) - .create(); + mockClient.configMaps() + .inNamespace("spring-k8s") + .resource(new ConfigMapBuilder().withNewMetadata().withName(name).endMetadata().addToData(data).build()) + .create(); } /** @@ -90,8 +91,13 @@ static void createConfigmap(String name, Map data) { */ @Test void testOne() { - this.webClient.get().uri("/named-configmap/profile/one").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("one-from-k8s")); + this.webClient.get() + .uri("/named-configmap/profile/one") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("one-from-k8s")); } /** @@ -108,8 +114,13 @@ void testOne() { */ @Test void testTwo() { - this.webClient.get().uri("/named-configmap/profile/two").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("two")); + this.webClient.get() + .uri("/named-configmap/profile/two") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("two")); } /** @@ -125,8 +136,13 @@ void testTwo() { */ @Test void testThree() { - this.webClient.get().uri("/named-configmap/profile/three").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("three-from-k8s")); + this.webClient.get() + .uri("/named-configmap/profile/three") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("three-from-k8s")); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/named_secret_with_prefix/NamedSecretWithPrefixTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/named_secret_with_prefix/NamedSecretWithPrefixTests.java index 902eacf042..c981576e44 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/named_secret_with_prefix/NamedSecretWithPrefixTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/named_secret_with_prefix/NamedSecretWithPrefixTests.java @@ -66,9 +66,10 @@ static void setUpBeforeClass(KubernetesClient mockClient) { } private static void createSecret(String name, Map data) { - mockClient.secrets().inNamespace("spring-k8s") - .resource(new SecretBuilder().withNewMetadata().withName(name).endMetadata().addToData(data).build()) - .create(); + mockClient.secrets() + .inNamespace("spring-k8s") + .resource(new SecretBuilder().withNewMetadata().withName(name).endMetadata().addToData(data).build()) + .create(); } /** @@ -82,8 +83,13 @@ private static void createSecret(String name, Map data) { */ @Test void testOne() { - this.webClient.get().uri("/named-secret/prefix/one").exchange().expectStatus().isOk().expectBody(String.class) - .value(Matchers.equalTo("one")); + this.webClient.get() + .uri("/named-secret/prefix/one") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("one")); } /** @@ -97,8 +103,13 @@ void testOne() { */ @Test void testTwo() { - this.webClient.get().uri("/named-secret/prefix/two").exchange().expectStatus().isOk().expectBody(String.class) - .value(Matchers.equalTo("two")); + this.webClient.get() + .uri("/named-secret/prefix/two") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("two")); } /** @@ -112,8 +123,13 @@ void testTwo() { */ @Test void testThree() { - this.webClient.get().uri("/named-secret/prefix/three").exchange().expectStatus().isOk().expectBody(String.class) - .value(Matchers.equalTo("three")); + this.webClient.get() + .uri("/named-secret/prefix/three") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("three")); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/named_secret_with_profile/NamedSecretWithProfileTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/named_secret_with_profile/NamedSecretWithProfileTests.java index d36bcf9ee6..8b02881b19 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/named_secret_with_profile/NamedSecretWithProfileTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/named_secret_with_profile/NamedSecretWithProfileTests.java @@ -80,9 +80,10 @@ static void setUpBeforeClass(KubernetesClient mockClient) { } private static void createSecret(String name, Map data) { - mockClient.secrets().inNamespace("spring-k8s") - .resource(new SecretBuilder().withNewMetadata().withName(name).endMetadata().addToData(data).build()) - .create(); + mockClient.secrets() + .inNamespace("spring-k8s") + .resource(new SecretBuilder().withNewMetadata().withName(name).endMetadata().addToData(data).build()) + .create(); } /** @@ -98,8 +99,13 @@ private static void createSecret(String name, Map data) { */ @Test void testOne() { - this.webClient.get().uri("/named-secret/profile/one").exchange().expectStatus().isOk().expectBody(String.class) - .value(Matchers.equalTo("one-from-k8s")); + this.webClient.get() + .uri("/named-secret/profile/one") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("one-from-k8s")); } /** @@ -116,8 +122,13 @@ void testOne() { */ @Test void testTwo() { - this.webClient.get().uri("/named-secret/profile/two").exchange().expectStatus().isOk().expectBody(String.class) - .value(Matchers.equalTo("two")); + this.webClient.get() + .uri("/named-secret/profile/two") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("two")); } /** @@ -133,8 +144,13 @@ void testTwo() { */ @Test void testThree() { - this.webClient.get().uri("/named-secret/profile/three").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("three-from-k8s")); + this.webClient.get() + .uri("/named-secret/profile/three") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("three-from-k8s")); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/reload/ConfigReloadAutoConfigurationTest.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/reload/ConfigReloadAutoConfigurationTest.java index 31b8981757..a01cf9107a 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/reload/ConfigReloadAutoConfigurationTest.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/reload/ConfigReloadAutoConfigurationTest.java @@ -73,12 +73,18 @@ static void setUpBeforeClass() { HashMap data = new HashMap<>(); data.put("bean.greeting", "Hello ConfigMap, %s!"); - ConfigMap configMap1 = new ConfigMapBuilder().withNewMetadata().withName(APPLICATION_NAME).endMetadata() - .addToData(data).build(); + ConfigMap configMap1 = new ConfigMapBuilder().withNewMetadata() + .withName(APPLICATION_NAME) + .endMetadata() + .addToData(data) + .build(); mockClient.configMaps().inNamespace("test").resource(configMap1).create(); - ConfigMap configMap2 = new ConfigMapBuilder().withNewMetadata().withName(APPLICATION_NAME).endMetadata() - .addToData(data).build(); + ConfigMap configMap2 = new ConfigMapBuilder().withNewMetadata() + .withName(APPLICATION_NAME) + .endMetadata() + .addToData(data) + .build(); mockClient.configMaps().inNamespace("spring").resource(configMap2).create(); } @@ -125,8 +131,11 @@ void reloadEventEnabledMonitoringConfigMapsEnabledByDefault() { "spring.main.cloud-platform=KUBERNETES"); Map map = getContext().getBeansOfType(ConfigurationChangeDetector.class); Assertions.assertEquals(map.size(), 1); - Assertions.assertTrue(map.values().iterator().next().getClass() - .isAssignableFrom(Fabric8EventBasedConfigMapChangeDetector.class)); + Assertions.assertTrue(map.values() + .iterator() + .next() + .getClass() + .isAssignableFrom(Fabric8EventBasedConfigMapChangeDetector.class)); } /** @@ -146,8 +155,11 @@ void reloadEventEnabledMonitoringConfigMapsEnabled() { "spring.cloud.kubernetes.reload.mode=event", "spring.main.cloud-platform=KUBERNETES"); Map map = getContext().getBeansOfType(ConfigurationChangeDetector.class); Assertions.assertEquals(map.size(), 1); - Assertions.assertTrue(map.values().iterator().next().getClass() - .isAssignableFrom(Fabric8EventBasedConfigMapChangeDetector.class)); + Assertions.assertTrue(map.values() + .iterator() + .next() + .getClass() + .isAssignableFrom(Fabric8EventBasedConfigMapChangeDetector.class)); } /** @@ -231,8 +243,11 @@ void reloadEventEnabledMonitoringConfigMapsDisabledMonitoringSecretsEnabled() { "spring.cloud.kubernetes.reload.mode=event"); Map map = getContext().getBeansOfType(ConfigurationChangeDetector.class); Assertions.assertEquals(map.size(), 1); - Assertions.assertTrue(map.values().iterator().next().getClass() - .isAssignableFrom(Fabric8EventBasedSecretsChangeDetector.class)); + Assertions.assertTrue(map.values() + .iterator() + .next() + .getClass() + .isAssignableFrom(Fabric8EventBasedSecretsChangeDetector.class)); } /** @@ -255,8 +270,8 @@ void reloadPollingEnabledMonitoringConfigMapsDisabledMonitoringSecretsEnabled() "spring.cloud.kubernetes.reload.mode=polling"); Map map = getContext().getBeansOfType(ConfigurationChangeDetector.class); Assertions.assertEquals(map.size(), 1); - Assertions.assertTrue( - map.values().iterator().next().getClass().isAssignableFrom(PollingSecretsChangeDetector.class)); + Assertions + .assertTrue(map.values().iterator().next().getClass().isAssignableFrom(PollingSecretsChangeDetector.class)); } /** @@ -279,8 +294,10 @@ void reloadEventEnabledMonitoringConfigMapsEnabledMonitoringSecretsEnabled() { "spring.cloud.kubernetes.reload.mode=event"); Map map = getContext().getBeansOfType(ConfigurationChangeDetector.class); Assertions.assertEquals(map.size(), 2); - List result = map.values().stream() - .sorted(Comparator.comparing(x -> x.getClass().getName())).toList(); + List result = map.values() + .stream() + .sorted(Comparator.comparing(x -> x.getClass().getName())) + .toList(); Assertions.assertEquals(result.get(0).getClass(), Fabric8EventBasedConfigMapChangeDetector.class); Assertions.assertEquals(result.get(1).getClass(), Fabric8EventBasedSecretsChangeDetector.class); } @@ -305,8 +322,10 @@ void reloadPollingEnabledMonitoringConfigMapsEnabledMonitoringSecretsEnabled() { "spring.cloud.kubernetes.reload.mode=polling"); Map map = getContext().getBeansOfType(ConfigurationChangeDetector.class); Assertions.assertEquals(map.size(), 2); - List result = map.values().stream() - .sorted(Comparator.comparing(x -> x.getClass().getName())).toList(); + List result = map.values() + .stream() + .sorted(Comparator.comparing(x -> x.getClass().getName())) + .toList(); Assertions.assertEquals(result.get(0).getClass(), PollingConfigMapChangeDetector.class); Assertions.assertEquals(result.get(1).getClass(), PollingSecretsChangeDetector.class); } @@ -375,8 +394,10 @@ void reloadEventEnabledMonitoringConfigMapsEnabledMonitoringSecretsDisabled() { "spring.cloud.kubernetes.reload.monitoring-secrets=false"); Map map = getContext().getBeansOfType(ConfigurationChangeDetector.class); Assertions.assertEquals(map.size(), 1); - List result = map.values().stream() - .sorted(Comparator.comparing(x -> x.getClass().getName())).toList(); + List result = map.values() + .stream() + .sorted(Comparator.comparing(x -> x.getClass().getName())) + .toList(); Assertions.assertEquals(result.get(0).getClass(), Fabric8EventBasedConfigMapChangeDetector.class); } @@ -400,8 +421,10 @@ void reloadPollingEnabledMonitoringConfigMapsEnabledMonitoringSecretsDisabled() "spring.cloud.kubernetes.reload.monitoring-secrets=false"); Map map = getContext().getBeansOfType(ConfigurationChangeDetector.class); Assertions.assertEquals(map.size(), 1); - List result = map.values().stream() - .sorted(Comparator.comparing(x -> x.getClass().getName())).toList(); + List result = map.values() + .stream() + .sorted(Comparator.comparing(x -> x.getClass().getName())) + .toList(); Assertions.assertEquals(result.get(0).getClass(), PollingConfigMapChangeDetector.class); } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/retry/ConfigDataSecretsRetryDisabledButConfigRetryEnabled.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/retry/ConfigDataSecretsRetryDisabledButConfigRetryEnabled.java index 829f355ad6..fcfe2322a7 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/retry/ConfigDataSecretsRetryDisabledButConfigRetryEnabled.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/retry/ConfigDataSecretsRetryDisabledButConfigRetryEnabled.java @@ -66,7 +66,7 @@ public void beforeEach() { protected void assertRetryBean(ApplicationContext context) { assertThat(context.containsBean("configDataSecretsPropertySourceLocator")).isTrue(); assertThat(context.getBean("configDataSecretsPropertySourceLocator")) - .isInstanceOf(Fabric8SecretsPropertySourceLocator.class); + .isInstanceOf(Fabric8SecretsPropertySourceLocator.class); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/retry/SecretsFailFastEnabledButRetryDisabled.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/retry/SecretsFailFastEnabledButRetryDisabled.java index 4ed82085be..b61720c1d2 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/retry/SecretsFailFastEnabledButRetryDisabled.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/retry/SecretsFailFastEnabledButRetryDisabled.java @@ -73,7 +73,7 @@ void locateShouldFailWithoutRetrying() { assertThat(context.containsBean("kubernetesSecretsRetryInterceptor")).isFalse(); assertThatThrownBy(() -> psl.locate(new MockEnvironment())).isInstanceOf(IllegalStateException.class) - .hasMessageContaining("api/v1/namespaces/default/secrets. Message: Internal Server Error"); + .hasMessageContaining("api/v1/namespaces/default/secrets. Message: Internal Server Error"); // verify that propertySourceLocator.locate is called only once verify(verifiablePsl, times(1)).locate(any()); diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/retry/SecretsRetryDisabledButConfigRetryEnabled.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/retry/SecretsRetryDisabledButConfigRetryEnabled.java index 322785ac5c..dc06185538 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/retry/SecretsRetryDisabledButConfigRetryEnabled.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/retry/SecretsRetryDisabledButConfigRetryEnabled.java @@ -81,7 +81,7 @@ void locateShouldFailWithoutRetrying() { assertRetryBean(context); assertThatThrownBy(() -> psl.locate(new MockEnvironment())).isInstanceOf(IllegalStateException.class) - .hasMessageContaining("v1/namespaces/default/secrets. Message: Internal Server Error"); + .hasMessageContaining("v1/namespaces/default/secrets. Message: Internal Server Error"); // verify that propertySourceLocator.locate is called only once verify(verifiablePsl, times(1)).locate(any()); diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/retry/secrets_enabled/SecretsRetryEnabled.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/retry/secrets_enabled/SecretsRetryEnabled.java index a655dbc48f..a448c4384b 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/retry/secrets_enabled/SecretsRetryEnabled.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/retry/secrets_enabled/SecretsRetryEnabled.java @@ -73,9 +73,12 @@ void locateShouldNotRetryWhenThereIsNoFailure() { data.put("some.sensitive.number", Base64.getEncoder().encodeToString("1".getBytes())); // return secret without failing - mockServer.expect().withPath(API).andReturn(200, new SecretListBuilder().withItems( - new SecretBuilder().withNewMetadata().withName("my-secret").endMetadata().addToData(data).build()) - .build()).once(); + mockServer.expect() + .withPath(API) + .andReturn(200, new SecretListBuilder().withItems( + new SecretBuilder().withNewMetadata().withName("my-secret").endMetadata().addToData(data).build()) + .build()) + .once(); PropertySource propertySource = Assertions.assertDoesNotThrow(() -> psl.locate(new MockEnvironment())); @@ -96,9 +99,12 @@ void locateShouldRetryAndRecover() { // fail 3 times then succeed at the 4th call mockServer.expect().withPath(API).andReturn(500, "Internal Server Error").times(3); - mockServer.expect().withPath(API).andReturn(200, new SecretListBuilder().withItems( - new SecretBuilder().withNewMetadata().withName("my-secret").endMetadata().addToData(data).build()) - .build()).once(); + mockServer.expect() + .withPath(API) + .andReturn(200, new SecretListBuilder().withItems( + new SecretBuilder().withNewMetadata().withName("my-secret").endMetadata().addToData(data).build()) + .build()) + .once(); PropertySource propertySource = Assertions.assertDoesNotThrow(() -> psl.locate(new MockEnvironment())); @@ -116,7 +122,7 @@ void locateShouldRetryAndFail() { mockServer.expect().withPath(API).andReturn(500, "Internal Server Error").times(5); assertThatThrownBy(() -> psl.locate(new MockEnvironment())).isInstanceOf(IllegalStateException.class) - .hasMessageContaining("api/v1/namespaces/default/secrets. Message: Internal Server Error."); + .hasMessageContaining("api/v1/namespaces/default/secrets. Message: Internal Server Error."); // verify retried 5 times until failure verify(verifiablePsl, times(5)).locate(any()); diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/retryable_sources_order/RetryableSourcesOrderTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/retryable_sources_order/RetryableSourcesOrderTests.java index 6d1ce3bd81..de1acf89f6 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/retryable_sources_order/RetryableSourcesOrderTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/retryable_sources_order/RetryableSourcesOrderTests.java @@ -61,13 +61,15 @@ static void setUpBeforeClass(KubernetesClient mockClient) { } private static void createSecret(String name, Map data) { - mockClient.secrets().inNamespace("spring-k8s") - .create(new SecretBuilder().withNewMetadata().withName(name).endMetadata().addToData(data).build()); + mockClient.secrets() + .inNamespace("spring-k8s") + .create(new SecretBuilder().withNewMetadata().withName(name).endMetadata().addToData(data).build()); } private static void createConfigmap(String name, Map data) { - mockClient.configMaps().inNamespace("spring-k8s") - .create(new ConfigMapBuilder().withNewMetadata().withName(name).endMetadata().addToData(data).build()); + mockClient.configMaps() + .inNamespace("spring-k8s") + .create(new ConfigMapBuilder().withNewMetadata().withName(name).endMetadata().addToData(data).build()); } /** @@ -82,13 +84,28 @@ private static void createConfigmap(String name, Map data) { */ @Test void test() { - this.webClient.get().uri("/retryable-one").exchange().expectStatus().isOk().expectBody(String.class) - .value(Matchers.equalTo("one")); - this.webClient.get().uri("/retryable-two").exchange().expectStatus().isOk().expectBody(String.class) - .value(Matchers.equalTo("two")); - - this.webClient.get().uri("/retryable-key").exchange().expectStatus().isOk().expectBody(String.class) - .value(Matchers.equalTo("from-configmap")); + this.webClient.get() + .uri("/retryable-one") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("one")); + this.webClient.get() + .uri("/retryable-two") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("two")); + + this.webClient.get() + .uri("/retryable-key") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("from-configmap")); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sanitize_secrets/BootstrapFabric8SanitizeConfigpropsEndpointTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sanitize_secrets/BootstrapFabric8SanitizeConfigpropsEndpointTests.java index b6c5aa516e..3bea977a17 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sanitize_secrets/BootstrapFabric8SanitizeConfigpropsEndpointTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sanitize_secrets/BootstrapFabric8SanitizeConfigpropsEndpointTests.java @@ -57,24 +57,42 @@ static void setUpBeforeClass() { @Test void test() { // configmap is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectBody() - .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeConfigMapName") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectBody() + .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeConfigMapName") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectBody() - .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeSecretName") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectBody() + .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeSecretName") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -104,24 +122,46 @@ static void setUpBeforeClass() { @Test void test() { // configmap is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeConfigMapName") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeConfigMapName") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeSecretName") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeSecretName") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -161,24 +201,46 @@ static void setUpBeforeClass() { @Test void test() { // configmap is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeConfigMapName") - .isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeConfigMapName") + .isEqualTo("sanitizeConfigMapValue"); // secret is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeSecretName") - .isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeSecretName") + .isEqualTo("sanitizeSecretValue"); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -218,30 +280,57 @@ static void setUpBeforeClass() { @Test void test() { // configmap is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeConfigMapName") - .isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeConfigMapName") + .isEqualTo("sanitizeConfigMapValue"); // first secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeSecretName") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeSecretName") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // second secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeSecretNameTwo") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.['sanitize-1'].beans.[*].properties.sanitizeSecretNameTwo") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sanitize_secrets/BootstrapFabric8SanitizeEnvEndpointTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sanitize_secrets/BootstrapFabric8SanitizeEnvEndpointTests.java index fe7fe397b7..357657a223 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sanitize_secrets/BootstrapFabric8SanitizeEnvEndpointTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sanitize_secrets/BootstrapFabric8SanitizeEnvEndpointTests.java @@ -57,24 +57,46 @@ static void setUpBeforeClass() { @Test void test() { // configmap is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -104,24 +126,46 @@ static void setUpBeforeClass() { @Test void test() { // configmap is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -160,24 +204,46 @@ static void setUpBeforeClass() { @Test void test() { // configmap is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") - .isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") + .isEqualTo("sanitizeConfigMapValue"); // secret is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") - .isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") + .isEqualTo("sanitizeSecretValue"); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -216,30 +282,57 @@ static void setUpBeforeClass() { @Test void test() { // configmap is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") - .isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") + .isEqualTo("sanitizeConfigMapValue"); // first secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // second secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretNameTwo'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretNameTwo'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sanitize_secrets/ConfigDataFabric8ConfigpropsEndpointTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sanitize_secrets/ConfigDataFabric8ConfigpropsEndpointTests.java index 52a002630a..6620a6a6aa 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sanitize_secrets/ConfigDataFabric8ConfigpropsEndpointTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sanitize_secrets/ConfigDataFabric8ConfigpropsEndpointTests.java @@ -57,24 +57,42 @@ static void setUpBeforeClass() { @Test void test() { // configmap is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectBody() - .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeConfigMapName") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectBody() + .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeConfigMapName") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectBody() - .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeSecretName") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectBody() + .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeSecretName") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -104,24 +122,46 @@ static void setUpBeforeClass() { @Test void test() { // configmap is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeConfigMapName") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeConfigMapName") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeSecretName") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeSecretName") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -161,24 +201,46 @@ static void setUpBeforeClass() { @Test void test() { // configmap is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeConfigMapName") - .isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeConfigMapName") + .isEqualTo("sanitizeConfigMapValue"); // secret is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeSecretName") - .isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeSecretName") + .isEqualTo("sanitizeSecretValue"); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -218,30 +280,57 @@ static void setUpBeforeClass() { @Test void test() { // configmap is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeConfigMapName") - .isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeConfigMapName") + .isEqualTo("sanitizeConfigMapValue"); // first secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeSecretName") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeSecretName") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // second secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/configprops", this.port) - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeSecretNameTwo") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/configprops", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contexts.sanitize.beans.[*].properties.sanitizeSecretNameTwo") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sanitize_secrets/ConfigDataFabric8SanitizeEnvEndpointTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sanitize_secrets/ConfigDataFabric8SanitizeEnvEndpointTests.java index 4230604bb6..12e1bcf3c0 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sanitize_secrets/ConfigDataFabric8SanitizeEnvEndpointTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sanitize_secrets/ConfigDataFabric8SanitizeEnvEndpointTests.java @@ -58,24 +58,46 @@ static void setUpBeforeClass() { @Test void test() { // configmap is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -105,24 +127,46 @@ static void setUpBeforeClass() { @Test void test() { // configmap is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -161,24 +205,46 @@ static void setUpBeforeClass() { @Test void test() { // configmap is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") - .isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") + .isEqualTo("sanitizeConfigMapValue"); // secret is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") - .isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") + .isEqualTo("sanitizeSecretValue"); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } @@ -217,30 +283,57 @@ static void setUpBeforeClass() { @Test void test() { // configmap is not sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") - .isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeConfigMapName'].value") + .isEqualTo("sanitizeConfigMapValue"); // first secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretName'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // second secret is sanitized - webClient.get().uri("http://localhost:{port}/actuator/env", this.port).accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretNameTwo'].value") - .isEqualTo(SanitizableData.SANITIZED_VALUE); + webClient.get() + .uri("http://localhost:{port}/actuator/env", this.port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources.[*].properties.['sanitize.sanitizeSecretNameTwo'].value") + .isEqualTo(SanitizableData.SANITIZED_VALUE); // secret is usable from configuration properties - webClient.get().uri("http://localhost:{port}/secret", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeSecretValue"); + webClient.get() + .uri("http://localhost:{port}/secret", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeSecretValue"); // configmap is usable from configuration properties - webClient.get().uri("http://localhost:{port}/configmap", this.port).exchange().expectStatus().isOk() - .expectBody().jsonPath("$").isEqualTo("sanitizeConfigMapValue"); + webClient.get() + .uri("http://localhost:{port}/configmap", this.port) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$") + .isEqualTo("sanitizeConfigMapValue"); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sanitize_secrets/Fabric8SecretsSanitize.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sanitize_secrets/Fabric8SecretsSanitize.java index ec8c389d95..fa5d952451 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sanitize_secrets/Fabric8SecretsSanitize.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sanitize_secrets/Fabric8SecretsSanitize.java @@ -42,20 +42,27 @@ static void setUpBeforeClass(KubernetesClient mockClient) { System.setProperty(Config.KUBERNETES_NAMESPACE_SYSTEM_PROPERTY, NAMESPACE); System.setProperty(Config.KUBERNETES_HTTP2_DISABLE, "true"); - Secret secret = new SecretBuilder().withNewMetadata().withName("sanitize-secret").endMetadata() - .addToData("sanitize.sanitizeSecretName", - Base64.getEncoder().encodeToString("sanitizeSecretValue".getBytes())) - .build(); + Secret secret = new SecretBuilder().withNewMetadata() + .withName("sanitize-secret") + .endMetadata() + .addToData("sanitize.sanitizeSecretName", + Base64.getEncoder().encodeToString("sanitizeSecretValue".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(secret).create(); - Secret secretTwo = new SecretBuilder().withNewMetadata().withName("sanitize-secret-two").endMetadata() - .addToData("sanitize.sanitizeSecretNameTwo", - Base64.getEncoder().encodeToString("sanitizeSecretValueTwo".getBytes())) - .build(); + Secret secretTwo = new SecretBuilder().withNewMetadata() + .withName("sanitize-secret-two") + .endMetadata() + .addToData("sanitize.sanitizeSecretNameTwo", + Base64.getEncoder().encodeToString("sanitizeSecretValueTwo".getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(secretTwo).create(); - ConfigMap configMap = new ConfigMapBuilder().withNewMetadata().withName("sanitize-configmap").endMetadata() - .addToData("sanitize.sanitizeConfigMapName", "sanitizeConfigMapValue").build(); + ConfigMap configMap = new ConfigMapBuilder().withNewMetadata() + .withName("sanitize-configmap") + .endMetadata() + .addToData("sanitize.sanitizeConfigMapName", "sanitizeConfigMapValue") + .build(); mockClient.configMaps().inNamespace(NAMESPACE).resource(configMap).create(); } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/secrets_property_source/Fabric8SecretsPropertySourceTest.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/secrets_property_source/Fabric8SecretsPropertySourceTest.java index 3c109e7081..bc092992a1 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/secrets_property_source/Fabric8SecretsPropertySourceTest.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/secrets_property_source/Fabric8SecretsPropertySourceTest.java @@ -54,9 +54,12 @@ static void setUpBeforeClass(KubernetesClient mockClient) { System.setProperty(Config.KUBERNETES_NAMESPACE_SYSTEM_PROPERTY, NAMESPACE); System.setProperty(Config.KUBERNETES_HTTP2_DISABLE, "true"); - Secret secret = new SecretBuilder().withNewMetadata().withName("test-secret") - .withLabels(singletonMap("foo", "bar")).endMetadata() - .addToData("secretName", Base64.getEncoder().encodeToString(SECRET_VALUE.getBytes())).build(); + Secret secret = new SecretBuilder().withNewMetadata() + .withName("test-secret") + .withLabels(singletonMap("foo", "bar")) + .endMetadata() + .addToData("secretName", Base64.getEncoder().encodeToString(SECRET_VALUE.getBytes())) + .build(); mockClient.secrets().inNamespace(NAMESPACE).resource(secret).create(); } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/secrets_with_labels/SecretsWithLabelsTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/secrets_with_labels/SecretsWithLabelsTests.java index 2661eae496..6bfba0aab3 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/secrets_with_labels/SecretsWithLabelsTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/secrets_with_labels/SecretsWithLabelsTests.java @@ -61,9 +61,10 @@ static void setUpBeforeClass(KubernetesClient mockClient) { } private static void createSecret(String name, Map data) { - mockClient.secrets().inNamespace("spring-k8s") - .resource(new SecretBuilder().withNewMetadata().withName(name).endMetadata().addToData(data).build()) - .create(); + mockClient.secrets() + .inNamespace("spring-k8s") + .resource(new SecretBuilder().withNewMetadata().withName(name).endMetadata().addToData(data).build()) + .create(); } /** @@ -77,8 +78,13 @@ private static void createSecret(String name, Map data) { */ @Test void testOne() { - this.webClient.get().uri("secrets/labels/one").exchange().expectStatus().isOk().expectBody(String.class) - .value(Matchers.equalTo("value")); + this.webClient.get() + .uri("secrets/labels/one") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("value")); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/single_source_multiple_files/SingleSourceMultipleFilesTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/single_source_multiple_files/SingleSourceMultipleFilesTests.java index 113992289c..6136b5bef8 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/single_source_multiple_files/SingleSourceMultipleFilesTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/single_source_multiple_files/SingleSourceMultipleFilesTests.java @@ -62,9 +62,14 @@ static void setUpBeforeClass(KubernetesClient mockClient) { } static void createConfigmap(Map data) { - mockClient.configMaps().inNamespace("spring-k8s").resource( - new ConfigMapBuilder().withNewMetadata().withName("my-configmap").endMetadata().addToData(data).build()) - .create(); + mockClient.configMaps() + .inNamespace("spring-k8s") + .resource(new ConfigMapBuilder().withNewMetadata() + .withName("my-configmap") + .endMetadata() + .addToData(data) + .build()) + .create(); } /** @@ -75,8 +80,13 @@ static void createConfigmap(Map data) { */ @Test void color() { - this.webClient.get().uri("/single_source-multiple-files/color").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("raw:green###ripe:yellow")); + this.webClient.get() + .uri("/single_source-multiple-files/color") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("raw:green###ripe:yellow")); } /** @@ -86,8 +96,13 @@ void color() { */ @Test void name() { - this.webClient.get().uri("/single_source-multiple-files/name").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("banana")); + this.webClient.get() + .uri("/single_source-multiple-files/name") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("banana")); } /** @@ -98,8 +113,13 @@ void name() { */ @Test void shape() { - this.webClient.get().uri("/single_source-multiple-files/shape").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.nullValue()); + this.webClient.get() + .uri("/single_source-multiple-files/shape") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.nullValue()); } /** @@ -109,8 +129,13 @@ void shape() { */ @Test void type() { - this.webClient.get().uri("/single_source-multiple-files/type").exchange().expectStatus().isOk() - .expectBody(String.class).value(Matchers.equalTo("yummy")); + this.webClient.get() + .uri("/single_source-multiple-files/type") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("yummy")); } } diff --git a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sources_order/SourcesOrderTests.java b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sources_order/SourcesOrderTests.java index 2da2785376..b2d0fa135b 100644 --- a/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sources_order/SourcesOrderTests.java +++ b/spring-cloud-kubernetes-fabric8-config/src/test/java/org/springframework/cloud/kubernetes/fabric8/config/sources_order/SourcesOrderTests.java @@ -65,13 +65,15 @@ static void setUpBeforeClass(KubernetesClient mockClient) { } private static void createSecret(String name, Map data) { - mockClient.secrets().inNamespace("spring-k8s") - .create(new SecretBuilder().withNewMetadata().withName(name).endMetadata().addToData(data).build()); + mockClient.secrets() + .inNamespace("spring-k8s") + .create(new SecretBuilder().withNewMetadata().withName(name).endMetadata().addToData(data).build()); } private static void createConfigmap(String name, Map data) { - mockClient.configMaps().inNamespace("spring-k8s") - .create(new ConfigMapBuilder().withNewMetadata().withName(name).endMetadata().addToData(data).build()); + mockClient.configMaps() + .inNamespace("spring-k8s") + .create(new ConfigMapBuilder().withNewMetadata().withName(name).endMetadata().addToData(data).build()); } /** @@ -86,13 +88,28 @@ private static void createConfigmap(String name, Map data) { */ @Test void test() { - this.webClient.get().uri("/one").exchange().expectStatus().isOk().expectBody(String.class) - .value(Matchers.equalTo("one")); - this.webClient.get().uri("/two").exchange().expectStatus().isOk().expectBody(String.class) - .value(Matchers.equalTo("two")); - - this.webClient.get().uri("/key").exchange().expectStatus().isOk().expectBody(String.class) - .value(Matchers.equalTo("from-configmap")); + this.webClient.get() + .uri("/one") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("one")); + this.webClient.get() + .uri("/two") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("two")); + + this.webClient.get() + .uri("/key") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(Matchers.equalTo("from-configmap")); } } diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8CatalogWatchContext.java b/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8CatalogWatchContext.java index 9a9fadf8f1..6a14e61253 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8CatalogWatchContext.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8CatalogWatchContext.java @@ -40,8 +40,10 @@ record Fabric8CatalogWatchContext(KubernetesClient kubernetesClient, KubernetesD KubernetesNamespaceProvider namespaceProvider) { static List state(Stream references) { - return references.filter(Objects::nonNull).map(x -> new EndpointNameAndNamespace(x.getName(), x.getNamespace())) - .sorted(comparing(EndpointNameAndNamespace::endpointName, nullsLast(String::compareTo))).toList(); + return references.filter(Objects::nonNull) + .map(x -> new EndpointNameAndNamespace(x.getName(), x.getNamespace())) + .sorted(comparing(EndpointNameAndNamespace::endpointName, nullsLast(String::compareTo))) + .toList(); } } diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8ConfigServerBootstrapper.java b/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8ConfigServerBootstrapper.java index 79b99aad2a..3b65c87750 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8ConfigServerBootstrapper.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8ConfigServerBootstrapper.java @@ -69,14 +69,14 @@ public void initialize(BootstrapRegistry registry) { PropertyResolver propertyResolver = getPropertyResolver(context); Fabric8AutoConfiguration fabric8AutoConfiguration = new Fabric8AutoConfiguration(); Config config = fabric8AutoConfiguration - .kubernetesClientConfig(context.get(KubernetesClientProperties.class)); + .kubernetesClientConfig(context.get(KubernetesClientProperties.class)); KubernetesClient kubernetesClient = fabric8AutoConfiguration.kubernetesClient(config); KubernetesDiscoveryProperties discoveryProperties = context.get(KubernetesDiscoveryProperties.class); KubernetesDiscoveryClient discoveryClient = new KubernetesDiscoveryClient(kubernetesClient, discoveryProperties, KubernetesClientServicesFunctionProvider.servicesFunction(discoveryProperties, new KubernetesNamespaceProvider(propertyResolver - .get(KubernetesNamespaceProvider.NAMESPACE_PROPERTY, String.class, null))), + .get(KubernetesNamespaceProvider.NAMESPACE_PROPERTY, String.class, null))), null, new ServicePortSecureResolver(discoveryProperties)); return discoveryClient::getInstances; } diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8DiscoveryServicesAdapter.java b/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8DiscoveryServicesAdapter.java index cdb079c805..25bd6a2ef7 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8DiscoveryServicesAdapter.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8DiscoveryServicesAdapter.java @@ -46,7 +46,8 @@ final class Fabric8DiscoveryServicesAdapter implements Function apply(KubernetesClient client) { LOG.debug(() -> "searching in namespaces : " + properties.namespaces() + " with filter : " + properties.filter()); List services = new ArrayList<>(); - properties.namespaces().forEach(namespace -> services.addAll(client.services().inNamespace(namespace) - .withLabels(properties.serviceLabels()).list().getItems().stream().filter(filter).toList())); + properties.namespaces() + .forEach(namespace -> services.addAll(client.services() + .inNamespace(namespace) + .withLabels(properties.serviceLabels()) + .list() + .getItems() + .stream() + .filter(filter) + .toList())); return services; } return function.apply(client).list().getItems().stream().filter(filter).toList(); diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8EndpointSliceV1CatalogWatch.java b/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8EndpointSliceV1CatalogWatch.java index 2e503ffead..22f4d88f05 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8EndpointSliceV1CatalogWatch.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8EndpointSliceV1CatalogWatch.java @@ -49,14 +49,20 @@ public List apply(Fabric8CatalogWatchContext context) if (context.properties().allNamespaces()) { LOG.debug(() -> "discovering endpoint slices in all namespaces"); - endpointSlices = client.discovery().v1().endpointSlices().inAnyNamespace() - .withLabels(context.properties().serviceLabels()).list().getItems(); + endpointSlices = client.discovery() + .v1() + .endpointSlices() + .inAnyNamespace() + .withLabels(context.properties().serviceLabels()) + .list() + .getItems(); } else if (!context.properties().namespaces().isEmpty()) { LOG.debug(() -> "discovering endpoint slices in " + context.properties().namespaces()); List inner = new ArrayList<>(context.properties().namespaces().size()); - context.properties().namespaces() - .forEach(namespace -> inner.addAll(endpointSlices(context, namespace, client))); + context.properties() + .namespaces() + .forEach(namespace -> inner.addAll(endpointSlices(context, namespace, client))); endpointSlices = inner; } else { @@ -66,8 +72,10 @@ else if (!context.properties().namespaces().isEmpty()) { endpointSlices = endpointSlices(context, namespace, client); } - Stream references = endpointSlices.stream().map(EndpointSlice::getEndpoints) - .flatMap(List::stream).map(Endpoint::getTargetRef); + Stream references = endpointSlices.stream() + .map(EndpointSlice::getEndpoints) + .flatMap(List::stream) + .map(Endpoint::getTargetRef); return Fabric8CatalogWatchContext.state(references); @@ -75,8 +83,13 @@ else if (!context.properties().namespaces().isEmpty()) { private List endpointSlices(Fabric8CatalogWatchContext context, String namespace, KubernetesClient client) { - return client.discovery().v1().endpointSlices().inNamespace(namespace) - .withLabels(context.properties().serviceLabels()).list().getItems(); + return client.discovery() + .v1() + .endpointSlices() + .inNamespace(namespace) + .withLabels(context.properties().serviceLabels()) + .list() + .getItems(); } } diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8EndpointsCatalogWatch.java b/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8EndpointsCatalogWatch.java index ad17865105..2e7791c2cf 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8EndpointsCatalogWatch.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8EndpointsCatalogWatch.java @@ -54,9 +54,14 @@ public List apply(Fabric8CatalogWatchContext context) * EndpointSubset::getAddresses and EndpointSubset::getPorts (each is a List) * */ - Stream references = endpoints.stream().map(Endpoints::getSubsets).filter(Objects::nonNull) - .flatMap(List::stream).map(EndpointSubset::getAddresses).filter(Objects::nonNull).flatMap(List::stream) - .map(EndpointAddress::getTargetRef); + Stream references = endpoints.stream() + .map(Endpoints::getSubsets) + .filter(Objects::nonNull) + .flatMap(List::stream) + .map(EndpointSubset::getAddresses) + .filter(Objects::nonNull) + .flatMap(List::stream) + .map(EndpointAddress::getTargetRef); return Fabric8CatalogWatchContext.state(references); } diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8InstanceIdHostPodNameSupplier.java b/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8InstanceIdHostPodNameSupplier.java index 2267e0ed9d..f5bc99eaa4 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8InstanceIdHostPodNameSupplier.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8InstanceIdHostPodNameSupplier.java @@ -62,19 +62,24 @@ static Fabric8InstanceIdHostPodNameSupplier externalName(Service service) { // instanceId is usually the pod-uid as seen in the .metadata.uid private String instanceId() { - return Optional.ofNullable(endpointAddress).map(EndpointAddress::getTargetRef).map(ObjectReference::getUid) - .orElseGet(() -> service.getMetadata().getUid()); + return Optional.ofNullable(endpointAddress) + .map(EndpointAddress::getTargetRef) + .map(ObjectReference::getUid) + .orElseGet(() -> service.getMetadata().getUid()); } private String host() { - return Optional.ofNullable(endpointAddress).map(EndpointAddress::getIp) - .orElseGet(() -> service.getSpec().getExternalName()); + return Optional.ofNullable(endpointAddress) + .map(EndpointAddress::getIp) + .orElseGet(() -> service.getSpec().getExternalName()); } private String podName() { - return Optional.ofNullable(endpointAddress).map(EndpointAddress::getTargetRef) - .filter(objectReference -> "Pod".equals(objectReference.getKind())).map(ObjectReference::getName) - .orElse(null); + return Optional.ofNullable(endpointAddress) + .map(EndpointAddress::getTargetRef) + .filter(objectReference -> "Pod".equals(objectReference.getKind())) + .map(ObjectReference::getName) + .orElse(null); } } diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8KubernetesDiscoveryClientUtils.java b/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8KubernetesDiscoveryClientUtils.java index e21de1eee5..eb3a264cd9 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8KubernetesDiscoveryClientUtils.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8KubernetesDiscoveryClientUtils.java @@ -71,8 +71,9 @@ static List endpoints(KubernetesDiscoveryProperties properties, Kuber if (!properties.namespaces().isEmpty()) { LOG.debug(() -> "discovering endpoints in namespaces : " + properties.namespaces()); List inner = new ArrayList<>(properties.namespaces().size()); - properties.namespaces().forEach(namespace -> inner.addAll(filteredEndpoints( - client.endpoints().inNamespace(namespace).withNewFilter(), properties, serviceName))); + properties.namespaces() + .forEach(namespace -> inner.addAll(filteredEndpoints( + client.endpoints().inNamespace(namespace).withNewFilter(), properties, serviceName))); endpoints = inner; } else if (properties.allNamespaces()) { @@ -103,19 +104,27 @@ static List withFilter(List endpoints, KubernetesDiscovery // group by namespace in order to make a single API call per namespace when // retrieving services Map> endpointsByNamespace = endpoints.stream() - .collect(Collectors.groupingBy(x -> x.getMetadata().getNamespace())); + .collect(Collectors.groupingBy(x -> x.getMetadata().getNamespace())); for (Map.Entry> entry : endpointsByNamespace.entrySet()) { // get all services in the namespace that match the filter - Set filteredServiceNames = client.services().inNamespace(entry.getKey()).list().getItems().stream() - .filter(filter).map(service -> service.getMetadata().getName()).collect(Collectors.toSet()); + Set filteredServiceNames = client.services() + .inNamespace(entry.getKey()) + .list() + .getItems() + .stream() + .filter(filter) + .map(service -> service.getMetadata().getName()) + .collect(Collectors.toSet()); // in the previous step we might have taken "too many" services, so in the // next one take only those that have a matching endpoints, by name. // This way we only get the endpoints that have a matching service with an // applied filter, it's like we filtered endpoints by that filter. - result.addAll(entry.getValue().stream() - .filter(endpoint -> filteredServiceNames.contains(endpoint.getMetadata().getName())).toList()); + result.addAll(entry.getValue() + .stream() + .filter(endpoint -> filteredServiceNames.contains(endpoint.getMetadata().getName())) + .toList()); } @@ -131,7 +140,7 @@ static List filteredEndpoints( KubernetesDiscoveryProperties properties, @Nullable String serviceName) { FilterNested>> partial = filterNested - .withLabels(properties.serviceLabels()); + .withLabels(properties.serviceLabels()); if (serviceName != null) { partial = partial.withField("metadata.name", serviceName); @@ -142,8 +151,9 @@ static List filteredEndpoints( } static List addresses(EndpointSubset endpointSubset, KubernetesDiscoveryProperties properties) { - List addresses = Optional.ofNullable(endpointSubset.getAddresses()).map(ArrayList::new) - .orElse(new ArrayList<>()); + List addresses = Optional.ofNullable(endpointSubset.getAddresses()) + .map(ArrayList::new) + .orElse(new ArrayList<>()); if (properties.includeNotReadyAddresses()) { List notReadyAddresses = endpointSubset.getNotReadyAddresses(); @@ -170,9 +180,10 @@ static List services(KubernetesDiscoveryProperties properties, Kubernet else if (!properties.namespaces().isEmpty()) { LOG.debug(() -> "discovering services in namespaces : " + properties.namespaces()); List inner = new ArrayList<>(properties.namespaces().size()); - properties.namespaces().forEach( - namespace -> inner.addAll(filteredServices(client.services().inNamespace(namespace).withNewFilter(), - properties, predicate, fieldFilters))); + properties.namespaces() + .forEach(namespace -> inner + .addAll(filteredServices(client.services().inNamespace(namespace).withNewFilter(), properties, + predicate, fieldFilters))); services = inner; } else { @@ -189,10 +200,11 @@ else if (!properties.namespaces().isEmpty()) { * a service is allowed to have a single port defined without a name. */ static Map endpointSubsetsPortData(List endpointSubsets) { - return endpointSubsets.stream().flatMap(endpointSubset -> endpointSubset.getPorts().stream()) - .collect(Collectors.toMap( - endpointPort -> hasText(endpointPort.getName()) ? endpointPort.getName() : UNSET_PORT_NAME, - EndpointPort::getPort)); + return endpointSubsets.stream() + .flatMap(endpointSubset -> endpointSubset.getPorts().stream()) + .collect(Collectors.toMap( + endpointPort -> hasText(endpointPort.getName()) ? endpointPort.getName() : UNSET_PORT_NAME, + EndpointPort::getPort)); } /** @@ -204,7 +216,7 @@ private static List filteredServices( @Nullable Map fieldFilters) { FilterNested>> partial = filterNested - .withLabels(properties.serviceLabels()); + .withLabels(properties.serviceLabels()); if (fieldFilters != null) { partial = partial.withFields(fieldFilters); diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8PodLabelsAndAnnotationsSupplier.java b/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8PodLabelsAndAnnotationsSupplier.java index 633f0463f9..b0cca89ea5 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8PodLabelsAndAnnotationsSupplier.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8PodLabelsAndAnnotationsSupplier.java @@ -58,7 +58,8 @@ static Fabric8PodLabelsAndAnnotationsSupplier externalName() { @Override public PodLabelsAndAnnotations apply(String podName) { ObjectMeta metadata = Optional.ofNullable(client.pods().inNamespace(namespace).withName(podName).get()) - .map(Pod::getMetadata).orElse(new ObjectMeta()); + .map(Pod::getMetadata) + .orElse(new ObjectMeta()); return new PodLabelsAndAnnotations(metadata.getLabels(), metadata.getAnnotations()); } diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesCatalogWatch.java b/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesCatalogWatch.java index 805623c22e..d6a84fb7b7 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesCatalogWatch.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesCatalogWatch.java @@ -98,11 +98,18 @@ Function> stateGenera // can't use try with resources here as it will close the client KubernetesClient client = context.kubernetesClient(); // this emulates : 'kubectl api-resources | grep -i EndpointSlice' - boolean found = client.getApiGroups().getGroups().stream().flatMap(x -> x.getVersions().stream()) - .map(GroupVersionForDiscovery::getGroupVersion).filter(DISCOVERY_GROUP_VERSION::equals).findFirst() - .map(client::getApiResources).map(APIResourceList::getResources) - .map(x -> x.stream().map(APIResource::getKind)) - .flatMap(x -> x.filter(y -> y.equals(ENDPOINT_SLICE)).findFirst()).isPresent(); + boolean found = client.getApiGroups() + .getGroups() + .stream() + .flatMap(x -> x.getVersions().stream()) + .map(GroupVersionForDiscovery::getGroupVersion) + .filter(DISCOVERY_GROUP_VERSION::equals) + .findFirst() + .map(client::getApiResources) + .map(APIResourceList::getResources) + .map(x -> x.stream().map(APIResource::getKind)) + .flatMap(x -> x.filter(y -> y.equals(ENDPOINT_SLICE)).findFirst()) + .isPresent(); if (!found) { throw new IllegalArgumentException("EndpointSlices are not supported on the cluster"); diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClient.java b/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClient.java index 5d8fcc1b90..79ca695870 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClient.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClient.java @@ -194,7 +194,10 @@ public List getServices() { @Deprecated(forRemoval = true) public List getServices(Predicate filter) { return new Fabric8DiscoveryServicesAdapter(kubernetesClientServicesFunction, properties, filter).apply(client) - .stream().map(s -> s.getMetadata().getName()).distinct().toList(); + .stream() + .map(s -> s.getMetadata().getName()) + .distinct() + .toList(); } @Override diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/reactive/KubernetesReactiveDiscoveryClient.java b/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/reactive/KubernetesReactiveDiscoveryClient.java index 351d6244a8..e86791b75e 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/reactive/KubernetesReactiveDiscoveryClient.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/reactive/KubernetesReactiveDiscoveryClient.java @@ -52,13 +52,13 @@ public String description() { public Flux getInstances(String serviceId) { Assert.notNull(serviceId, "[Assertion failed] - the object argument must not be null"); return Flux.defer(() -> Flux.fromIterable(kubernetesDiscoveryClient.getInstances(serviceId))) - .subscribeOn(Schedulers.boundedElastic()); + .subscribeOn(Schedulers.boundedElastic()); } @Override public Flux getServices() { return Flux.defer(() -> Flux.fromIterable(kubernetesDiscoveryClient.getServices())) - .subscribeOn(Schedulers.boundedElastic()); + .subscribeOn(Schedulers.boundedElastic()); } } diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8CatalogWatchContextTests.java b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8CatalogWatchContextTests.java index 3324baaba1..408af3c3a8 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8CatalogWatchContextTests.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8CatalogWatchContextTests.java @@ -35,7 +35,7 @@ class Fabric8CatalogWatchContextTests { void stateWithASingleElementNameNotNull() { Stream referenceStream = Stream - .of(new ObjectReferenceBuilder().withName("a").withNamespace("default").build()); + .of(new ObjectReferenceBuilder().withName("a").withNamespace("default").build()); List result = Fabric8CatalogWatchContext.state(referenceStream); Assertions.assertEquals(result.size(), 1); @@ -48,7 +48,7 @@ void stateWithASingleElementNameNotNull() { void stateWithASingleElementNameNull() { Stream referenceStream = Stream - .of(new ObjectReferenceBuilder().withName(null).withNamespace("default").build()); + .of(new ObjectReferenceBuilder().withName(null).withNamespace("default").build()); List result = Fabric8CatalogWatchContext.state(referenceStream); Assertions.assertEquals(result.size(), 1); diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8ConfigServerBootstrapperTests.java b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8ConfigServerBootstrapperTests.java index 7d03d9f6ce..2363f76056 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8ConfigServerBootstrapperTests.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8ConfigServerBootstrapperTests.java @@ -79,16 +79,32 @@ public void before() throws JsonProcessingException { System.setProperty(Config.KUBERNETES_AUTH_TRYSERVICEACCOUNT_SYSTEM_PROPERTY, "false"); System.setProperty(Config.KUBERNETES_HTTP2_DISABLE, "true"); - Endpoints endPoint = new EndpointsBuilder().withNewMetadata().withName("spring-cloud-kubernetes-configserver") - .withNamespace("test").withLabels(new HashMap<>()).endMetadata().addNewSubset().addNewAddress() - .withHostname("localhost").withIp("localhost").withNewTargetRef().withUid("10").endTargetRef() - .endAddress().addNewPort("http", "http_tcp", wireMockServer.port(), "TCP").endSubset().build(); + Endpoints endPoint = new EndpointsBuilder().withNewMetadata() + .withName("spring-cloud-kubernetes-configserver") + .withNamespace("test") + .withLabels(new HashMap<>()) + .endMetadata() + .addNewSubset() + .addNewAddress() + .withHostname("localhost") + .withIp("localhost") + .withNewTargetRef() + .withUid("10") + .endTargetRef() + .endAddress() + .addNewPort("http", "http_tcp", wireMockServer.port(), "TCP") + .endSubset() + .build(); mockClient.endpoints().inNamespace("test").create(endPoint); - Service service = new ServiceBuilder().withNewMetadata().withName("spring-cloud-kubernetes-configserver") - .withNamespace("test").withLabels(new HashMap<>()).endMetadata() - .withSpec(new ServiceSpecBuilder().withType("NodePort").build()).build(); + Service service = new ServiceBuilder().withNewMetadata() + .withName("spring-cloud-kubernetes-configserver") + .withNamespace("test") + .withLabels(new HashMap<>()) + .endMetadata() + .withSpec(new ServiceSpecBuilder().withType("NodePort").build()) + .build(); mockClient.services().inNamespace("test").create(service); @@ -98,9 +114,9 @@ public void before() throws JsonProcessingException { org.springframework.cloud.config.environment.PropertySource p = new PropertySource("p1", properties); environment.add(p); ObjectMapper objectMapper = new ObjectMapper(); - stubFor(get("/application/default") - .willReturn(aResponse().withStatus(200).withBody(objectMapper.writeValueAsString(environment)) - .withHeader("content-type", "application/json"))); + stubFor(get("/application/default").willReturn(aResponse().withStatus(200) + .withBody(objectMapper.writeValueAsString(environment)) + .withHeader("content-type", "application/json"))); } @AfterEach @@ -119,7 +135,7 @@ void testBootstrapper() { SpringApplicationBuilder setup(String... env) { SpringApplicationBuilder builder = new SpringApplicationBuilder(TestConfig.class) - .properties(addDefaultEnv(env)); + .properties(addDefaultEnv(env)); builder.addBootstrapRegistryInitializer(new Fabric8ConfigServerBootstrapper()); return builder; } diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8DiscoveryServicesAdapterTests.java b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8DiscoveryServicesAdapterTests.java index df45b1edc6..9ed841106d 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8DiscoveryServicesAdapterTests.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8DiscoveryServicesAdapterTests.java @@ -243,7 +243,7 @@ void testSpecificNamespaceWithoutLabelsWithoutFilter() { utils.when(() -> Fabric8Utils.getApplicationNamespace(Mockito.any(KubernetesClient.class), Mockito.nullable(String.class), Mockito.anyString(), Mockito.any(KubernetesNamespaceProvider.class))) - .thenReturn("namespaceA"); + .thenReturn("namespaceA"); service("namespaceA", "serviceA", Map.of("color", "red")); service("namespaceB", "serviceB", Map.of("color", "blue")); @@ -285,7 +285,7 @@ void testSpecificNamespaceWithLabelsWithoutFilter() { utils.when(() -> Fabric8Utils.getApplicationNamespace(Mockito.any(KubernetesClient.class), Mockito.nullable(String.class), Mockito.anyString(), Mockito.any(KubernetesNamespaceProvider.class))) - .thenReturn("namespaceA"); + .thenReturn("namespaceA"); service("namespaceA", "serviceA", Map.of("color", "red")); service("namespaceA", "serviceB", Map.of("color", "purple")); @@ -332,7 +332,7 @@ void testSpecificNamespaceWithoutLabelsWithFilter() { utils.when(() -> Fabric8Utils.getApplicationNamespace(Mockito.any(KubernetesClient.class), Mockito.nullable(String.class), Mockito.anyString(), Mockito.any(KubernetesNamespaceProvider.class))) - .thenReturn("namespaceA"); + .thenReturn("namespaceA"); service("namespaceA", "serviceA", Map.of("color", "red", "number", "1")); service("namespaceA", "serviceB", Map.of("color", "purple", "cycle", "create")); @@ -471,9 +471,10 @@ void testSomeNamespacesWithLabelsWithFilter() { } private void service(String namespace, String name, Map labels) { - client.services().inNamespace(namespace) - .resource(new ServiceBuilder().withNewMetadata().withName(name).withLabels(labels).and().build()) - .create(); + client.services() + .inNamespace(namespace) + .resource(new ServiceBuilder().withNewMetadata().withName(name).withLabels(labels).and().build()) + .create(); } } diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8EndpointsAndEndpointSlicesTests.java b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8EndpointsAndEndpointSlicesTests.java index 23dd73087d..4f4a55144f 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8EndpointsAndEndpointSlicesTests.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8EndpointsAndEndpointSlicesTests.java @@ -61,7 +61,7 @@ abstract class Fabric8EndpointsAndEndpointSlicesTests { static final KubernetesNamespaceProvider NAMESPACE_PROVIDER = Mockito.mock(KubernetesNamespaceProvider.class); static final ArgumentCaptor HEARTBEAT_EVENT_ARGUMENT_CAPTOR = ArgumentCaptor - .forClass(HeartbeatEvent.class); + .forClass(HeartbeatEvent.class); static final ApplicationEventPublisher APPLICATION_EVENT_PUBLISHER = Mockito.mock(ApplicationEventPublisher.class); @@ -297,31 +297,39 @@ KubernetesCatalogWatch createWatcherInSpecificNamespacesWithLabels(Set n void endpoints(String namespace, Map labels, String podName) { EndpointAddress endpointAddress = new EndpointAddressBuilder() - .withTargetRef(new ObjectReferenceBuilder().withName(podName).withNamespace(namespace).build()).build(); + .withTargetRef(new ObjectReferenceBuilder().withName(podName).withNamespace(namespace).build()) + .build(); EndpointSubset endpointSubset = new EndpointSubsetBuilder().withAddresses(List.of(endpointAddress)).build(); Endpoints endpoints = new EndpointsBuilder() - .withMetadata(new ObjectMetaBuilder().withLabels(labels).withName("endpoints-" + podName).build()) - .withSubsets(List.of(endpointSubset)).build(); + .withMetadata(new ObjectMetaBuilder().withLabels(labels).withName("endpoints-" + podName).build()) + .withSubsets(List.of(endpointSubset)) + .build(); mockClient().endpoints().inNamespace(namespace).resource(endpoints).create(); } void service(String namespace, Map labels, String podName) { Service service = new ServiceBuilder() - .withMetadata(new ObjectMetaBuilder().withLabels(labels).withName("endpoints-" + podName).build()) - .build(); + .withMetadata(new ObjectMetaBuilder().withLabels(labels).withName("endpoints-" + podName).build()) + .build(); mockClient().services().inNamespace(namespace).resource(service).create(); } static void endpointSlice(String namespace, Map labels, String podName) { Endpoint endpoint = new EndpointBuilder() - .withTargetRef(new ObjectReferenceBuilder().withName(podName).withNamespace(namespace).build()).build(); + .withTargetRef(new ObjectReferenceBuilder().withName(podName).withNamespace(namespace).build()) + .build(); - EndpointSlice slice = new EndpointSliceBuilder().withMetadata(new ObjectMetaBuilder().withNamespace(namespace) - .withName("slice-" + podName).withLabels(labels).build()).withEndpoints(endpoint).build(); + EndpointSlice slice = new EndpointSliceBuilder() + .withMetadata(new ObjectMetaBuilder().withNamespace(namespace) + .withName("slice-" + podName) + .withLabels(labels) + .build()) + .withEndpoints(endpoint) + .build(); mockClient().discovery().v1().endpointSlices().inNamespace(namespace).resource(slice).create(); @@ -331,7 +339,7 @@ static void invokeAndAssert(KubernetesCatalogWatch watch, List labels = Map.of("l", "v"); - Endpoints endPoint = new EndpointsBuilder().withNewMetadata().withName("endpoint").withNamespace("test") - .withLabels(labels).endMetadata().addNewSubset().addNewAddress().withIp("ip1").withNewTargetRef() - .withUid("10").endTargetRef().endAddress().addNewPort("http", "http_tcp", 80, "TCP").endSubset() - .build(); + Endpoints endPoint = new EndpointsBuilder().withNewMetadata() + .withName("endpoint") + .withNamespace("test") + .withLabels(labels) + .endMetadata() + .addNewSubset() + .addNewAddress() + .withIp("ip1") + .withNewTargetRef() + .withUid("10") + .endTargetRef() + .endAddress() + .addNewPort("http", "http_tcp", 80, "TCP") + .endSubset() + .build(); mockClient.endpoints().inNamespace("test").resource(endPoint).create(); Service service = new ServiceBuilder().withSpec(new ServiceSpecBuilder().withType("ExternalName").build()) - .withNewMetadata().withName("endpoint").withNamespace("test").withLabels(labels).endMetadata().build(); + .withNewMetadata() + .withName("endpoint") + .withNamespace("test") + .withLabels(labels) + .endMetadata() + .build(); mockClient.services().inNamespace("test").resource(service).create(); @@ -88,24 +104,44 @@ void getInstancesShouldBeAbleToHandleEndpointsSingleAddress() { List instances = discoveryClient.getInstances("endpoint"); - assertThat(instances).hasSize(1).filteredOn(s -> s.getHost().equals("ip1") && !s.isSecure()).hasSize(1) - .filteredOn(s -> s.getInstanceId().equals("10")).hasSize(1); + assertThat(instances).hasSize(1) + .filteredOn(s -> s.getHost().equals("ip1") && !s.isSecure()) + .hasSize(1) + .filteredOn(s -> s.getInstanceId().equals("10")) + .hasSize(1); } @Test void getInstancesShouldBeAbleToHandleEndpointsSingleAddressAndMultiplePorts() { Map labels = Map.of("l2", "v2"); - Endpoints endPoint = new EndpointsBuilder().withNewMetadata().withName("endpoint").withNamespace("test") - .withLabels(labels).endMetadata().addNewSubset().addNewAddress().withIp("ip1").withNewTargetRef() - .withUid("20").endTargetRef().endAddress().addNewPort("mgmt", "mgmt_tcp", 900, "TCP") - .addNewPort("http", "http_tcp", 80, "TCP").endSubset().build(); + Endpoints endPoint = new EndpointsBuilder().withNewMetadata() + .withName("endpoint") + .withNamespace("test") + .withLabels(labels) + .endMetadata() + .addNewSubset() + .addNewAddress() + .withIp("ip1") + .withNewTargetRef() + .withUid("20") + .endTargetRef() + .endAddress() + .addNewPort("mgmt", "mgmt_tcp", 900, "TCP") + .addNewPort("http", "http_tcp", 80, "TCP") + .endSubset() + .build(); mockClient.endpoints().inNamespace("test").resource(endPoint).create(); Service service = new ServiceBuilder().withSpec(new ServiceSpecBuilder().withType("ExternalName").build()) - .withNewMetadata().withName("endpoint").withNamespace("test").withLabels(labels).withAnnotations(labels) - .endMetadata().build(); + .withNewMetadata() + .withName("endpoint") + .withNamespace("test") + .withLabels(labels) + .withAnnotations(labels) + .endMetadata() + .build(); mockClient.services().inNamespace("test").resource(service).create(); @@ -117,21 +153,39 @@ void getInstancesShouldBeAbleToHandleEndpointsSingleAddressAndMultiplePorts() { List instances = discoveryClient.getInstances("endpoint"); - assertThat(instances).hasSize(1).filteredOn(s -> s.getHost().equals("ip1") && !s.isSecure()).hasSize(1) - .filteredOn(s -> s.getInstanceId().equals("20")).hasSize(1).filteredOn(s -> 80 == s.getPort()) - .hasSize(1); + assertThat(instances).hasSize(1) + .filteredOn(s -> s.getHost().equals("ip1") && !s.isSecure()) + .hasSize(1) + .filteredOn(s -> s.getInstanceId().equals("20")) + .hasSize(1) + .filteredOn(s -> 80 == s.getPort()) + .hasSize(1); } @Test void getEndPointsListTest() { Map labels = Map.of("l", "v"); - Endpoints endPoint = new EndpointsBuilder().withNewMetadata().withName("endpoint").withNamespace("test") - .withLabels(labels).endMetadata().addNewSubset().addNewAddress().withIp("ip1").withNewTargetRef() - .withUid("30").endTargetRef().endAddress().addNewPort("http", "http_tcp", 80, "TCP").endSubset() - .build(); - Service service = new ServiceBuilder().withNewMetadata().withName("endpoint").withNamespace("test") - .endMetadata().build(); + Endpoints endPoint = new EndpointsBuilder().withNewMetadata() + .withName("endpoint") + .withNamespace("test") + .withLabels(labels) + .endMetadata() + .addNewSubset() + .addNewAddress() + .withIp("ip1") + .withNewTargetRef() + .withUid("30") + .endTargetRef() + .endAddress() + .addNewPort("http", "http_tcp", 80, "TCP") + .endSubset() + .build(); + Service service = new ServiceBuilder().withNewMetadata() + .withName("endpoint") + .withNamespace("test") + .endMetadata() + .build(); mockClient.endpoints().inNamespace("test").resource(endPoint).create(); mockClient.services().inNamespace("test").resource(service).create(); @@ -151,15 +205,27 @@ void getEndPointsListTestAllNamespaces() { String namespace1 = "ns1"; String namespace2 = "ns2"; - Endpoints endPoint1 = new EndpointsBuilder().withNewMetadata().withName("endpoint").withNamespace(namespace1) - .endMetadata().build(); - Endpoints endPoint2 = new EndpointsBuilder().withNewMetadata().withName("endpoint").withNamespace(namespace2) - .endMetadata().build(); - - Service service1 = new ServiceBuilder().withNewMetadata().withName("endpoint").withNamespace(namespace1) - .endMetadata().build(); - Service service2 = new ServiceBuilder().withNewMetadata().withName("endpoint").withNamespace(namespace2) - .endMetadata().build(); + Endpoints endPoint1 = new EndpointsBuilder().withNewMetadata() + .withName("endpoint") + .withNamespace(namespace1) + .endMetadata() + .build(); + Endpoints endPoint2 = new EndpointsBuilder().withNewMetadata() + .withName("endpoint") + .withNamespace(namespace2) + .endMetadata() + .build(); + + Service service1 = new ServiceBuilder().withNewMetadata() + .withName("endpoint") + .withNamespace(namespace1) + .endMetadata() + .build(); + Service service2 = new ServiceBuilder().withNewMetadata() + .withName("endpoint") + .withNamespace(namespace2) + .endMetadata() + .build(); mockClient.endpoints().inNamespace(namespace1).resource(endPoint1).create(); mockClient.endpoints().inNamespace(namespace2).resource(endPoint2).create(); @@ -184,19 +250,37 @@ void getEndPointsListShouldHandleNamespaces() { String namespace2 = "ns2"; String namespace3 = "ns3"; - Endpoints endPoint1 = new EndpointsBuilder().withNewMetadata().withName("endpoint").withNamespace(namespace1) - .endMetadata().build(); - Endpoints endPoint2 = new EndpointsBuilder().withNewMetadata().withName("endpoint").withNamespace(namespace2) - .endMetadata().build(); - Endpoints endPoint3 = new EndpointsBuilder().withNewMetadata().withName("endpoint").withNamespace(namespace3) - .endMetadata().build(); - - Service service1 = new ServiceBuilder().withNewMetadata().withName("endpoint").withNamespace(namespace1) - .endMetadata().build(); - Service service2 = new ServiceBuilder().withNewMetadata().withName("endpoint").withNamespace(namespace2) - .endMetadata().build(); - Service service3 = new ServiceBuilder().withNewMetadata().withName("endpoint").withNamespace(namespace3) - .endMetadata().build(); + Endpoints endPoint1 = new EndpointsBuilder().withNewMetadata() + .withName("endpoint") + .withNamespace(namespace1) + .endMetadata() + .build(); + Endpoints endPoint2 = new EndpointsBuilder().withNewMetadata() + .withName("endpoint") + .withNamespace(namespace2) + .endMetadata() + .build(); + Endpoints endPoint3 = new EndpointsBuilder().withNewMetadata() + .withName("endpoint") + .withNamespace(namespace3) + .endMetadata() + .build(); + + Service service1 = new ServiceBuilder().withNewMetadata() + .withName("endpoint") + .withNamespace(namespace1) + .endMetadata() + .build(); + Service service2 = new ServiceBuilder().withNewMetadata() + .withName("endpoint") + .withNamespace(namespace2) + .endMetadata() + .build(); + Service service3 = new ServiceBuilder().withNewMetadata() + .withName("endpoint") + .withNamespace(namespace3) + .endMetadata() + .build(); mockClient.endpoints().inNamespace(namespace1).resource(endPoint1).create(); mockClient.endpoints().inNamespace(namespace2).resource(endPoint2).create(); @@ -215,24 +299,47 @@ void getEndPointsListShouldHandleNamespaces() { List result_endpoints = discoveryClient.getEndPointsList("endpoint"); assertThat(result_endpoints).hasSize(2); - assertThat(result_endpoints.stream().map(Endpoints::getMetadata).map(ObjectMeta::getNamespace) - .collect(Collectors.toList())).containsOnly(namespace1, namespace3); + assertThat(result_endpoints.stream() + .map(Endpoints::getMetadata) + .map(ObjectMeta::getNamespace) + .collect(Collectors.toList())).containsOnly(namespace1, namespace3); } @Test void getInstancesShouldBeAbleToHandleEndpointsMultipleAddresses() { Map labels = Map.of("l1", "v1"); - Endpoints endPoint = new EndpointsBuilder().withNewMetadata().withName("endpoint").withNamespace("test") - .withLabels(labels).endMetadata().addNewSubset().addNewAddress().withIp("ip1").withNewTargetRef() - .withUid("40").endTargetRef().endAddress().addNewAddress().withIp("ip2").withNewTargetRef() - .withUid("50").endTargetRef().endAddress().addNewPort("https", "https_tcp", 443, "TCP").endSubset() - .build(); + Endpoints endPoint = new EndpointsBuilder().withNewMetadata() + .withName("endpoint") + .withNamespace("test") + .withLabels(labels) + .endMetadata() + .addNewSubset() + .addNewAddress() + .withIp("ip1") + .withNewTargetRef() + .withUid("40") + .endTargetRef() + .endAddress() + .addNewAddress() + .withIp("ip2") + .withNewTargetRef() + .withUid("50") + .endTargetRef() + .endAddress() + .addNewPort("https", "https_tcp", 443, "TCP") + .endSubset() + .build(); mockClient.endpoints().inNamespace("test").resource(endPoint).create(); Service service = new ServiceBuilder().withSpec(new ServiceSpecBuilder().withType("ExternalName").build()) - .withNewMetadata().withName("endpoint").withNamespace("test").withLabels(labels).endMetadata().build(); + .withNewMetadata() + .withName("endpoint") + .withNamespace("test") + .withLabels(labels) + .endMetadata() + .build(); mockClient.services().inNamespace("test").resource(service).create(); @@ -245,23 +352,36 @@ void getInstancesShouldBeAbleToHandleEndpointsMultipleAddresses() { List instances = discoveryClient.getInstances("endpoint"); - assertThat(instances).hasSize(2).filteredOn(ServiceInstance::isSecure).extracting(ServiceInstance::getHost) - .containsOnly("ip1", "ip2"); + assertThat(instances).hasSize(2) + .filteredOn(ServiceInstance::isSecure) + .extracting(ServiceInstance::getHost) + .containsOnly("ip1", "ip2"); } @Test void getServicesShouldReturnAllServicesWhenNoLabelsAreAppliedToTheClient() { Map service1Labels = Collections.singletonMap("label", "value"); - Service service1 = new ServiceBuilder().withNewMetadata().withName("s1").withNamespace("test") - .withLabels(service1Labels).endMetadata().build(); + Service service1 = new ServiceBuilder().withNewMetadata() + .withName("s1") + .withNamespace("test") + .withLabels(service1Labels) + .endMetadata() + .build(); Map service2Labels = Map.of("label", "value", "label2", "value2"); - Service service2 = new ServiceBuilder().withNewMetadata().withName("s2").withNamespace("test") - .withLabels(service2Labels).endMetadata().build(); - - Service service3 = new ServiceBuilder().withNewMetadata().withName("s3").withNamespace("test").endMetadata() - .build(); + Service service2 = new ServiceBuilder().withNewMetadata() + .withName("s2") + .withNamespace("test") + .withLabels(service2Labels) + .endMetadata() + .build(); + + Service service3 = new ServiceBuilder().withNewMetadata() + .withName("s3") + .withNamespace("test") + .endMetadata() + .build(); mockClient.services().inNamespace("test").resource(service1).create(); mockClient.services().inNamespace("test").resource(service2).create(); mockClient.services().inNamespace("test").resource(service3).create(); @@ -279,12 +399,20 @@ void getServicesShouldReturnAllServicesWhenNoLabelsAreAppliedToTheClient() { void getServicesShouldReturnOnlyMatchingServicesWhenLabelsAreAppliedToTheClient() { Map service1Labels = Collections.singletonMap("label", "value"); - Service service1 = new ServiceBuilder().withNewMetadata().withName("s1").withNamespace("test") - .withLabels(service1Labels).endMetadata().build(); + Service service1 = new ServiceBuilder().withNewMetadata() + .withName("s1") + .withNamespace("test") + .withLabels(service1Labels) + .endMetadata() + .build(); Map service2Labels = Map.of("label", "value", "label2", "value2"); - Service service2 = new ServiceBuilder().withNewMetadata().withName("s2").withNamespace("test") - .withLabels(service2Labels).endMetadata().build(); + Service service2 = new ServiceBuilder().withNewMetadata() + .withName("s2") + .withNamespace("test") + .withLabels(service2Labels) + .endMetadata() + .build(); mockClient.services().inNamespace("test").resource(service1).create(); mockClient.services().inNamespace("test").resource(service2).create(); @@ -306,14 +434,23 @@ void getServicesShouldReturnServicesInNamespaces() { String nameSpace2 = "ns2"; String nameSpace3 = "ns3"; - Service service1 = new ServiceBuilder().withNewMetadata().withName("s1").withNamespace(nameSpace1).endMetadata() - .build(); + Service service1 = new ServiceBuilder().withNewMetadata() + .withName("s1") + .withNamespace(nameSpace1) + .endMetadata() + .build(); - Service service2 = new ServiceBuilder().withNewMetadata().withName("s2").withNamespace(nameSpace2).endMetadata() - .build(); + Service service2 = new ServiceBuilder().withNewMetadata() + .withName("s2") + .withNamespace(nameSpace2) + .endMetadata() + .build(); - Service service3 = new ServiceBuilder().withNewMetadata().withName("s3").withNamespace(nameSpace3).endMetadata() - .build(); + Service service3 = new ServiceBuilder().withNewMetadata() + .withName("s3") + .withNamespace(nameSpace3) + .endMetadata() + .build(); mockClient.services().inNamespace(nameSpace1).resource(service1).create(); mockClient.services().inNamespace(nameSpace2).resource(service2).create(); @@ -333,24 +470,54 @@ void getServicesShouldReturnServicesInNamespaces() { @Test void getInstancesShouldBeAbleToHandleEndpointsFromMultipleNamespaces() { - Endpoints endPoints1 = new EndpointsBuilder().withNewMetadata().withName("endpoint").withNamespace("test") - .endMetadata().addNewSubset().addNewAddress().withIp("ip1").withNewTargetRef().withUid("60") - .endTargetRef().endAddress().addNewPort("http", "http_tcp", 80, "TCP").endSubset().build(); - - Endpoints endPoints2 = new EndpointsBuilder().withNewMetadata().withName("endpoint").withNamespace("test2") - .endMetadata().addNewSubset().addNewAddress().withIp("ip2").withNewTargetRef().withUid("70") - .endTargetRef().endAddress().addNewPort("http", "http_tcp", 80, "TCP").endSubset().build(); + Endpoints endPoints1 = new EndpointsBuilder().withNewMetadata() + .withName("endpoint") + .withNamespace("test") + .endMetadata() + .addNewSubset() + .addNewAddress() + .withIp("ip1") + .withNewTargetRef() + .withUid("60") + .endTargetRef() + .endAddress() + .addNewPort("http", "http_tcp", 80, "TCP") + .endSubset() + .build(); + + Endpoints endPoints2 = new EndpointsBuilder().withNewMetadata() + .withName("endpoint") + .withNamespace("test2") + .endMetadata() + .addNewSubset() + .addNewAddress() + .withIp("ip2") + .withNewTargetRef() + .withUid("70") + .endTargetRef() + .endAddress() + .addNewPort("http", "http_tcp", 80, "TCP") + .endSubset() + .build(); mockClient.endpoints().inNamespace("test").resource(endPoints1).create(); mockClient.endpoints().inNamespace("test2").resource(endPoints2).create(); Service service1 = new ServiceBuilder().withSpec(new ServiceSpecBuilder().withType("ExternalName").build()) - .withNewMetadata().withName("endpoint").withNamespace("test") - .withLabels(Collections.singletonMap("l", "v")).endMetadata().build(); + .withNewMetadata() + .withName("endpoint") + .withNamespace("test") + .withLabels(Collections.singletonMap("l", "v")) + .endMetadata() + .build(); Service service2 = new ServiceBuilder().withSpec(new ServiceSpecBuilder().withType("ExternalName").build()) - .withNewMetadata().withName("endpoint").withNamespace("test2") - .withLabels(Collections.singletonMap("l", "v")).endMetadata().build(); + .withNewMetadata() + .withName("endpoint") + .withNamespace("test2") + .withLabels(Collections.singletonMap("l", "v")) + .endMetadata() + .build(); mockClient.services().inNamespace("test").resource(service1).create(); mockClient.services().inNamespace("test2").resource(service2).create(); @@ -366,18 +533,26 @@ void getInstancesShouldBeAbleToHandleEndpointsFromMultipleNamespaces() { assertThat(instances).hasSize(2); assertThat(instances).filteredOn(s -> s.getHost().equals("ip1") && !s.isSecure()).hasSize(1); assertThat(instances).filteredOn(s -> s.getHost().equals("ip2") && !s.isSecure()).hasSize(1); - assertThat(instances).filteredOn(s -> s.getServiceId().contains("endpoint") - && ((KubernetesServiceInstance) s).getNamespace().equals("test")).hasSize(1); - assertThat(instances).filteredOn(s -> s.getServiceId().contains("endpoint") - && ((KubernetesServiceInstance) s).getNamespace().equals("test2")).hasSize(1); + assertThat(instances) + .filteredOn(s -> s.getServiceId().contains("endpoint") + && ((KubernetesServiceInstance) s).getNamespace().equals("test")) + .hasSize(1); + assertThat(instances) + .filteredOn(s -> s.getServiceId().contains("endpoint") + && ((KubernetesServiceInstance) s).getNamespace().equals("test2")) + .hasSize(1); assertThat(instances).filteredOn(s -> s.getInstanceId().equals("60")).hasSize(1); assertThat(instances).filteredOn(s -> s.getInstanceId().equals("70")).hasSize(1); } @Test void instanceWithoutSubsetsShouldBeSkipped() { - Endpoints endPoint = new EndpointsBuilder().withNewMetadata().withName("endpoint1").withNamespace("test") - .withLabels(Collections.emptyMap()).endMetadata().build(); + Endpoints endPoint = new EndpointsBuilder().withNewMetadata() + .withName("endpoint1") + .withNamespace("test") + .withLabels(Collections.emptyMap()) + .endMetadata() + .build(); mockClient.endpoints().inNamespace("test").resource(endPoint).create(); @@ -394,16 +569,33 @@ void instanceWithoutSubsetsShouldBeSkipped() { void getInstancesShouldBeAbleToHandleEndpointsSingleAddressAndMultiplePortsUsingPrimaryPortNameLabel() { Map labels = Map.of("primary-port-name", "https"); - Endpoints endPoint1 = new EndpointsBuilder().withNewMetadata().withName("endpoint2").withNamespace("test") - .withLabels(labels).endMetadata().addNewSubset().addNewAddress().withIp("ip1").withNewTargetRef() - .withUid("80").endTargetRef().endAddress().addNewPort("http", "https", 443, "TCP") - .addNewPort("http", "http", 80, "TCP").endSubset().build(); + Endpoints endPoint1 = new EndpointsBuilder().withNewMetadata() + .withName("endpoint2") + .withNamespace("test") + .withLabels(labels) + .endMetadata() + .addNewSubset() + .addNewAddress() + .withIp("ip1") + .withNewTargetRef() + .withUid("80") + .endTargetRef() + .endAddress() + .addNewPort("http", "https", 443, "TCP") + .addNewPort("http", "http", 80, "TCP") + .endSubset() + .build(); mockClient.endpoints().inNamespace("test").resource(endPoint1).create(); Service service = new ServiceBuilder().withSpec(new ServiceSpecBuilder().withType("ExternalName").build()) - .withNewMetadata().withName("endpoint2").withNamespace("test").withLabels(labels) - .withAnnotations(labels).endMetadata().build(); + .withNewMetadata() + .withName("endpoint2") + .withNamespace("test") + .withLabels(labels) + .withAnnotations(labels) + .endMetadata() + .build(); mockClient.services().inNamespace("test").resource(service).create(); @@ -415,26 +607,48 @@ void getInstancesShouldBeAbleToHandleEndpointsSingleAddressAndMultiplePortsUsing List instances = discoveryClient.getInstances("endpoint2"); - assertThat(instances).hasSize(1).filteredOn(s -> s.getHost().equals("ip1") && s.isSecure()).hasSize(1) - .filteredOn(s -> s.getInstanceId().equals("80")).hasSize(1).filteredOn(s -> 443 == s.getPort()) - .hasSize(1); + assertThat(instances).hasSize(1) + .filteredOn(s -> s.getHost().equals("ip1") && s.isSecure()) + .hasSize(1) + .filteredOn(s -> s.getInstanceId().equals("80")) + .hasSize(1) + .filteredOn(s -> 443 == s.getPort()) + .hasSize(1); } @Test void instanceWithMultiplePortsAndMisconfiguredPrimaryPortNameInLabelWithoutFallbackShouldLogWarning() { Map labels = Map.of("primary-port-name", "oops"); - Endpoints endPoint1 = new EndpointsBuilder().withNewMetadata().withName("endpoint3").withNamespace("test") - .withLabels(labels).endMetadata().addNewSubset().addNewAddress().withIp("ip1").withNewTargetRef() - .withUid("90").endTargetRef().endAddress().addNewPort("http", "https1", 443, "TCP") - .addNewPort("http", "https2", 8443, "TCP").addNewPort("http", "http1", 80, "TCP") - .addNewPort("http", "http2", 8080, "TCP").endSubset().build(); + Endpoints endPoint1 = new EndpointsBuilder().withNewMetadata() + .withName("endpoint3") + .withNamespace("test") + .withLabels(labels) + .endMetadata() + .addNewSubset() + .addNewAddress() + .withIp("ip1") + .withNewTargetRef() + .withUid("90") + .endTargetRef() + .endAddress() + .addNewPort("http", "https1", 443, "TCP") + .addNewPort("http", "https2", 8443, "TCP") + .addNewPort("http", "http1", 80, "TCP") + .addNewPort("http", "http2", 8080, "TCP") + .endSubset() + .build(); mockClient.endpoints().inNamespace("test").resource(endPoint1).create(); Service service = new ServiceBuilder().withSpec(new ServiceSpecBuilder().withType("ExternalName").build()) - .withNewMetadata().withName("endpoint3").withNamespace("test").withLabels(labels) - .withAnnotations(labels).endMetadata().build(); + .withNewMetadata() + .withName("endpoint3") + .withNamespace("test") + .withLabels(labels) + .withAnnotations(labels) + .endMetadata() + .build(); mockClient.services().inNamespace("test").resource(service).create(); @@ -446,25 +660,47 @@ void instanceWithMultiplePortsAndMisconfiguredPrimaryPortNameInLabelWithoutFallb List instances = discoveryClient.getInstances("endpoint3"); - assertThat(instances).hasSize(1).filteredOn(s -> s.getHost().equals("ip1") && s.isSecure()).hasSize(1) - .filteredOn(s -> s.getInstanceId().equals("90")).hasSize(1).hasSize(1); + assertThat(instances).hasSize(1) + .filteredOn(s -> s.getHost().equals("ip1") && s.isSecure()) + .hasSize(1) + .filteredOn(s -> s.getInstanceId().equals("90")) + .hasSize(1) + .hasSize(1); } @Test void instanceWithMultiplePortsAndMisconfiguredGenericPrimaryPortNameWithoutFallbackShouldLogWarning() { Map labels = Map.of(); - Endpoints endPoint = new EndpointsBuilder().withNewMetadata().withName("endpoint4").withNamespace("test") - .withLabels(labels).endMetadata().addNewSubset().addNewAddress().withIp("ip1").withNewTargetRef() - .withUid("100").endTargetRef().endAddress().addNewPort("http", "https1", 443, "TCP") - .addNewPort("http", "https2", 8443, "TCP").addNewPort("http", "http1", 80, "TCP") - .addNewPort("http", "http2", 8080, "TCP").endSubset().build(); + Endpoints endPoint = new EndpointsBuilder().withNewMetadata() + .withName("endpoint4") + .withNamespace("test") + .withLabels(labels) + .endMetadata() + .addNewSubset() + .addNewAddress() + .withIp("ip1") + .withNewTargetRef() + .withUid("100") + .endTargetRef() + .endAddress() + .addNewPort("http", "https1", 443, "TCP") + .addNewPort("http", "https2", 8443, "TCP") + .addNewPort("http", "http1", 80, "TCP") + .addNewPort("http", "http2", 8080, "TCP") + .endSubset() + .build(); mockClient.endpoints().inNamespace("test").resource(endPoint).create(); Service service = new ServiceBuilder().withSpec(new ServiceSpecBuilder().withType("ExternalName").build()) - .withNewMetadata().withName("endpoint4").withNamespace("test").withLabels(labels) - .withAnnotations(labels).endMetadata().build(); + .withNewMetadata() + .withName("endpoint4") + .withNamespace("test") + .withLabels(labels) + .withAnnotations(labels) + .endMetadata() + .build(); mockClient.services().inNamespace("test").resource(service).create(); @@ -476,24 +712,45 @@ void instanceWithMultiplePortsAndMisconfiguredGenericPrimaryPortNameWithoutFallb List instances = discoveryClient.getInstances("endpoint4"); - assertThat(instances).hasSize(1).filteredOn(s -> s.getHost().equals("ip1") && s.isSecure()).hasSize(1) - .filteredOn(s -> s.getInstanceId().equals("100")).hasSize(1).hasSize(1); + assertThat(instances).hasSize(1) + .filteredOn(s -> s.getHost().equals("ip1") && s.isSecure()) + .hasSize(1) + .filteredOn(s -> s.getInstanceId().equals("100")) + .hasSize(1) + .hasSize(1); } @Test void instanceWithMultiplePortsAndWithoutPrimaryPortNameSpecifiedShouldFallBackToHttps() { Map labels = Map.of(); - Endpoints endPoint1 = new EndpointsBuilder().withNewMetadata().withName("endpoint5").withNamespace("test") - .withLabels(labels).endMetadata().addNewSubset().addNewAddress().withIp("ip1").withNewTargetRef() - .withUid("110").endTargetRef().endAddress().addNewPort("http", "https", 443, "TCP") - .addNewPort("http", "http", 80, "TCP").endSubset().build(); + Endpoints endPoint1 = new EndpointsBuilder().withNewMetadata() + .withName("endpoint5") + .withNamespace("test") + .withLabels(labels) + .endMetadata() + .addNewSubset() + .addNewAddress() + .withIp("ip1") + .withNewTargetRef() + .withUid("110") + .endTargetRef() + .endAddress() + .addNewPort("http", "https", 443, "TCP") + .addNewPort("http", "http", 80, "TCP") + .endSubset() + .build(); mockClient.endpoints().inNamespace("test").resource(endPoint1).create(); Service service = new ServiceBuilder().withSpec(new ServiceSpecBuilder().withType("ExternalName").build()) - .withNewMetadata().withName("endpoint5").withNamespace("test").withLabels(labels) - .withAnnotations(labels).endMetadata().build(); + .withNewMetadata() + .withName("endpoint5") + .withNamespace("test") + .withLabels(labels) + .withAnnotations(labels) + .endMetadata() + .build(); mockClient.services().inNamespace("test").resource(service).create(); @@ -505,25 +762,47 @@ void instanceWithMultiplePortsAndWithoutPrimaryPortNameSpecifiedShouldFallBackTo List instances = discoveryClient.getInstances("endpoint5"); - assertThat(instances).hasSize(1).filteredOn(s -> s.getHost().equals("ip1") && s.isSecure()).hasSize(1) - .filteredOn(s -> s.getInstanceId().equals("110")).hasSize(1).filteredOn(s -> 443 == s.getPort()) - .hasSize(1); + assertThat(instances).hasSize(1) + .filteredOn(s -> s.getHost().equals("ip1") && s.isSecure()) + .hasSize(1) + .filteredOn(s -> s.getInstanceId().equals("110")) + .hasSize(1) + .filteredOn(s -> 443 == s.getPort()) + .hasSize(1); } @Test void instanceWithMultiplePortsAndWithoutPrimaryPortNameSpecifiedOrHttpsPortShouldFallBackToHttp() { Map labels = Map.of(); - Endpoints endPoint1 = new EndpointsBuilder().withNewMetadata().withName("endpoint5").withNamespace("test") - .withLabels(labels).endMetadata().addNewSubset().addNewAddress().withIp("ip1").withNewTargetRef() - .withUid("120").endTargetRef().endAddress().addNewPort("http", "https1", 443, "TCP") - .addNewPort("http", "https2", 8443, "TCP").addNewPort("http", "http", 80, "TCP").endSubset().build(); + Endpoints endPoint1 = new EndpointsBuilder().withNewMetadata() + .withName("endpoint5") + .withNamespace("test") + .withLabels(labels) + .endMetadata() + .addNewSubset() + .addNewAddress() + .withIp("ip1") + .withNewTargetRef() + .withUid("120") + .endTargetRef() + .endAddress() + .addNewPort("http", "https1", 443, "TCP") + .addNewPort("http", "https2", 8443, "TCP") + .addNewPort("http", "http", 80, "TCP") + .endSubset() + .build(); mockClient.endpoints().inNamespace("test").resource(endPoint1).create(); Service service = new ServiceBuilder().withSpec(new ServiceSpecBuilder().withType("ExternalName").build()) - .withNewMetadata().withName("endpoint5").withNamespace("test").withLabels(labels) - .withAnnotations(labels).endMetadata().build(); + .withNewMetadata() + .withName("endpoint5") + .withNamespace("test") + .withLabels(labels) + .withAnnotations(labels) + .endMetadata() + .build(); mockClient.services().inNamespace("test").resource(service).create(); @@ -533,25 +812,46 @@ void instanceWithMultiplePortsAndWithoutPrimaryPortNameSpecifiedOrHttpsPortShoul List instances = discoveryClient.getInstances("endpoint5"); - assertThat(instances).hasSize(1).filteredOn(s -> s.getHost().equals("ip1") && !s.isSecure()).hasSize(1) - .filteredOn(s -> s.getInstanceId().equals("120")).hasSize(1).filteredOn(s -> 80 == s.getPort()) - .hasSize(1); + assertThat(instances).hasSize(1) + .filteredOn(s -> s.getHost().equals("ip1") && !s.isSecure()) + .hasSize(1) + .filteredOn(s -> s.getInstanceId().equals("120")) + .hasSize(1) + .filteredOn(s -> 80 == s.getPort()) + .hasSize(1); } @Test void instanceWithMultiplePortsAndWithoutPrimaryPortNameSpecifiedShouldLogWarning() { Map labels = Map.of(); - Endpoints endPoint1 = new EndpointsBuilder().withNewMetadata().withName("endpoint5").withNamespace("test") - .withLabels(labels).endMetadata().addNewSubset().addNewAddress().withIp("ip1").withNewTargetRef() - .withUid("130").endTargetRef().endAddress().addNewPort("http", "https", 443, "TCP") - .addNewPort("http", "http", 80, "TCP").endSubset().build(); + Endpoints endPoint1 = new EndpointsBuilder().withNewMetadata() + .withName("endpoint5") + .withNamespace("test") + .withLabels(labels) + .endMetadata() + .addNewSubset() + .addNewAddress() + .withIp("ip1") + .withNewTargetRef() + .withUid("130") + .endTargetRef() + .endAddress() + .addNewPort("http", "https", 443, "TCP") + .addNewPort("http", "http", 80, "TCP") + .endSubset() + .build(); mockClient.endpoints().inNamespace("test").resource(endPoint1).create(); Service service = new ServiceBuilder().withSpec(new ServiceSpecBuilder().withType("ExternalName").build()) - .withNewMetadata().withName("endpoint5").withNamespace("test").withLabels(labels) - .withAnnotations(labels).endMetadata().build(); + .withNewMetadata() + .withName("endpoint5") + .withNamespace("test") + .withLabels(labels) + .withAnnotations(labels) + .endMetadata() + .build(); mockClient.services().inNamespace("test").resource(service).create(); @@ -564,24 +864,44 @@ void instanceWithMultiplePortsAndWithoutPrimaryPortNameSpecifiedShouldLogWarning List instances = discoveryClient.getInstances("endpoint5"); // We're returning the first discovered port to not change previous behaviour - assertThat(instances).hasSize(1).filteredOn(s -> s.getHost().equals("ip1") && s.isSecure()).hasSize(1) - .filteredOn(s -> s.getInstanceId().equals("130")).hasSize(1).filteredOn(s -> 443 == s.getPort()) - .hasSize(1); + assertThat(instances).hasSize(1) + .filteredOn(s -> s.getHost().equals("ip1") && s.isSecure()) + .hasSize(1) + .filteredOn(s -> s.getInstanceId().equals("130")) + .hasSize(1) + .filteredOn(s -> 443 == s.getPort()) + .hasSize(1); } @Test public void instanceWithoutPorts() { Map labels = new HashMap<>(); - Endpoints endPoint1 = new EndpointsBuilder().withNewMetadata().withName("endpoint5").withNamespace("test") - .withLabels(labels).endMetadata().addNewSubset().addNewAddress().withIp("ip1").withNewTargetRef() - .withUid("130").endTargetRef().endAddress().endSubset().build(); + Endpoints endPoint1 = new EndpointsBuilder().withNewMetadata() + .withName("endpoint5") + .withNamespace("test") + .withLabels(labels) + .endMetadata() + .addNewSubset() + .addNewAddress() + .withIp("ip1") + .withNewTargetRef() + .withUid("130") + .endTargetRef() + .endAddress() + .endSubset() + .build(); mockClient.endpoints().inNamespace("test").create(endPoint1); Service service = new ServiceBuilder().withSpec(new ServiceSpecBuilder().withType("ClusterIP").build()) - .withNewMetadata().withName("endpoint5").withNamespace("test").withLabels(labels) - .withAnnotations(labels).endMetadata().build(); + .withNewMetadata() + .withName("endpoint5") + .withNamespace("test") + .withLabels(labels) + .withAnnotations(labels) + .endMetadata() + .build(); mockClient.services().inNamespace("test").create(service); @@ -593,10 +913,14 @@ public void instanceWithoutPorts() { final List instances = discoveryClient.getInstances("endpoint5"); // We're returning the first discovered port to not change previous behaviour - assertThat(instances).hasSize(1).filteredOn(s -> s.getHost().equals("ip1") && !s.isSecure()).hasSize(1) - .filteredOn(s -> s.getUri().toASCIIString().equals("http://ip1")) - .filteredOn(s -> s.getInstanceId().equals("130")).hasSize(1).filteredOn(s -> 0 == s.getPort()) - .hasSize(1); + assertThat(instances).hasSize(1) + .filteredOn(s -> s.getHost().equals("ip1") && !s.isSecure()) + .hasSize(1) + .filteredOn(s -> s.getUri().toASCIIString().equals("http://ip1")) + .filteredOn(s -> s.getInstanceId().equals("130")) + .hasSize(1) + .filteredOn(s -> 0 == s.getPort()) + .hasSize(1); } } diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8KubernetesDiscoveryClientTests.java b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8KubernetesDiscoveryClientTests.java index d4d55e2988..41aee5673a 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8KubernetesDiscoveryClientTests.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8KubernetesDiscoveryClientTests.java @@ -498,13 +498,21 @@ void testSelectiveNamespacesMultipleNamespacesAllMatch(CapturedOutput output) { @Test void testGetServicesWithExternalNameService() { Service nonExternalNameService = new ServiceBuilder() - .withSpec(new ServiceSpecBuilder().withType("ClusterIP").build()).withNewMetadata() - .withName("blue-service").withNamespace("a").endMetadata().build(); + .withSpec(new ServiceSpecBuilder().withType("ClusterIP").build()) + .withNewMetadata() + .withName("blue-service") + .withNamespace("a") + .endMetadata() + .build(); client.services().inNamespace("a").resource(nonExternalNameService).create(); Service externalNameService = new ServiceBuilder() - .withSpec(new ServiceSpecBuilder().withType("ExternalName").withExternalName("k8s-spring").build()) - .withNewMetadata().withName("blue-service").withNamespace("b").endMetadata().build(); + .withSpec(new ServiceSpecBuilder().withType("ExternalName").withExternalName("k8s-spring").build()) + .withNewMetadata() + .withName("blue-service") + .withNamespace("b") + .endMetadata() + .build(); client.services().inNamespace("b").resource(externalNameService).create(); // last argument is irrelevant, as getServices does not care about that flag @@ -520,9 +528,14 @@ void testGetServicesWithExternalNameService() { @Test void testExternalNameService() { Service externalNameService = new ServiceBuilder() - .withSpec(new ServiceSpecBuilder().withType("ExternalName").withExternalName("k8s-spring-b").build()) - .withNewMetadata().withLabels(Map.of("label-key", "label-value")).withAnnotations(Map.of("abc", "def")) - .withName("blue-service").withNamespace("b").endMetadata().build(); + .withSpec(new ServiceSpecBuilder().withType("ExternalName").withExternalName("k8s-spring-b").build()) + .withNewMetadata() + .withLabels(Map.of("label-key", "label-value")) + .withAnnotations(Map.of("abc", "def")) + .withName("blue-service") + .withNamespace("b") + .endMetadata() + .build(); client.services().inNamespace("b").resource(externalNameService).create(); KubernetesDiscoveryProperties.Metadata metadata = new KubernetesDiscoveryProperties.Metadata(true, @@ -546,21 +559,34 @@ void testExternalNameService() { @Test void testPodMetadata() { Service nonExternalNameService = new ServiceBuilder() - .withSpec(new ServiceSpecBuilder().withType("ClusterIP").build()).withNewMetadata() - .withName("blue-service").withNamespace("a").endMetadata().build(); + .withSpec(new ServiceSpecBuilder().withType("ClusterIP").build()) + .withNewMetadata() + .withName("blue-service") + .withNamespace("a") + .endMetadata() + .build(); client.services().inNamespace("a").resource(nonExternalNameService).create(); - client.endpoints().inNamespace("a").resource(new EndpointsBuilder() - .withMetadata(new ObjectMetaBuilder().withName("blue-service").build()) + client.endpoints() + .inNamespace("a") + .resource(new EndpointsBuilder().withMetadata(new ObjectMetaBuilder().withName("blue-service").build()) .withSubsets(new EndpointSubsetBuilder().withPorts(new EndpointPortBuilder().withPort(8080).build()) - .withAddresses(new EndpointAddressBuilder().withIp("127.0.0.1") - .withTargetRef(new ObjectReferenceBuilder().withKind("Pod").withName("my-pod").build()) - .build()) + .withAddresses(new EndpointAddressBuilder().withIp("127.0.0.1") + .withTargetRef(new ObjectReferenceBuilder().withKind("Pod").withName("my-pod").build()) .build()) - .build()).create(); - - client.pods().inNamespace("a").resource(new PodBuilder().withMetadata(new ObjectMetaBuilder().withName("my-pod") - .withLabels(Map.of("a", "b")).withAnnotations(Map.of("c", "d")).build()).build()).create(); + .build()) + .build()) + .create(); + + client.pods() + .inNamespace("a") + .resource(new PodBuilder() + .withMetadata(new ObjectMetaBuilder().withName("my-pod") + .withLabels(Map.of("a", "b")) + .withAnnotations(Map.of("c", "d")) + .build()) + .build()) + .create(); KubernetesDiscoveryProperties.Metadata metadata = new KubernetesDiscoveryProperties.Metadata(true, "labels-prefix-", true, "annotations-prefix-", true, "ports-prefix", true, true); @@ -583,17 +609,21 @@ void testPodMetadata() { } private void createEndpoints(String namespace, String name, Map labels) { - client.endpoints().inNamespace(namespace) - .resource(new EndpointsBuilder() - .withMetadata(new ObjectMetaBuilder().withName(name).withLabels(labels).build()).build()) - .create(); + client.endpoints() + .inNamespace(namespace) + .resource(new EndpointsBuilder() + .withMetadata(new ObjectMetaBuilder().withName(name).withLabels(labels).build()) + .build()) + .create(); } private void createService(String namespace, String name, Map labels) { - client.services().inNamespace(namespace) - .resource(new ServiceBuilder() - .withMetadata(new ObjectMetaBuilder().withName(name).withLabels(labels).build()).build()) - .create(); + client.services() + .inNamespace(namespace) + .resource( + new ServiceBuilder().withMetadata(new ObjectMetaBuilder().withName(name).withLabels(labels).build()) + .build()) + .create(); } } diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8KubernetesDiscoveryClientUtilsFilterTests.java b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8KubernetesDiscoveryClientUtilsFilterTests.java index c44d08e026..d8f2796e12 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8KubernetesDiscoveryClientUtilsFilterTests.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8KubernetesDiscoveryClientUtilsFilterTests.java @@ -239,15 +239,21 @@ void withFilterSingleEndpointsNoPredicateMatch() { } private Endpoints createEndpoints(String name, String namespace) { - Endpoints endpoints = new EndpointsBuilder().withNewMetadata().withName(name).withNamespace(namespace) - .endMetadata().build(); + Endpoints endpoints = new EndpointsBuilder().withNewMetadata() + .withName(name) + .withNamespace(namespace) + .endMetadata() + .build(); client.endpoints().inNamespace(namespace).resource(endpoints).create(); return endpoints; } private void createService(String name, String namespace) { - Service service = new ServiceBuilder().withNewMetadata().withName(name).withNamespace(namespace).endMetadata() - .build(); + Service service = new ServiceBuilder().withNewMetadata() + .withName(name) + .withNamespace(namespace) + .endMetadata() + .build(); client.services().inNamespace(namespace).resource(service).create(); } diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8KubernetesDiscoveryClientUtilsTests.java b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8KubernetesDiscoveryClientUtilsTests.java index a19db4f5e3..30e0ae52ba 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8KubernetesDiscoveryClientUtilsTests.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8KubernetesDiscoveryClientUtilsTests.java @@ -270,8 +270,11 @@ void testServicesNamespaceProviderPredicateFilter() { @Test void testExternalName() { Service service = new ServiceBuilder() - .withSpec(new ServiceSpecBuilder().withType("ExternalName").withExternalName("k8s-spring").build()) - .withNewMetadata().withName("external-name-service").and().build(); + .withSpec(new ServiceSpecBuilder().withType("ExternalName").withExternalName("k8s-spring").build()) + .withNewMetadata() + .withName("external-name-service") + .and() + .build(); client.services().inNamespace("test").resource(service).create(); boolean allNamespaces = false; @@ -288,9 +291,10 @@ void testExternalName() { void testPortsDataOne() { List endpointSubsets = List.of( new EndpointSubsetBuilder().withPorts(new EndpointPortBuilder().withPort(8081).withName("").build()) - .build(), + .build(), new EndpointSubsetBuilder() - .withPorts(new EndpointPortBuilder().withPort(8080).withName("https").build()).build()); + .withPorts(new EndpointPortBuilder().withPort(8080).withName("https").build()) + .build()); Map portsData = endpointSubsetsPortData(endpointSubsets); Assertions.assertEquals(portsData.size(), 2); @@ -302,9 +306,10 @@ void testPortsDataOne() { void testPortsDataTwo() { List endpointSubsets = List.of( new EndpointSubsetBuilder().withPorts(new EndpointPortBuilder().withPort(8081).withName("http").build()) - .build(), + .build(), new EndpointSubsetBuilder() - .withPorts(new EndpointPortBuilder().withPort(8080).withName("https").build()).build()); + .withPorts(new EndpointPortBuilder().withPort(8080).withName("https").build()) + .build()); Map portsData = endpointSubsetsPortData(endpointSubsets); Assertions.assertEquals(portsData.size(), 2); @@ -323,7 +328,8 @@ void endpointSubsetPortsDataWithoutPorts() { @Test void endpointSubsetPortsDataSinglePort() { EndpointSubset endpointSubset = new EndpointSubsetBuilder() - .withPorts(new EndpointPortBuilder().withName("name").withPort(80).build()).build(); + .withPorts(new EndpointPortBuilder().withName("name").withPort(80).build()) + .build(); Map result = endpointSubsetsPortData(List.of(endpointSubset)); Assertions.assertEquals(result.size(), 1); @@ -333,7 +339,8 @@ void endpointSubsetPortsDataSinglePort() { @Test void endpointSubsetPortsDataSinglePortNoName() { EndpointSubset endpointSubset = new EndpointSubsetBuilder() - .withPorts(new EndpointPortBuilder().withPort(80).build()).build(); + .withPorts(new EndpointPortBuilder().withPort(80).build()) + .build(); Map result = endpointSubsetsPortData(List.of(endpointSubset)); Assertions.assertEquals(result.size(), 1); @@ -341,8 +348,12 @@ void endpointSubsetPortsDataSinglePortNoName() { } private void service(String name, String namespace, Map labels) { - Service service = new ServiceBuilder().withNewMetadata().withName(name).withLabels(labels) - .withNamespace(namespace).and().build(); + Service service = new ServiceBuilder().withNewMetadata() + .withName(name) + .withLabels(labels) + .withNamespace(namespace) + .and() + .build(); client.services().inNamespace(namespace).resource(service).create(); } diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8PodLabelsAndAnnotationsSupplierTests.java b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8PodLabelsAndAnnotationsSupplierTests.java index 08e5de0830..1f9277d74c 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8PodLabelsAndAnnotationsSupplierTests.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8PodLabelsAndAnnotationsSupplierTests.java @@ -47,12 +47,13 @@ void afterEach() { @Test void noObjetMeta() { - client.pods().inNamespace(NAMESPACE) - .resource(new PodBuilder().withMetadata(new ObjectMetaBuilder().withName(POD_NAME).build()).build()) - .create(); + client.pods() + .inNamespace(NAMESPACE) + .resource(new PodBuilder().withMetadata(new ObjectMetaBuilder().withName(POD_NAME).build()).build()) + .create(); PodLabelsAndAnnotations result = Fabric8PodLabelsAndAnnotationsSupplier.nonExternalName(client, NAMESPACE) - .apply(POD_NAME); + .apply(POD_NAME); Assertions.assertNotNull(result); Assertions.assertTrue(result.labels().isEmpty()); Assertions.assertTrue(result.annotations().isEmpty()); @@ -60,12 +61,18 @@ void noObjetMeta() { @Test void labelsAndAnnotationsPresent() { - client.pods().inNamespace(NAMESPACE).resource(new PodBuilder().withMetadata(new ObjectMetaBuilder() - .withName(POD_NAME).withLabels(Map.of("a", "b")).withAnnotations(Map.of("c", "d")).build()).build()) - .create(); + client.pods() + .inNamespace(NAMESPACE) + .resource(new PodBuilder() + .withMetadata(new ObjectMetaBuilder().withName(POD_NAME) + .withLabels(Map.of("a", "b")) + .withAnnotations(Map.of("c", "d")) + .build()) + .build()) + .create(); PodLabelsAndAnnotations result = Fabric8PodLabelsAndAnnotationsSupplier.nonExternalName(client, NAMESPACE) - .apply(POD_NAME); + .apply(POD_NAME); Assertions.assertNotNull(result); Assertions.assertEquals(result.labels(), Map.of("a", "b")); Assertions.assertEquals(result.annotations(), Map.of("c", "d")); diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesCatalogServicesWatchConfigurationTest.java b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesCatalogServicesWatchConfigurationTest.java index 6ad806343a..21f0aae386 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesCatalogServicesWatchConfigurationTest.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesCatalogServicesWatchConfigurationTest.java @@ -83,7 +83,9 @@ private void setup(String... env) { context = new SpringApplicationBuilder(PropertyPlaceholderAutoConfiguration.class, KubernetesClientTestConfiguration.class, KubernetesCatalogWatchAutoConfiguration.class, KubernetesDiscoveryClientAutoConfiguration.class, KubernetesDiscoveryPropertiesAutoConfiguration.class) - .web(WebApplicationType.NONE).properties(envList.toArray(new String[0])).run(); + .web(WebApplicationType.NONE) + .properties(envList.toArray(new String[0])) + .run(); } @Configuration(proxyBeanMethods = false) diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesCatalogWatchAutoConfigurationApplicationContextTests.java b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesCatalogWatchAutoConfigurationApplicationContextTests.java index 0978a6b68b..859fa8ed91 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesCatalogWatchAutoConfigurationApplicationContextTests.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesCatalogWatchAutoConfigurationApplicationContextTests.java @@ -131,10 +131,11 @@ void disableKubernetesDiscovery() { } private void setup(String... properties) { - applicationContextRunner = new ApplicationContextRunner().withConfiguration( - AutoConfigurations.of(KubernetesCatalogWatchAutoConfiguration.class, Fabric8AutoConfiguration.class, - KubernetesCommonsAutoConfiguration.class, KubernetesDiscoveryPropertiesAutoConfiguration.class)) - .withPropertyValues(properties); + applicationContextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(KubernetesCatalogWatchAutoConfiguration.class, + Fabric8AutoConfiguration.class, KubernetesCommonsAutoConfiguration.class, + KubernetesDiscoveryPropertiesAutoConfiguration.class)) + .withPropertyValues(properties); } } diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesCatalogWatchTest.java b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesCatalogWatchTest.java index dbefc0e673..679ed17118 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesCatalogWatchTest.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesCatalogWatchTest.java @@ -70,22 +70,22 @@ class KubernetesCatalogWatchTest { private KubernetesCatalogWatch kubernetesCatalogWatch; private static final ApplicationEventPublisher APPLICATION_EVENT_PUBLISHER = Mockito - .mock(ApplicationEventPublisher.class); + .mock(ApplicationEventPublisher.class); private static final MixedOperation> MIXED_OPERATION = Mockito - .mock(MixedOperation.class); + .mock(MixedOperation.class); private static final NonNamespaceOperation> NON_NAMESPACE_OPERATION = Mockito - .mock(NonNamespaceOperation.class); + .mock(NonNamespaceOperation.class); private static final FilterWatchListDeletable> FILTER_WATCH_LIST_DELETABLE = Mockito - .mock(FilterWatchListDeletable.class); + .mock(FilterWatchListDeletable.class); private static final FilterNested>> FILTER_NESTED = Mockito - .mock(FilterNested.class); + .mock(FilterNested.class); private static final ArgumentCaptor HEARTBEAT_EVENT_ARGUMENT_CAPTOR = ArgumentCaptor - .forClass(HeartbeatEvent.class); + .forClass(HeartbeatEvent.class); @AfterEach void afterEach() { @@ -99,8 +99,8 @@ void testRandomOrderChangePods() { createInSpecificNamespaceWatcher(); when(FILTER_WATCH_LIST_DELETABLE.list()) - .thenReturn(createSingleEndpointEndpointListByPodName("test", "api-pod", "other-pod")) - .thenReturn(createSingleEndpointEndpointListByPodName("test", "other-pod", "api-pod")); + .thenReturn(createSingleEndpointEndpointListByPodName("test", "api-pod", "other-pod")) + .thenReturn(createSingleEndpointEndpointListByPodName("test", "other-pod", "api-pod")); mockServicesCall("api-pod", "test"); mockServicesCall("other-pod", "test"); @@ -117,8 +117,8 @@ void testRandomOrderChangePodsAllNamespaces() { createInAllNamespaceWatcher(); when(FILTER_WATCH_LIST_DELETABLE.list()) - .thenReturn(createSingleEndpointEndpointListByPodName("test", "api-pod", "other-pod")) - .thenReturn(createSingleEndpointEndpointListByPodName("test", "other-pod", "api-pod")); + .thenReturn(createSingleEndpointEndpointListByPodName("test", "api-pod", "other-pod")) + .thenReturn(createSingleEndpointEndpointListByPodName("test", "other-pod", "api-pod")); mockServicesCall("api-pod", "test"); mockServicesCall("other-pod", "test"); @@ -136,8 +136,8 @@ void testRandomOrderChangeServices() { createInSpecificNamespaceWatcher(); when(FILTER_WATCH_LIST_DELETABLE.list()) - .thenReturn(createEndpointsListByServiceName("test", "api-service", "other-service")) - .thenReturn(createEndpointsListByServiceName("test", "other-service", "api-service")); + .thenReturn(createEndpointsListByServiceName("test", "api-service", "other-service")) + .thenReturn(createEndpointsListByServiceName("test", "other-service", "api-service")); mockServicesCall("api-service", "test"); mockServicesCall("other-service", "test"); @@ -154,8 +154,8 @@ void testRandomOrderChangeServicesAllNamespaces() { createInAllNamespaceWatcher(); when(FILTER_WATCH_LIST_DELETABLE.list()) - .thenReturn(createEndpointsListByServiceName("test", "api-service", "other-service")) - .thenReturn(createEndpointsListByServiceName("test", "other-service", "api-service")); + .thenReturn(createEndpointsListByServiceName("test", "api-service", "other-service")) + .thenReturn(createEndpointsListByServiceName("test", "other-service", "api-service")); mockServicesCall("api-service", "test"); mockServicesCall("other-service", "test"); @@ -172,7 +172,7 @@ void testEventBody() { createInSpecificNamespaceWatcher(); when(FILTER_WATCH_LIST_DELETABLE.list()) - .thenReturn(createSingleEndpointListWithNamespace("default", "other-pod", "api-pod", "other-pod")); + .thenReturn(createSingleEndpointListWithNamespace("default", "other-pod", "api-pod", "other-pod")); mockServicesCall("api-pod", "default"); mockServicesCall("other-pod", "default"); @@ -194,7 +194,7 @@ void testEventBodyAllNamespaces() { createInAllNamespaceWatcher(); when(FILTER_WATCH_LIST_DELETABLE.list()) - .thenReturn(createSingleEndpointListWithNamespace("default", "other-pod", "api-pod", "other-pod")); + .thenReturn(createSingleEndpointListWithNamespace("default", "other-pod", "api-pod", "other-pod")); mockServicesCall("api-pod", "default"); mockServicesCall("other-pod", "default"); @@ -317,7 +317,8 @@ void testEndpointsWithoutTargetRefsAllNamespaces() { private EndpointsList createEndpointsListByServiceName(String namespace, String... serviceNames) { List endpoints = stream(serviceNames) - .map(s -> createEndpointsByPodName(namespace, s + "-singlePodUniqueId")).collect(Collectors.toList()); + .map(s -> createEndpointsByPodName(namespace, s + "-singlePodUniqueId")) + .collect(Collectors.toList()); EndpointsList endpointsList = new EndpointsList(); endpointsList.setItems(endpoints); @@ -325,8 +326,11 @@ private EndpointsList createEndpointsListByServiceName(String namespace, String. } private EndpointsList createSingleEndpointEndpointListWithoutSubsets(String name, String namespace) { - Endpoints endpoints = new EndpointsBuilder().withNewMetadata().withName(name).withNamespace(namespace) - .endMetadata().build(); + Endpoints endpoints = new EndpointsBuilder().withNewMetadata() + .withName(name) + .withNamespace(namespace) + .endMetadata() + .build(); EndpointsList endpointsList = new EndpointsList(); endpointsList.setItems(Collections.singletonList(endpoints)); @@ -345,8 +349,11 @@ private EndpointsList createSingleEndpointEndpointListByPodName(String namespace private EndpointsList createSingleEndpointListWithNamespace(String namespace, String endpointsName, String... podNames) { - Endpoints endpoints = new EndpointsBuilder().withNewMetadata().withNamespace(namespace).withName(endpointsName) - .and().build(); + Endpoints endpoints = new EndpointsBuilder().withNewMetadata() + .withNamespace(namespace) + .withName(endpointsName) + .and() + .build(); endpoints.setSubsets(createSubsetsWithNamespace(namespace, podNames)); EndpointsList endpointsList = new EndpointsList(); @@ -432,14 +439,14 @@ private void createInSpecificNamespaceWatcher() { private void mockServicesCall(String name, String namespace) { MixedOperation> mixedOperation = Mockito - .mock(MixedOperation.class); + .mock(MixedOperation.class); NonNamespaceOperation> nonNamespaceOperation = Mockito - .mock(NonNamespaceOperation.class); + .mock(NonNamespaceOperation.class); when(CLIENT.services()).thenReturn(mixedOperation); when(mixedOperation.inNamespace(namespace)).thenReturn(nonNamespaceOperation); when(nonNamespaceOperation.list()).thenReturn(new ServiceListBuilder().withItems( new ServiceBuilder().withNewMetadata().withName(name).withNamespace(namespace).endMetadata().build()) - .build()); + .build()); } } diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientAutoConfigurationApplicationContextTests.java b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientAutoConfigurationApplicationContextTests.java index 9f144d84f4..d45f677d37 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientAutoConfigurationApplicationContextTests.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientAutoConfigurationApplicationContextTests.java @@ -162,18 +162,20 @@ void reactiveDisabled() { } private void setup(String... properties) { - applicationContextRunner = new ApplicationContextRunner().withConfiguration( - AutoConfigurations.of(KubernetesDiscoveryClientAutoConfiguration.class, Fabric8AutoConfiguration.class, - KubernetesCommonsAutoConfiguration.class, KubernetesDiscoveryPropertiesAutoConfiguration.class)) - .withPropertyValues(properties); + applicationContextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(KubernetesDiscoveryClientAutoConfiguration.class, + Fabric8AutoConfiguration.class, KubernetesCommonsAutoConfiguration.class, + KubernetesDiscoveryPropertiesAutoConfiguration.class)) + .withPropertyValues(properties); } private void setupWithFilteredClassLoader(Class cls, String... properties) { applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(KubernetesDiscoveryClientAutoConfiguration.class, - Fabric8AutoConfiguration.class, KubernetesCommonsAutoConfiguration.class, - KubernetesDiscoveryPropertiesAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(cls)).withPropertyValues(properties); + .withConfiguration(AutoConfigurations.of(KubernetesDiscoveryClientAutoConfiguration.class, + Fabric8AutoConfiguration.class, KubernetesCommonsAutoConfiguration.class, + KubernetesDiscoveryPropertiesAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(cls)) + .withPropertyValues(properties); } } diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientAutoConfigurationPropertiesTests.java b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientAutoConfigurationPropertiesTests.java index 8a252a3080..9a2299cf6b 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientAutoConfigurationPropertiesTests.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientAutoConfigurationPropertiesTests.java @@ -83,8 +83,9 @@ private void setup(String... env) { context = new SpringApplicationBuilder(PropertyPlaceholderAutoConfiguration.class, KubernetesClientTestConfiguration.class, KubernetesDiscoveryClientAutoConfiguration.class, KubernetesDiscoveryPropertiesAutoConfiguration.class) - .web(org.springframework.boot.WebApplicationType.NONE) - .properties(envList.toArray(new String[0])).run(); + .web(org.springframework.boot.WebApplicationType.NONE) + .properties(envList.toArray(new String[0])) + .run(); } @Configuration(proxyBeanMethods = false) diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientAutoConfigurationTests.java b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientAutoConfigurationTests.java index 09e6ad68d4..a538788316 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientAutoConfigurationTests.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientAutoConfigurationTests.java @@ -40,7 +40,7 @@ void kubernetesDiscoveryClientCreated() { CompositeDiscoveryClient composite = (CompositeDiscoveryClient) this.discoveryClient; assertThat(composite.getDiscoveryClients().stream().anyMatch(dc -> dc instanceof KubernetesDiscoveryClient)) - .isTrue(); + .isTrue(); } @SpringBootApplication diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientFilterMetadataTest.java b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientFilterMetadataTest.java index 0316847ce5..ad8d2c84b2 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientFilterMetadataTest.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientFilterMetadataTest.java @@ -64,18 +64,18 @@ class KubernetesDiscoveryClientFilterMetadataTest { private static final KubernetesClient CLIENT = Mockito.mock(KubernetesClient.class); private final MixedOperation> serviceOperation = Mockito - .mock(MixedOperation.class); + .mock(MixedOperation.class); private final MixedOperation> endpointsOperation = Mockito - .mock(MixedOperation.class); + .mock(MixedOperation.class); private final ServiceResource serviceResource = Mockito.mock(ServiceResource.class); private final FilterWatchListDeletable> filter = Mockito - .mock(FilterWatchListDeletable.class); + .mock(FilterWatchListDeletable.class); private final FilterNested>> filterNested = Mockito - .mock(FilterNested.class); + .mock(FilterNested.class); @Test void testAllExtraMetadataDisabled() { @@ -240,22 +240,37 @@ void testLabelsAndAnnotationsAndPortsEnabledWithPrefix() { private void setupServiceWithLabelsAndAnnotationsAndPorts(String serviceId, String namespace, Map labels, Map annotations, Map ports) { Service service = new ServiceBuilder() - .withSpec(new ServiceSpecBuilder().withType("ClusterIP").withPorts(getServicePorts(ports)).build()) - .withNewMetadata().withNamespace(namespace).withLabels(labels).withAnnotations(annotations) - .endMetadata().build(); + .withSpec(new ServiceSpecBuilder().withType("ClusterIP").withPorts(getServicePorts(ports)).build()) + .withNewMetadata() + .withNamespace(namespace) + .withLabels(labels) + .withAnnotations(annotations) + .endMetadata() + .build(); when(serviceOperation.withName(serviceId)).thenReturn(serviceResource); when(serviceResource.get()).thenReturn(service); when(CLIENT.services()).thenReturn(serviceOperation); when(CLIENT.services().inNamespace(anyString())).thenReturn(serviceOperation); - when(serviceOperation.list()).thenReturn(new ServiceListBuilder().withItems(new ServiceBuilder() - .withNewMetadata().withName(serviceId).withNamespace(namespace).endMetadata().build()).build()); + when(serviceOperation.list()).thenReturn( + new ServiceListBuilder() + .withItems(new ServiceBuilder().withNewMetadata() + .withName(serviceId) + .withNamespace(namespace) + .endMetadata() + .build()) + .build()); ObjectMeta objectMeta = new ObjectMeta(); objectMeta.setNamespace(namespace); objectMeta.setName(serviceId); - Endpoints endpoints = new EndpointsBuilder().withMetadata(objectMeta).addNewSubset() - .addAllToPorts(getEndpointPorts(ports)).addNewAddress().endAddress().endSubset().build(); + Endpoints endpoints = new EndpointsBuilder().withMetadata(objectMeta) + .addNewSubset() + .addAllToPorts(getEndpointPorts(ports)) + .addNewAddress() + .endAddress() + .endSubset() + .build(); when(CLIENT.endpoints()).thenReturn(endpointsOperation); when(endpointsOperation.inNamespace(Mockito.anyString())).thenReturn(endpointsOperation); diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientFilterTest.java b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientFilterTest.java index 6399457f21..a004aabdb0 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientFilterTest.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientFilterTest.java @@ -43,7 +43,7 @@ class KubernetesDiscoveryClientFilterTest { private final KubernetesClientServicesFunction kubernetesClientServicesFunction = KubernetesClient::services; private final MixedOperation> serviceOperation = Mockito - .mock(MixedOperation.class); + .mock(MixedOperation.class); @Test void testFilteredServices() { diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientUtilsTests.java b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientUtilsTests.java index f7abe74f7c..b84acb9b67 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientUtilsTests.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientUtilsTests.java @@ -62,9 +62,9 @@ void testReadyAddressesOnly() { KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, true, Set.of(), true, 60L, includeNotReadyAddresses, "", Set.of(), Map.of(), "", null, 0, false); EndpointSubset endpointSubset = new EndpointSubsetBuilder() - .withAddresses(new EndpointAddressBuilder().withHostname("one").build(), - new EndpointAddressBuilder().withHostname("two").build()) - .build(); + .withAddresses(new EndpointAddressBuilder().withHostname("one").build(), + new EndpointAddressBuilder().withHostname("two").build()) + .build(); List addresses = Fabric8KubernetesDiscoveryClientUtils.addresses(endpointSubset, properties); Assertions.assertEquals(addresses.size(), 2); } @@ -81,9 +81,10 @@ void testReadyAddressesTakenNotReadyAddressesNotTaken() { KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, true, Set.of(), true, 60L, includeNotReadyAddresses, "", Set.of(), Map.of(), "", null, 0, false, false); EndpointSubset endpointSubset = new EndpointSubsetBuilder() - .withAddresses(new EndpointAddressBuilder().withHostname("one").build(), - new EndpointAddressBuilder().withHostname("two").build()) - .withNotReadyAddresses(new EndpointAddressBuilder().withHostname("three").build()).build(); + .withAddresses(new EndpointAddressBuilder().withHostname("one").build(), + new EndpointAddressBuilder().withHostname("two").build()) + .withNotReadyAddresses(new EndpointAddressBuilder().withHostname("three").build()) + .build(); List addresses = Fabric8KubernetesDiscoveryClientUtils.addresses(endpointSubset, properties); Assertions.assertEquals(addresses.size(), 2); List hostNames = addresses.stream().map(EndpointAddress::getHostname).sorted().toList(); @@ -102,9 +103,10 @@ void testBothAddressesTaken() { KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, true, Set.of(), true, 60L, includeNotReadyAddresses, "", Set.of(), Map.of(), "", null, 0, false); EndpointSubset endpointSubset = new EndpointSubsetBuilder() - .withAddresses(new EndpointAddressBuilder().withHostname("one").build(), - new EndpointAddressBuilder().withHostname("two").build()) - .withNotReadyAddresses(new EndpointAddressBuilder().withHostname("three").build()).build(); + .withAddresses(new EndpointAddressBuilder().withHostname("one").build(), + new EndpointAddressBuilder().withHostname("two").build()) + .withNotReadyAddresses(new EndpointAddressBuilder().withHostname("three").build()) + .build(); List addresses = Fabric8KubernetesDiscoveryClientUtils.addresses(endpointSubset, properties); Assertions.assertEquals(addresses.size(), 3); List hostNames = addresses.stream().map(EndpointAddress::getHostname).sorted().toList(); diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/reactive/KubernetesReactiveDiscoveryClientAutoConfigurationApplicationContextTests.java b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/reactive/KubernetesReactiveDiscoveryClientAutoConfigurationApplicationContextTests.java index a0e156b957..a4a36d6e72 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/reactive/KubernetesReactiveDiscoveryClientAutoConfigurationApplicationContextTests.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/reactive/KubernetesReactiveDiscoveryClientAutoConfigurationApplicationContextTests.java @@ -156,20 +156,21 @@ void healthEnabledClassNotPresent() { private void setup(String... properties) { applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(UtilAutoConfiguration.class, - ReactiveCommonsClientAutoConfiguration.class, KubernetesCommonsAutoConfiguration.class, - Fabric8AutoConfiguration.class, KubernetesReactiveDiscoveryClientAutoConfiguration.class, - KubernetesDiscoveryPropertiesAutoConfiguration.class)) - .withPropertyValues(properties); + .withConfiguration(AutoConfigurations.of(UtilAutoConfiguration.class, + ReactiveCommonsClientAutoConfiguration.class, KubernetesCommonsAutoConfiguration.class, + Fabric8AutoConfiguration.class, KubernetesReactiveDiscoveryClientAutoConfiguration.class, + KubernetesDiscoveryPropertiesAutoConfiguration.class)) + .withPropertyValues(properties); } private void setupWithFilteredClassLoader(String name, String... properties) { applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(UtilAutoConfiguration.class, - ReactiveCommonsClientAutoConfiguration.class, KubernetesCommonsAutoConfiguration.class, - Fabric8AutoConfiguration.class, KubernetesReactiveDiscoveryClientAutoConfiguration.class, - KubernetesDiscoveryPropertiesAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(name)).withPropertyValues(properties); + .withConfiguration(AutoConfigurations.of(UtilAutoConfiguration.class, + ReactiveCommonsClientAutoConfiguration.class, KubernetesCommonsAutoConfiguration.class, + Fabric8AutoConfiguration.class, KubernetesReactiveDiscoveryClientAutoConfiguration.class, + KubernetesDiscoveryPropertiesAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(name)) + .withPropertyValues(properties); } } diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/reactive/KubernetesReactiveDiscoveryClientAutoConfigurationTests.java b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/reactive/KubernetesReactiveDiscoveryClientAutoConfigurationTests.java index bc27268398..fd18eb7845 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/reactive/KubernetesReactiveDiscoveryClientAutoConfigurationTests.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/reactive/KubernetesReactiveDiscoveryClientAutoConfigurationTests.java @@ -38,11 +38,11 @@ class KubernetesReactiveDiscoveryClientAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(UtilAutoConfiguration.class, - ReactiveCommonsClientAutoConfiguration.class, KubernetesCommonsAutoConfiguration.class, - Fabric8AutoConfiguration.class, KubernetesDiscoveryClientAutoConfiguration.class, - KubernetesReactiveDiscoveryClientAutoConfiguration.class, - KubernetesDiscoveryPropertiesAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(UtilAutoConfiguration.class, + ReactiveCommonsClientAutoConfiguration.class, KubernetesCommonsAutoConfiguration.class, + Fabric8AutoConfiguration.class, KubernetesDiscoveryClientAutoConfiguration.class, + KubernetesReactiveDiscoveryClientAutoConfiguration.class, + KubernetesDiscoveryPropertiesAutoConfiguration.class)); @Test void shouldWorkWithDefaults() { @@ -99,10 +99,11 @@ void worksWithoutWebflux() { @Test void worksWithoutActuator() { contextRunner.withPropertyValues("spring.main.cloud-platform=KUBERNETES") - .withClassLoader(new FilteredClassLoader("org.springframework.boot.actuate")).run(context -> { - assertThat(context).hasSingleBean(ReactiveDiscoveryClient.class); - assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class); - }); + .withClassLoader(new FilteredClassLoader("org.springframework.boot.actuate")) + .run(context -> { + assertThat(context).hasSingleBean(ReactiveDiscoveryClient.class); + assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class); + }); } } diff --git a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/reactive/KubernetesReactiveDiscoveryClientTests.java b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/reactive/KubernetesReactiveDiscoveryClientTests.java index 75fee4c5e0..f2241b1e47 100644 --- a/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/reactive/KubernetesReactiveDiscoveryClientTests.java +++ b/spring-cloud-kubernetes-fabric8-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/discovery/reactive/KubernetesReactiveDiscoveryClientTests.java @@ -82,12 +82,29 @@ void verifyDefaults() { @Test void shouldReturnFluxOfServices() { - kubernetesServer.expect().get().withPath("/api/v1/namespaces/test/services") - .andReturn(200, new ServiceListBuilder().addNewItem().withNewMetadata().withName("s1") - .withLabels(Map.of("label", "value")).endMetadata().endItem().addNewItem().withNewMetadata() - .withName("s2").withLabels(Map.of("label", "value", "label2", "value2")).endMetadata().endItem() - .addNewItem().withNewMetadata().withName("s3").endMetadata().endItem().build()) - .once(); + kubernetesServer.expect() + .get() + .withPath("/api/v1/namespaces/test/services") + .andReturn(200, + new ServiceListBuilder().addNewItem() + .withNewMetadata() + .withName("s1") + .withLabels(Map.of("label", "value")) + .endMetadata() + .endItem() + .addNewItem() + .withNewMetadata() + .withName("s2") + .withLabels(Map.of("label", "value", "label2", "value2")) + .endMetadata() + .endItem() + .addNewItem() + .withNewMetadata() + .withName("s3") + .endMetadata() + .endItem() + .build()) + .once(); ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient, KubernetesDiscoveryProperties.DEFAULT, KubernetesClient::services); Flux services = client.getServices(); @@ -96,8 +113,11 @@ void shouldReturnFluxOfServices() { @Test void shouldReturnEmptyFluxOfServicesWhenNoInstancesFound() { - kubernetesServer.expect().get().withPath("/api/v1/namespaces/test/services") - .andReturn(200, new ServiceListBuilder().build()).once(); + kubernetesServer.expect() + .get() + .withPath("/api/v1/namespaces/test/services") + .andReturn(200, new ServiceListBuilder().build()) + .once(); ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient, KubernetesDiscoveryProperties.DEFAULT, KubernetesClient::services); @@ -107,9 +127,11 @@ void shouldReturnEmptyFluxOfServicesWhenNoInstancesFound() { @Test void shouldReturnEmptyFluxForNonExistingService() { - kubernetesServer.expect().get() - .withPath("/api/v1/namespaces/test/endpoints?fieldSelector=metadata.name%3Dnonexistent-service") - .andReturn(200, new EndpointsBuilder().build()).once(); + kubernetesServer.expect() + .get() + .withPath("/api/v1/namespaces/test/endpoints?fieldSelector=metadata.name%3Dnonexistent-service") + .andReturn(200, new EndpointsBuilder().build()) + .once(); ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient, KubernetesDiscoveryProperties.DEFAULT, KubernetesClient::services); @@ -119,14 +141,24 @@ void shouldReturnEmptyFluxForNonExistingService() { @Test void shouldReturnEmptyFluxWhenServiceHasNoSubsets() { - kubernetesServer.expect().get().withPath("/api/v1/namespaces/test/services") - .andReturn(200, new ServiceListBuilder().addNewItem().withNewMetadata().withName("existing-service") - .withLabels(Map.of("label", "value")).endMetadata().endItem().build()) - .once(); - - kubernetesServer.expect().get() - .withPath("/api/v1/namespaces/test/endpoints?fieldSelector=metadata.name%3Dexisting-service") - .andReturn(200, new EndpointsBuilder().build()).once(); + kubernetesServer.expect() + .get() + .withPath("/api/v1/namespaces/test/services") + .andReturn(200, + new ServiceListBuilder().addNewItem() + .withNewMetadata() + .withName("existing-service") + .withLabels(Map.of("label", "value")) + .endMetadata() + .endItem() + .build()) + .once(); + + kubernetesServer.expect() + .get() + .withPath("/api/v1/namespaces/test/endpoints?fieldSelector=metadata.name%3Dexisting-service") + .andReturn(200, new EndpointsBuilder().build()) + .once(); ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient, KubernetesDiscoveryProperties.DEFAULT, KubernetesClient::services); @@ -136,14 +168,31 @@ void shouldReturnEmptyFluxWhenServiceHasNoSubsets() { @Test void shouldReturnFlux() { - ServiceList services = new ServiceListBuilder().addNewItem().withNewMetadata().withName("existing-service") - .withNamespace("test").withLabels(Map.of("label", "value")).endMetadata() - .withSpec(new ServiceSpecBuilder().withType("ExternalName").build()).endItem().build(); - - Endpoints endPoint = new EndpointsBuilder().withNewMetadata().withName("existing-service").withNamespace("test") - .withLabels(Map.of("label", "value")).endMetadata().addNewSubset().addNewAddress().withIp("ip1") - .withNewTargetRef().withUid("uid1").endTargetRef().endAddress() - .addNewPort("http", "http_tcp", 80, "TCP").endSubset().build(); + ServiceList services = new ServiceListBuilder().addNewItem() + .withNewMetadata() + .withName("existing-service") + .withNamespace("test") + .withLabels(Map.of("label", "value")) + .endMetadata() + .withSpec(new ServiceSpecBuilder().withType("ExternalName").build()) + .endItem() + .build(); + + Endpoints endPoint = new EndpointsBuilder().withNewMetadata() + .withName("existing-service") + .withNamespace("test") + .withLabels(Map.of("label", "value")) + .endMetadata() + .addNewSubset() + .addNewAddress() + .withIp("ip1") + .withNewTargetRef() + .withUid("uid1") + .endTargetRef() + .endAddress() + .addNewPort("http", "http_tcp", 80, "TCP") + .endSubset() + .build(); List endpointsList = new ArrayList<>(); endpointsList.add(endPoint); @@ -151,12 +200,17 @@ void shouldReturnFlux() { EndpointsList endpoints = new EndpointsList(); endpoints.setItems(endpointsList); - kubernetesServer.expect().get() - .withPath("/api/v1/namespaces/test/endpoints?fieldSelector=metadata.name%3Dexisting-service") - .andReturn(200, endpoints).once(); + kubernetesServer.expect() + .get() + .withPath("/api/v1/namespaces/test/endpoints?fieldSelector=metadata.name%3Dexisting-service") + .andReturn(200, endpoints) + .once(); - kubernetesServer.expect().get().withPath("/api/v1/namespaces/test/services/existing-service") - .andReturn(200, services.getItems().get(0)).once(); + kubernetesServer.expect() + .get() + .withPath("/api/v1/namespaces/test/services/existing-service") + .andReturn(200, services.getItems().get(0)) + .once(); kubernetesServer.expect().get().withPath("/api/v1/namespaces/test/services").andReturn(200, services).once(); @@ -168,16 +222,34 @@ void shouldReturnFlux() { @Test void shouldReturnFluxWithPrefixedMetadata() { - kubernetesServer.expect().get().withPath("/api/v1/namespaces/test/services") - .andReturn(200, - new ServiceListBuilder().addNewItem().withNewMetadata().withName("existing-service") - .withLabels(Map.of("label", "value")).endMetadata() - .withSpec(new ServiceSpecBuilder().withType("ExternalName").build()).endItem().build()) - .once(); - - Endpoints endPoint = new EndpointsBuilder().withNewMetadata().withName("existing-service").withNamespace("test") - .endMetadata().addNewSubset().addNewAddress().withIp("ip1").withNewTargetRef().withUid("uid1") - .endTargetRef().endAddress().addNewPort("http", "http_tcp", 80, "TCP").endSubset().build(); + kubernetesServer.expect() + .get() + .withPath("/api/v1/namespaces/test/services") + .andReturn(200, + new ServiceListBuilder().addNewItem() + .withNewMetadata() + .withName("existing-service") + .withLabels(Map.of("label", "value")) + .endMetadata() + .withSpec(new ServiceSpecBuilder().withType("ExternalName").build()) + .endItem() + .build()) + .once(); + + Endpoints endPoint = new EndpointsBuilder().withNewMetadata() + .withName("existing-service") + .withNamespace("test") + .endMetadata() + .addNewSubset() + .addNewAddress() + .withIp("ip1") + .withNewTargetRef() + .withUid("uid1") + .endTargetRef() + .endAddress() + .addNewPort("http", "http_tcp", 80, "TCP") + .endSubset() + .build(); List endpointsList = new ArrayList<>(); endpointsList.add(endPoint); @@ -185,14 +257,23 @@ void shouldReturnFluxWithPrefixedMetadata() { EndpointsList endpoints = new EndpointsList(); endpoints.setItems(endpointsList); - kubernetesServer.expect().get() - .withPath("/api/v1/namespaces/test/endpoints?fieldSelector=metadata.name%3Dexisting-service") - .andReturn(200, endpoints).once(); - - kubernetesServer.expect().get().withPath("/api/v1/namespaces/test/services/existing-service").andReturn(200, - new ServiceBuilder().withNewMetadata().withName("existing-service").withLabels(Map.of("label", "value")) - .endMetadata().withSpec(new ServiceSpecBuilder().withType("ExternalName").build()).build()) - .once(); + kubernetesServer.expect() + .get() + .withPath("/api/v1/namespaces/test/endpoints?fieldSelector=metadata.name%3Dexisting-service") + .andReturn(200, endpoints) + .once(); + + kubernetesServer.expect() + .get() + .withPath("/api/v1/namespaces/test/services/existing-service") + .andReturn(200, + new ServiceBuilder().withNewMetadata() + .withName("existing-service") + .withLabels(Map.of("label", "value")) + .endMetadata() + .withSpec(new ServiceSpecBuilder().withType("ExternalName").build()) + .build()) + .once(); ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient, KubernetesDiscoveryProperties.DEFAULT, KubernetesClient::services); @@ -202,17 +283,35 @@ void shouldReturnFluxWithPrefixedMetadata() { @Test void shouldReturnFluxWhenServiceHasMultiplePortsAndPrimaryPortNameIsSet() { - kubernetesServer.expect().get().withPath("/api/v1/namespaces/test/services") - .andReturn(200, - new ServiceListBuilder().addNewItem().withNewMetadata().withName("existing-service") - .withLabels(Map.of("label", "value")).endMetadata() - .withSpec(new ServiceSpecBuilder().withType("ExternalName").build()).endItem().build()) - .once(); - - Endpoints endPoint = new EndpointsBuilder().withNewMetadata().withName("existing-service").withNamespace("test") - .endMetadata().addNewSubset().addNewAddress().withIp("ip1").withNewTargetRef().withUid("uid1") - .endTargetRef().endAddress().addNewPort("http", "http_tcp", 80, "TCP") - .addNewPort("https", "https_tcp", 443, "TCP").endSubset().build(); + kubernetesServer.expect() + .get() + .withPath("/api/v1/namespaces/test/services") + .andReturn(200, + new ServiceListBuilder().addNewItem() + .withNewMetadata() + .withName("existing-service") + .withLabels(Map.of("label", "value")) + .endMetadata() + .withSpec(new ServiceSpecBuilder().withType("ExternalName").build()) + .endItem() + .build()) + .once(); + + Endpoints endPoint = new EndpointsBuilder().withNewMetadata() + .withName("existing-service") + .withNamespace("test") + .endMetadata() + .addNewSubset() + .addNewAddress() + .withIp("ip1") + .withNewTargetRef() + .withUid("uid1") + .endTargetRef() + .endAddress() + .addNewPort("http", "http_tcp", 80, "TCP") + .addNewPort("https", "https_tcp", 443, "TCP") + .endSubset() + .build(); List endpointsList = new ArrayList<>(); endpointsList.add(endPoint); @@ -220,14 +319,23 @@ void shouldReturnFluxWhenServiceHasMultiplePortsAndPrimaryPortNameIsSet() { EndpointsList endpoints = new EndpointsList(); endpoints.setItems(endpointsList); - kubernetesServer.expect().get() - .withPath("/api/v1/namespaces/test/endpoints?fieldSelector=metadata.name%3Dexisting-service") - .andReturn(200, endpoints).once(); - - kubernetesServer.expect().get().withPath("/api/v1/namespaces/test/services/existing-service").andReturn(200, - new ServiceBuilder().withNewMetadata().withName("existing-service").withLabels(Map.of("label", "value")) - .endMetadata().withSpec(new ServiceSpecBuilder().withType("ExternalName").build()).build()) - .once(); + kubernetesServer.expect() + .get() + .withPath("/api/v1/namespaces/test/endpoints?fieldSelector=metadata.name%3Dexisting-service") + .andReturn(200, endpoints) + .once(); + + kubernetesServer.expect() + .get() + .withPath("/api/v1/namespaces/test/services/existing-service") + .andReturn(200, + new ServiceBuilder().withNewMetadata() + .withName("existing-service") + .withLabels(Map.of("label", "value")) + .endMetadata() + .withSpec(new ServiceSpecBuilder().withType("ExternalName").build()) + .build()) + .once(); ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient, KubernetesDiscoveryProperties.DEFAULT, KubernetesClient::services); @@ -237,28 +345,56 @@ void shouldReturnFluxWhenServiceHasMultiplePortsAndPrimaryPortNameIsSet() { @Test void shouldReturnFluxOfServicesAcrossAllNamespaces() { - kubernetesServer.expect().get().withPath("/api/v1/namespaces/test/services") - .andReturn(200, - new ServiceListBuilder().addNewItem().withNewMetadata().withName("existing-service") - .withLabels(Map.of("label", "value")).endMetadata() - .withSpec(new ServiceSpecBuilder().withType("ExternalName").build()).endItem().build()) - .once(); - - Endpoints endpoints = new EndpointsBuilder().withNewMetadata().withName("existing-service") - .withNamespace("test").endMetadata().addNewSubset().addNewAddress().withIp("ip1").withNewTargetRef() - .withUid("uid1").endTargetRef().endAddress().addNewPort("http", "http_tcp", 80, "TCP") - .addNewPort("https", "https_tcp", 443, "TCP").endSubset().build(); + kubernetesServer.expect() + .get() + .withPath("/api/v1/namespaces/test/services") + .andReturn(200, + new ServiceListBuilder().addNewItem() + .withNewMetadata() + .withName("existing-service") + .withLabels(Map.of("label", "value")) + .endMetadata() + .withSpec(new ServiceSpecBuilder().withType("ExternalName").build()) + .endItem() + .build()) + .once(); + + Endpoints endpoints = new EndpointsBuilder().withNewMetadata() + .withName("existing-service") + .withNamespace("test") + .endMetadata() + .addNewSubset() + .addNewAddress() + .withIp("ip1") + .withNewTargetRef() + .withUid("uid1") + .endTargetRef() + .endAddress() + .addNewPort("http", "http_tcp", 80, "TCP") + .addNewPort("https", "https_tcp", 443, "TCP") + .endSubset() + .build(); EndpointsList endpointsList = new EndpointsList(); endpointsList.setItems(singletonList(endpoints)); - kubernetesServer.expect().get().withPath("/api/v1/endpoints?fieldSelector=metadata.name%3Dexisting-service") - .andReturn(200, endpointsList).once(); - - kubernetesServer.expect().get().withPath("/api/v1/namespaces/test/services/existing-service").andReturn(200, - new ServiceBuilder().withNewMetadata().withName("existing-service").withLabels(Map.of("label", "value")) - .endMetadata().withSpec(new ServiceSpecBuilder().withType("ExternalName").build()).build()) - .once(); + kubernetesServer.expect() + .get() + .withPath("/api/v1/endpoints?fieldSelector=metadata.name%3Dexisting-service") + .andReturn(200, endpointsList) + .once(); + + kubernetesServer.expect() + .get() + .withPath("/api/v1/namespaces/test/services/existing-service") + .andReturn(200, + new ServiceBuilder().withNewMetadata() + .withName("existing-service") + .withLabels(Map.of("label", "value")) + .endMetadata() + .withSpec(new ServiceSpecBuilder().withType("ExternalName").build()) + .build()) + .once(); KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, true, Set.of(), true, 60, false, null, Set.of(), Map.of(), "https_tcp", Metadata.DEFAULT, 0, true); diff --git a/spring-cloud-kubernetes-fabric8-istio/src/main/java/org/springframework/cloud/kubernetes/fabric8/client/istio/utils/MeshUtils.java b/spring-cloud-kubernetes-fabric8-istio/src/main/java/org/springframework/cloud/kubernetes/fabric8/client/istio/utils/MeshUtils.java index 39090ece43..74cd375c20 100644 --- a/spring-cloud-kubernetes-fabric8-istio/src/main/java/org/springframework/cloud/kubernetes/fabric8/client/istio/utils/MeshUtils.java +++ b/spring-cloud-kubernetes-fabric8-istio/src/main/java/org/springframework/cloud/kubernetes/fabric8/client/istio/utils/MeshUtils.java @@ -52,7 +52,7 @@ private synchronized boolean checkIstioServices() { // TODO: We can improve this initial detection if better methods are found. String resource = "http://localhost:" + this.istioClientProperties.getEnvoyPort(); ResponseEntity response = this.restTemplate - .getForEntity(resource + "/" + this.istioClientProperties.getTestPath(), String.class); + .getForEntity(resource + "/" + this.istioClientProperties.getTestPath(), String.class); if (response.getStatusCode().is2xxSuccessful()) { LOG.info("Istio Resources Found."); return true; diff --git a/spring-cloud-kubernetes-fabric8-leader/src/main/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeaderRecordWatcher.java b/spring-cloud-kubernetes-fabric8-leader/src/main/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeaderRecordWatcher.java index c65fea0608..32b8093d4a 100644 --- a/spring-cloud-kubernetes-fabric8-leader/src/main/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeaderRecordWatcher.java +++ b/spring-cloud-kubernetes-fabric8-leader/src/main/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeaderRecordWatcher.java @@ -60,8 +60,9 @@ public void start() { if (configMapWatch == null) { LOGGER.debug(() -> "Starting leader record watcher"); configMapWatch = kubernetesClient.configMaps() - .inNamespace(leaderProperties.getNamespace(kubernetesClient.getNamespace())) - .withName(leaderProperties.getConfigMapName()).watch(this); + .inNamespace(leaderProperties.getNamespace(kubernetesClient.getNamespace())) + .withName(leaderProperties.getConfigMapName()) + .watch(this); } }); } diff --git a/spring-cloud-kubernetes-fabric8-leader/src/main/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeadershipController.java b/spring-cloud-kubernetes-fabric8-leader/src/main/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeadershipController.java index f6aadc4706..b2c9d037aa 100644 --- a/spring-cloud-kubernetes-fabric8-leader/src/main/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeadershipController.java +++ b/spring-cloud-kubernetes-fabric8-leader/src/main/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeadershipController.java @@ -149,18 +149,27 @@ private boolean isPodReady(String name) { } private ConfigMap getConfigMap() { - return kubernetesClient.configMaps().inNamespace(leaderProperties.getNamespace(kubernetesClient.getNamespace())) - .withName(leaderProperties.getConfigMapName()).get(); + return kubernetesClient.configMaps() + .inNamespace(leaderProperties.getNamespace(kubernetesClient.getNamespace())) + .withName(leaderProperties.getConfigMapName()) + .get(); } private void createConfigMap(Map data) { LOGGER.debug(() -> "Creating new config map with data: " + data); - ConfigMap newConfigMap = new ConfigMapBuilder().withNewMetadata().withName(leaderProperties.getConfigMapName()) - .addToLabels(PROVIDER_KEY, PROVIDER).addToLabels(KIND_KEY, KIND).endMetadata().addToData(data).build(); - - kubernetesClient.configMaps().inNamespace(leaderProperties.getNamespace(kubernetesClient.getNamespace())) - .resource(newConfigMap).create(); + ConfigMap newConfigMap = new ConfigMapBuilder().withNewMetadata() + .withName(leaderProperties.getConfigMapName()) + .addToLabels(PROVIDER_KEY, PROVIDER) + .addToLabels(KIND_KEY, KIND) + .endMetadata() + .addToData(data) + .build(); + + kubernetesClient.configMaps() + .inNamespace(leaderProperties.getNamespace(kubernetesClient.getNamespace())) + .resource(newConfigMap) + .create(); } private void updateConfigMapEntry(ConfigMap configMap, Map newData) { @@ -177,8 +186,11 @@ private void removeConfigMapEntry(ConfigMap configMap, String key) { private void updateConfigMap(ConfigMap oldConfigMap, ConfigMap newConfigMap) { String oldResourceVersion = oldConfigMap.getMetadata().getResourceVersion(); - kubernetesClient.configMaps().inNamespace(leaderProperties.getNamespace(kubernetesClient.getNamespace())) - .resource(newConfigMap).lockResourceVersion(oldResourceVersion).update(); + kubernetesClient.configMaps() + .inNamespace(leaderProperties.getNamespace(kubernetesClient.getNamespace())) + .resource(newConfigMap) + .lockResourceVersion(oldResourceVersion) + .update(); } } diff --git a/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeaderAutoConfigurationTests.java b/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeaderAutoConfigurationTests.java index 6ee975b483..c55dfd57cd 100644 --- a/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeaderAutoConfigurationTests.java +++ b/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeaderAutoConfigurationTests.java @@ -46,8 +46,14 @@ void contextLoads() { @Test void infoEndpointShouldContainLeaderElection() { - webClient.get().uri("http://localhost:{port}/actuator/info", port).accept(MediaType.APPLICATION_JSON).exchange() - .expectStatus().isOk().expectBody(String.class).value(containsString("kubernetes")); + webClient.get() + .uri("http://localhost:{port}/actuator/info", port) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .value(containsString("kubernetes")); } @SpringBootConfiguration diff --git a/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeaderRecordWatcherTest.java b/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeaderRecordWatcherTest.java index 704361817c..9549a07e22 100644 --- a/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeaderRecordWatcherTest.java +++ b/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeaderRecordWatcherTest.java @@ -42,17 +42,17 @@ class Fabric8LeaderRecordWatcherTest { private final LeaderProperties mockLeaderProperties = Mockito.mock(LeaderProperties.class); private final Fabric8LeadershipController mockFabric8LeadershipController = Mockito - .mock(Fabric8LeadershipController.class); + .mock(Fabric8LeadershipController.class); private final KubernetesClient mockKubernetesClient = Mockito.mock(KubernetesClient.class); @SuppressWarnings("unchecked") private final MixedOperation> mockConfigMapsOperation = Mockito - .mock(MixedOperation.class); + .mock(MixedOperation.class); @SuppressWarnings("unchecked") private final NonNamespaceOperation> mockInNamespaceOperation = Mockito - .mock(NonNamespaceOperation.class); + .mock(NonNamespaceOperation.class); @SuppressWarnings("unchecked") private final Resource mockWithNameResource = Mockito.mock(Resource.class); diff --git a/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeadershipControllerTest.java b/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeadershipControllerTest.java index 424e789a12..7eacb0be0e 100644 --- a/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeadershipControllerTest.java +++ b/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeadershipControllerTest.java @@ -76,7 +76,7 @@ void whenNonExistentConfigmapAndCreationNotAllowedStopLeadershipAcquire(Captured Resource mockResource = Mockito.mock(Resource.class); @SuppressWarnings("unchecked") NonNamespaceOperation> mockNonNamespaceOperation = Mockito - .mock(NonNamespaceOperation.class); + .mock(NonNamespaceOperation.class); Fabric8LeadershipController fabric8LeadershipController = new Fabric8LeadershipController(mockCandidate, mockLeaderProperties, mockLeaderEventPublisher, mockKubernetesClient); diff --git a/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8PodReadinessWatcherTest.java b/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8PodReadinessWatcherTest.java index bd58f353b0..7d4eb71f21 100644 --- a/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8PodReadinessWatcherTest.java +++ b/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8PodReadinessWatcherTest.java @@ -40,7 +40,7 @@ public class Fabric8PodReadinessWatcherTest { private static final String POD_NAME = "test-pod"; private final Fabric8LeadershipController mockFabric8LeadershipController = Mockito - .mock(Fabric8LeadershipController.class); + .mock(Fabric8LeadershipController.class); private final KubernetesClient mockKubernetesClient = Mockito.mock(KubernetesClient.class); diff --git a/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/LeaderContextTest.java b/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/LeaderContextTest.java index f0804c1f5a..ab4097efa4 100644 --- a/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/LeaderContextTest.java +++ b/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/LeaderContextTest.java @@ -37,7 +37,7 @@ public class LeaderContextTest { private final Candidate mockCandidate = Mockito.mock(Candidate.class); private final Fabric8LeadershipController mockFabric8LeadershipController = Mockito - .mock(Fabric8LeadershipController.class); + .mock(Fabric8LeadershipController.class); private final Leader mockLeader = Mockito.mock(Leader.class); diff --git a/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/LeaderInitiatorTest.java b/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/LeaderInitiatorTest.java index 7bca401472..b9d82935fe 100644 --- a/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/LeaderInitiatorTest.java +++ b/spring-cloud-kubernetes-fabric8-leader/src/test/java/org/springframework/cloud/kubernetes/fabric8/leader/LeaderInitiatorTest.java @@ -39,13 +39,13 @@ public class LeaderInitiatorTest { private final LeaderProperties leaderProperties = new LeaderProperties(); private final Fabric8LeadershipController mockFabric8LeadershipController = Mockito - .mock(Fabric8LeadershipController.class); + .mock(Fabric8LeadershipController.class); private final Fabric8LeaderRecordWatcher mockFabric8LeaderRecordWatcher = Mockito - .mock(Fabric8LeaderRecordWatcher.class); + .mock(Fabric8LeaderRecordWatcher.class); private final Fabric8PodReadinessWatcher mockFabric8PodReadinessWatcher = Mockito - .mock(Fabric8PodReadinessWatcher.class); + .mock(Fabric8PodReadinessWatcher.class); private final Runnable runnable = Mockito.mock(Runnable.class); diff --git a/spring-cloud-kubernetes-fabric8-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8LoadBalancerClientConfiguration.java b/spring-cloud-kubernetes-fabric8-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8LoadBalancerClientConfiguration.java index 09ca17f6e1..0dc43ec4d4 100644 --- a/spring-cloud-kubernetes-fabric8-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8LoadBalancerClientConfiguration.java +++ b/spring-cloud-kubernetes-fabric8-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8LoadBalancerClientConfiguration.java @@ -38,8 +38,9 @@ ServiceInstanceListSupplier kubernetesServicesListSupplier(Environment environme KubernetesClient kubernetesClient, Fabric8ServiceInstanceMapper mapper, KubernetesDiscoveryProperties discoveryProperties, ConfigurableApplicationContext context) { return ServiceInstanceListSupplier.builder() - .withBase(new Fabric8ServicesListSupplier(environment, kubernetesClient, mapper, discoveryProperties)) - .withCaching().build(context); + .withBase(new Fabric8ServicesListSupplier(environment, kubernetesClient, mapper, discoveryProperties)) + .withCaching() + .build(context); } } diff --git a/spring-cloud-kubernetes-fabric8-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8ServiceInstanceMapper.java b/spring-cloud-kubernetes-fabric8-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8ServiceInstanceMapper.java index 7cccfafcc8..07603a81ee 100644 --- a/spring-cloud-kubernetes-fabric8-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8ServiceInstanceMapper.java +++ b/spring-cloud-kubernetes-fabric8-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8ServiceInstanceMapper.java @@ -91,7 +91,8 @@ public KubernetesServiceInstance map(Service service) { String portNameFromProperties = properties.getPortName(); if (StringUtils.hasText(portNameFromProperties)) { Optional optionalPort = ports.stream() - .filter(x -> Objects.equals(x.getName(), portNameFromProperties)).findAny(); + .filter(x -> Objects.equals(x.getName(), portNameFromProperties)) + .findAny(); if (optionalPort.isPresent()) { LOG.debug(() -> "found port name that matches : " + portNameFromProperties); port = optionalPort.get(); diff --git a/spring-cloud-kubernetes-fabric8-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8ServicesListSupplier.java b/spring-cloud-kubernetes-fabric8-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8ServicesListSupplier.java index 74ce4b09a2..4daeb1377a 100644 --- a/spring-cloud-kubernetes-fabric8-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8ServicesListSupplier.java +++ b/spring-cloud-kubernetes-fabric8-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8ServicesListSupplier.java @@ -63,16 +63,21 @@ public Flux> get() { if (discoveryProperties.allNamespaces()) { LOG.debug(() -> "discovering services in all namespaces"); - List services = kubernetesClient.services().inAnyNamespace() - .withField("metadata.name", serviceName).list().getItems(); + List services = kubernetesClient.services() + .inAnyNamespace() + .withField("metadata.name", serviceName) + .list() + .getItems(); services.forEach(service -> addMappedService(mapper, result, service)); } else if (!discoveryProperties.namespaces().isEmpty()) { List selectiveNamespaces = discoveryProperties.namespaces().stream().sorted().toList(); LOG.debug(() -> "discovering services in selective namespaces : " + selectiveNamespaces); selectiveNamespaces.forEach(selectiveNamespace -> { - Service service = kubernetesClient.services().inNamespace(selectiveNamespace).withName(serviceName) - .get(); + Service service = kubernetesClient.services() + .inNamespace(selectiveNamespace) + .withName(serviceName) + .get(); if (service != null) { addMappedService(mapper, result, service); } diff --git a/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8LoadBalancerAutoConfigurationTests.java b/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8LoadBalancerAutoConfigurationTests.java index 0994bee637..e8b6d3ecbc 100644 --- a/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8LoadBalancerAutoConfigurationTests.java +++ b/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8LoadBalancerAutoConfigurationTests.java @@ -34,42 +34,43 @@ class Fabric8LoadBalancerAutoConfigurationTests { @Test void kubernetesLoadBalancerWhenKubernetesDisabledAndLoadBalancerDisabled() { new ApplicationContextRunner().withUserConfiguration(Fabric8LoadBalancerAutoConfigurationTests.Config.class) - .withConfiguration(AutoConfigurations.of(Fabric8LoadBalancerAutoConfiguration.class)) - .withPropertyValues("spring.cloud.kubernetes.loadbalancer.enabled=false") - .run(this::assertInstanceMapperMissing); + .withConfiguration(AutoConfigurations.of(Fabric8LoadBalancerAutoConfiguration.class)) + .withPropertyValues("spring.cloud.kubernetes.loadbalancer.enabled=false") + .run(this::assertInstanceMapperMissing); } @Test void kubernetesLoadBalancerWhenKubernetesDisabledAndLoadBalancerEnabled() { new ApplicationContextRunner().withUserConfiguration(Fabric8LoadBalancerAutoConfigurationTests.Config.class) - .withConfiguration(AutoConfigurations.of(Fabric8LoadBalancerAutoConfiguration.class)) - .withPropertyValues("spring.cloud.kubernetes.loadbalancer.enabled=true") - .run(this::assertInstanceMapperMissing); + .withConfiguration(AutoConfigurations.of(Fabric8LoadBalancerAutoConfiguration.class)) + .withPropertyValues("spring.cloud.kubernetes.loadbalancer.enabled=true") + .run(this::assertInstanceMapperMissing); } @Test void kubernetesLoadBalancerWhenKubernetesEnabledAndLoadBalancerEnabled() { new ApplicationContextRunner().withUserConfiguration(Fabric8LoadBalancerAutoConfigurationTests.Config.class) - .withConfiguration(AutoConfigurations.of(Fabric8LoadBalancerAutoConfiguration.class)) - .withPropertyValues("spring.cloud.kubernetes.loadbalancer.enabled=true", - "spring.main.cloud-platform=KUBERNETES") - .run(this::assertInstanceMapperPresent); + .withConfiguration(AutoConfigurations.of(Fabric8LoadBalancerAutoConfiguration.class)) + .withPropertyValues("spring.cloud.kubernetes.loadbalancer.enabled=true", + "spring.main.cloud-platform=KUBERNETES") + .run(this::assertInstanceMapperPresent); } @Test void kubernetesLoadBalancerWhenKubernetesEnabledAndLoadBalancerDisabled() { new ApplicationContextRunner().withUserConfiguration(Fabric8LoadBalancerAutoConfigurationTests.Config.class) - .withConfiguration(AutoConfigurations.of(Fabric8LoadBalancerAutoConfiguration.class)) - .withPropertyValues("spring.cloud.kubernetes.loadbalancer.enabled=false", - "spring.main.cloud-platform=KUBERNETES") - .run(this::assertInstanceMapperMissing); + .withConfiguration(AutoConfigurations.of(Fabric8LoadBalancerAutoConfiguration.class)) + .withPropertyValues("spring.cloud.kubernetes.loadbalancer.enabled=false", + "spring.main.cloud-platform=KUBERNETES") + .run(this::assertInstanceMapperMissing); } @Test void kubernetesLoadBalancerWhenDefaultProperties() { new ApplicationContextRunner().withUserConfiguration(Fabric8LoadBalancerAutoConfigurationTests.Config.class) - .withConfiguration(AutoConfigurations.of(Fabric8LoadBalancerAutoConfiguration.class)) - .withPropertyValues("spring.main.cloud-platform=KUBERNETES").run(this::assertInstanceMapperPresent); + .withConfiguration(AutoConfigurations.of(Fabric8LoadBalancerAutoConfiguration.class)) + .withPropertyValues("spring.main.cloud-platform=KUBERNETES") + .run(this::assertInstanceMapperPresent); } private void assertInstanceMapperMissing(AssertableApplicationContext context) { diff --git a/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8ServiceInstanceMapperTests.java b/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8ServiceInstanceMapperTests.java index 95c5725538..8bc9394126 100644 --- a/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8ServiceInstanceMapperTests.java +++ b/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8ServiceInstanceMapperTests.java @@ -44,7 +44,8 @@ void testMapperSimple() { KubernetesLoadBalancerProperties properties = new KubernetesLoadBalancerProperties(); Service service = buildService("test", "test-namespace", "abc", 8080, null, Map.of()); KubernetesServiceInstance instance = new Fabric8ServiceInstanceMapper(properties, - KubernetesDiscoveryProperties.DEFAULT).map(service); + KubernetesDiscoveryProperties.DEFAULT) + .map(service); Assertions.assertNotNull(instance); Assertions.assertEquals("test", instance.getServiceId()); Assertions.assertEquals("abc", instance.getInstanceId()); @@ -59,7 +60,8 @@ void testMapperMultiplePorts() { ports.add(new ServicePortBuilder().withPort(9000).withName("http").build()); Service service = buildService("test", "test-namespace", "abc", ports, Map.of()); KubernetesServiceInstance instance = new Fabric8ServiceInstanceMapper(properties, - KubernetesDiscoveryProperties.DEFAULT).map(service); + KubernetesDiscoveryProperties.DEFAULT) + .map(service); Assertions.assertNotNull(instance); Assertions.assertEquals("test", instance.getServiceId()); Assertions.assertEquals("abc", instance.getInstanceId()); @@ -76,7 +78,7 @@ void testMapperSecure() { KubernetesDiscoveryProperties.Metadata.DEFAULT, 0, false, false, null); KubernetesServiceInstance instance = new Fabric8ServiceInstanceMapper(properties, discoveryProperties) - .map(service); + .map(service); Assertions.assertNotNull(instance); Assertions.assertEquals("test", instance.getServiceId()); Assertions.assertEquals("abc", instance.getInstanceId()); @@ -93,7 +95,7 @@ void testMapperSecureNullLabelsAndAnnotations() { ports.add(new ServicePortBuilder().withPort(443).build()); Service service = buildService("test", "test-namespace", "abc", ports, null, null); KubernetesServiceInstance instance = new Fabric8ServiceInstanceMapper(properties, discoveryProperties) - .map(service); + .map(service); Assertions.assertNotNull(instance); Assertions.assertEquals("test", instance.getServiceId()); Assertions.assertEquals("abc", instance.getInstanceId()); @@ -106,7 +108,8 @@ void testMapperSecureWithLabels() { Map labels = Map.of("secured", "true", "label1", "123"); Service service = buildService("test", "test-namespace", "abc", 8080, null, labels); KubernetesServiceInstance instance = new Fabric8ServiceInstanceMapper(properties, - KubernetesDiscoveryProperties.DEFAULT).map(service); + KubernetesDiscoveryProperties.DEFAULT) + .map(service); Assertions.assertNotNull(instance); Assertions.assertEquals("test", instance.getServiceId()); Assertions.assertEquals("abc", instance.getInstanceId()); @@ -130,7 +133,7 @@ void serviceMetadataTest() { Service service = buildService("test", "test-namespace", "abc", ports, labels, annotations); Map result = new Fabric8ServiceInstanceMapper(loadBalancerProperties, discoveryProperties) - .serviceMetadata(service); + .serviceMetadata(service); Assertions.assertEquals(result.size(), 4); Assertions.assertEquals(result.get("k8s_namespace"), "test-namespace"); Assertions.assertEquals(result.get("type"), "ClusterIP"); @@ -153,11 +156,11 @@ void testMapEmptyPorts(CapturedOutput output) { List ports = List.of(); Service service = buildService("test", "test-namespace", "abc", ports, Map.of(), Map.of()); KubernetesServiceInstance result = new Fabric8ServiceInstanceMapper(loadBalancerProperties, discoveryProperties) - .map(service); + .map(service); Assertions.assertNull(result); Assertions.assertTrue(output.getOut() - .contains("service : test does not have any ServicePort(s), will not consider it for load balancing")); + .contains("service : test does not have any ServicePort(s), will not consider it for load balancing")); } @@ -178,11 +181,12 @@ void testSinglePortsMatchesProperty(CapturedOutput output) { List ports = List.of(new ServicePortBuilder().withPort(8080).withName("my-port-name").build()); Service service = buildService("test", "test-namespace", "abc", ports, Map.of(), Map.of()); KubernetesServiceInstance result = new Fabric8ServiceInstanceMapper(loadBalancerProperties, discoveryProperties) - .map(service); + .map(service); Assertions.assertNotNull(result); - Assertions.assertTrue(output.getOut().contains( - "single ServicePort found, will use it as-is (without checking 'spring.cloud.kubernetes.loadbalancer.portName')")); + Assertions.assertTrue(output.getOut() + .contains( + "single ServicePort found, will use it as-is (without checking 'spring.cloud.kubernetes.loadbalancer.portName')")); } @@ -206,11 +210,12 @@ void testSinglePortDoesNotMatchProperty(CapturedOutput output) { List ports = List.of(new ServicePortBuilder().withPort(8080).withName("my-port-name").build()); Service service = buildService("test", "test-namespace", "abc", ports, Map.of(), Map.of()); KubernetesServiceInstance result = new Fabric8ServiceInstanceMapper(loadBalancerProperties, discoveryProperties) - .map(service); + .map(service); Assertions.assertNotNull(result); - Assertions.assertTrue(output.getOut().contains( - "single ServicePort found, will use it as-is (without checking 'spring.cloud.kubernetes.loadbalancer.portName')")); + Assertions.assertTrue(output.getOut() + .contains( + "single ServicePort found, will use it as-is (without checking 'spring.cloud.kubernetes.loadbalancer.portName')")); } @@ -232,7 +237,7 @@ void testMultiplePortsWithoutPortNameProperty(CapturedOutput output) { new ServicePortBuilder().withPort(8081).withName("two").build()); Service service = buildService("test", "test-namespace", "abc", ports, Map.of(), Map.of()); KubernetesServiceInstance result = new Fabric8ServiceInstanceMapper(loadBalancerProperties, discoveryProperties) - .map(service); + .map(service); Assertions.assertNotNull(result); Assertions.assertTrue(output.getOut().contains("'spring.cloud.kubernetes.loadbalancer.portName' is not set")); @@ -257,7 +262,7 @@ void testMultiplePortsWithPortNamePropertyMatch(CapturedOutput output) { new ServicePortBuilder().withPort(8081).withName("two").build()); Service service = buildService("test", "test-namespace", "abc", ports, Map.of(), Map.of()); KubernetesServiceInstance result = new Fabric8ServiceInstanceMapper(loadBalancerProperties, discoveryProperties) - .map(service); + .map(service); Assertions.assertNotNull(result); Assertions.assertTrue(output.getOut().contains("found port name that matches : one")); @@ -282,7 +287,7 @@ void testMultiplePortsWithPortNamePropertyNoMatch(CapturedOutput output) { new ServicePortBuilder().withPort(8081).withName("two").build()); Service service = buildService("test", "test-namespace", "abc", ports, Map.of(), Map.of()); KubernetesServiceInstance result = new Fabric8ServiceInstanceMapper(loadBalancerProperties, discoveryProperties) - .map(service); + .map(service); Assertions.assertNotNull(result); Assertions.assertTrue(output.getOut().contains("Did not find a port name that is equal to the value three")); @@ -298,9 +303,18 @@ private Service buildService(String name, String namespace, String uid, int port private Service buildService(String name, String namespace, String uid, List ports, Map labels, Map annotations) { - return new ServiceBuilder().withNewMetadata().withNamespace(namespace).withName(name).withUid(uid) - .addToLabels(labels).withAnnotations(annotations).endMetadata().withNewSpec().addAllToPorts(ports) - .withType("ClusterIP").endSpec().build(); + return new ServiceBuilder().withNewMetadata() + .withNamespace(namespace) + .withName(name) + .withUid(uid) + .addToLabels(labels) + .withAnnotations(annotations) + .endMetadata() + .withNewSpec() + .addAllToPorts(ports) + .withType("ClusterIP") + .endSpec() + .build(); } private Service buildService(String name, String namespace, String uid, List ports, diff --git a/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8ServiceListSupplierTests.java b/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8ServiceListSupplierTests.java index 2462417f12..5e12209d55 100644 --- a/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8ServiceListSupplierTests.java +++ b/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8ServiceListSupplierTests.java @@ -53,23 +53,23 @@ class Fabric8ServiceListSupplierTests { @SuppressWarnings("unchecked") private final MixedOperation> serviceOperation = Mockito - .mock(MixedOperation.class); + .mock(MixedOperation.class); @SuppressWarnings("unchecked") private final NonNamespaceOperation> namespaceOperation = Mockito - .mock(NonNamespaceOperation.class); + .mock(NonNamespaceOperation.class); @SuppressWarnings("unchecked") private final ServiceResource serviceResource = Mockito.mock(ServiceResource.class); @SuppressWarnings("unchecked") private final AnyNamespaceOperation> multiDeletable = Mockito - .mock(AnyNamespaceOperation.class); + .mock(AnyNamespaceOperation.class); @Test void testPositiveMatch() { when(mapper.map(any(Service.class))) - .thenReturn(new DefaultKubernetesServiceInstance("", "", "", 0, null, false)); + .thenReturn(new DefaultKubernetesServiceInstance("", "", "", 0, null, false)); when(this.client.getNamespace()).thenReturn("test"); when(this.client.services()).thenReturn(this.serviceOperation); when(this.serviceOperation.inNamespace("test")).thenReturn(namespaceOperation); @@ -84,7 +84,7 @@ void testPositiveMatch() { @Test void testPositiveMatchAllNamespaces() { when(mapper.map(any(Service.class))) - .thenReturn(new DefaultKubernetesServiceInstance("", "", "", 0, null, false)); + .thenReturn(new DefaultKubernetesServiceInstance("", "", "", 0, null, false)); when(this.client.services()).thenReturn(this.serviceOperation); when(this.serviceOperation.inAnyNamespace()).thenReturn(this.multiDeletable); when(this.multiDeletable.withField("metadata.name", "test-service")).thenReturn(this.multiDeletable); @@ -101,8 +101,15 @@ void testPositiveMatchAllNamespaces() { } private Service buildService(String name, int port) { - return new ServiceBuilder().withNewMetadata().withName(name).endMetadata().withNewSpec().addNewPort() - .withPort(port).endPort().endSpec().build(); + return new ServiceBuilder().withNewMetadata() + .withName(name) + .endMetadata() + .withNewSpec() + .addNewPort() + .withPort(port) + .endPort() + .endSpec() + .build(); } } diff --git a/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8ServicesListSupplierMockClientTests.java b/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8ServicesListSupplierMockClientTests.java index 460af3885e..c4d227803d 100644 --- a/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8ServicesListSupplierMockClientTests.java +++ b/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8ServicesListSupplierMockClientTests.java @@ -89,8 +89,10 @@ void testAllNamespaces(CapturedOutput output) { List> serviceInstances = supplier.get().collectList().block(); Assertions.assertEquals(serviceInstances.size(), 1); - List serviceInstancesSorted = serviceInstances.get(0).stream() - .sorted(Comparator.comparing(ServiceInstance::getServiceId)).toList(); + List serviceInstancesSorted = serviceInstances.get(0) + .stream() + .sorted(Comparator.comparing(ServiceInstance::getServiceId)) + .toList(); Assertions.assertEquals(serviceInstancesSorted.size(), 2); Assertions.assertEquals(serviceInstancesSorted.get(0).getServiceId(), "service-a"); @@ -112,7 +114,7 @@ void testOneNamespace(CapturedOutput output) { createService("c", "service-c", 8889); Environment environment = new MockEnvironment().withProperty("spring.cloud.kubernetes.client.namespace", "c") - .withProperty("loadbalancer.client.name", "service-c"); + .withProperty("loadbalancer.client.name", "service-c"); boolean allNamespaces = false; Set selectiveNamespaces = Set.of(); @@ -128,8 +130,10 @@ void testOneNamespace(CapturedOutput output) { Assertions.assertEquals(serviceInstances.size(), 1); List inner = serviceInstances.get(0); - List serviceInstancesSorted = serviceInstances.get(0).stream() - .sorted(Comparator.comparing(ServiceInstance::getServiceId)).toList(); + List serviceInstancesSorted = serviceInstances.get(0) + .stream() + .sorted(Comparator.comparing(ServiceInstance::getServiceId)) + .toList(); Assertions.assertEquals(serviceInstancesSorted.size(), 1); Assertions.assertEquals(inner.get(0).getServiceId(), "service-c"); Assertions.assertEquals(inner.get(0).getHost(), "service-c.c.svc.cluster.local"); @@ -160,8 +164,10 @@ void testSelectiveNamespaces(CapturedOutput output) { List> serviceInstances = supplier.get().collectList().block(); Assertions.assertEquals(serviceInstances.size(), 1); - List serviceInstancesSorted = serviceInstances.get(0).stream() - .sorted(Comparator.comparing(ServiceInstance::getPort)).toList(); + List serviceInstancesSorted = serviceInstances.get(0) + .stream() + .sorted(Comparator.comparing(ServiceInstance::getPort)) + .toList(); Assertions.assertEquals(serviceInstancesSorted.size(), 2); Assertions.assertEquals(serviceInstancesSorted.get(0).getServiceId(), "my-service"); Assertions.assertEquals(serviceInstancesSorted.get(0).getHost(), "my-service.a.svc.cluster.local"); @@ -175,10 +181,14 @@ void testSelectiveNamespaces(CapturedOutput output) { } private void createService(String namespace, String name, int port) { - Service service = new ServiceBuilder().withNewMetadata().withNamespace(namespace).withName(name).endMetadata() - .withSpec(new ServiceSpecBuilder() - .withPorts(new ServicePortBuilder().withName("http").withPort(port).build()).build()) - .build(); + Service service = new ServiceBuilder().withNewMetadata() + .withNamespace(namespace) + .withName(name) + .endMetadata() + .withSpec( + new ServiceSpecBuilder().withPorts(new ServicePortBuilder().withName("http").withPort(port).build()) + .build()) + .build(); mockClient.services().resource(service).create(); } diff --git a/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/Util.java b/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/Util.java index 92dfebaecd..03f73c14f5 100644 --- a/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/Util.java +++ b/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/Util.java @@ -44,17 +44,23 @@ private Util() { } public static Service service(String namespace, String name, int port) { - return new ServiceBuilder().withNewMetadata().withNamespace(namespace).withName(name).endMetadata() - .withSpec(new ServiceSpecBuilder() - .withPorts(new ServicePortBuilder().withName("http").withPort(port).build()).build()) - .build(); + return new ServiceBuilder().withNewMetadata() + .withNamespace(namespace) + .withName(name) + .endMetadata() + .withSpec( + new ServiceSpecBuilder().withPorts(new ServicePortBuilder().withName("http").withPort(port).build()) + .build()) + .build(); } public static Endpoints endpoints(int port, String host, String namespace) { return new EndpointsBuilder() - .withSubsets(new EndpointSubsetBuilder().withPorts(new EndpointPortBuilder().withPort(port).build()) - .withAddresses(new EndpointAddressBuilder().withIp(host).build()).build()) - .withMetadata(new ObjectMetaBuilder().withName("random-name").withNamespace(namespace).build()).build(); + .withSubsets(new EndpointSubsetBuilder().withPorts(new EndpointPortBuilder().withPort(port).build()) + .withAddresses(new EndpointAddressBuilder().withIp(host).build()) + .build()) + .withMetadata(new ObjectMetaBuilder().withName("random-name").withNamespace(namespace).build()) + .build(); } @TestConfiguration diff --git a/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/pod/AllNamespacesTest.java b/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/pod/AllNamespacesTest.java index c58b8c3c27..864a467b3d 100644 --- a/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/pod/AllNamespacesTest.java +++ b/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/pod/AllNamespacesTest.java @@ -70,7 +70,7 @@ class AllNamespacesTest { private static WireMockServer serviceBMockServer; private static final MockedStatic MOCKED_STATIC = Mockito - .mockStatic(KubernetesServiceInstanceMapper.class); + .mockStatic(KubernetesServiceInstanceMapper.class); @Autowired private WebClient.Builder builder; @@ -96,10 +96,10 @@ static void beforeAll() { // we mock host creation so that it becomes something like : localhost:8888 // then wiremock can catch this request, and we can assert for the result MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("service-a", "a", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("service-b", "b", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); // Configure the kubernetes master url to point to the mock server System.setProperty(Config.KUBERNETES_MASTER_SYSTEM_PROPERTY, "http://localhost:" + wireMockServer.port()); @@ -141,43 +141,53 @@ void test() { String serviceBString = Serialization.asJson(serviceB); wireMockServer - .stubFor(WireMock.get(WireMock.urlEqualTo("/api/v1/endpoints?fieldSelector=metadata.name%3Dservice-a")) - .willReturn(WireMock.aResponse().withBody(endpointsAListAsString).withStatus(200))); + .stubFor(WireMock.get(WireMock.urlEqualTo("/api/v1/endpoints?fieldSelector=metadata.name%3Dservice-a")) + .willReturn(WireMock.aResponse().withBody(endpointsAListAsString).withStatus(200))); wireMockServer - .stubFor(WireMock.get(WireMock.urlEqualTo("/api/v1/endpoints?fieldSelector=metadata.name%3Dservice-b")) - .willReturn(WireMock.aResponse().withBody(endpointsBListAsString).withStatus(200))); + .stubFor(WireMock.get(WireMock.urlEqualTo("/api/v1/endpoints?fieldSelector=metadata.name%3Dservice-b")) + .willReturn(WireMock.aResponse().withBody(endpointsBListAsString).withStatus(200))); wireMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/api/v1/namespaces/a/services/service-a")) - .willReturn(WireMock.aResponse().withBody(serviceAString).withStatus(200))); + .willReturn(WireMock.aResponse().withBody(serviceAString).withStatus(200))); wireMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/api/v1/namespaces/b/services/service-b")) - .willReturn(WireMock.aResponse().withBody(serviceBString).withStatus(200))); + .willReturn(WireMock.aResponse().withBody(serviceBString).withStatus(200))); serviceAMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); + .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); serviceBMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); - - String serviceAResult = builder.baseUrl(SERVICE_A_URL).build().method(HttpMethod.GET).retrieve() - .bodyToMono(String.class).block(); + .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); + + String serviceAResult = builder.baseUrl(SERVICE_A_URL) + .build() + .method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .block(); Assertions.assertThat(serviceAResult).isEqualTo("service-a-reached"); - String serviceBResult = builder.baseUrl(SERVICE_B_URL).build().method(HttpMethod.GET).retrieve() - .bodyToMono(String.class).block(); + String serviceBResult = builder.baseUrl(SERVICE_B_URL) + .build() + .method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .block(); Assertions.assertThat(serviceBResult).isEqualTo("service-b-reached"); CachingServiceInstanceListSupplier supplier = (CachingServiceInstanceListSupplier) loadBalancerClientFactory - .getIfAvailable().getProvider("service-a", ServiceInstanceListSupplier.class).getIfAvailable(); + .getIfAvailable() + .getProvider("service-a", ServiceInstanceListSupplier.class) + .getIfAvailable(); Assertions.assertThat(supplier.getDelegate().getClass()) - .isSameAs(DiscoveryClientServiceInstanceListSupplier.class); + .isSameAs(DiscoveryClientServiceInstanceListSupplier.class); wireMockServer.verify(WireMock.exactly(1), WireMock - .getRequestedFor(WireMock.urlEqualTo("/api/v1/endpoints?fieldSelector=metadata.name%3Dservice-a"))); + .getRequestedFor(WireMock.urlEqualTo("/api/v1/endpoints?fieldSelector=metadata.name%3Dservice-a"))); wireMockServer.verify(WireMock.exactly(1), WireMock - .getRequestedFor(WireMock.urlEqualTo("/api/v1/endpoints?fieldSelector=metadata.name%3Dservice-b"))); + .getRequestedFor(WireMock.urlEqualTo("/api/v1/endpoints?fieldSelector=metadata.name%3Dservice-b"))); wireMockServer.verify(WireMock.exactly(1), WireMock.getRequestedFor(WireMock.urlEqualTo("/api/v1/namespaces/a/services/service-a"))); diff --git a/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/pod/SelectiveNamespacesTest.java b/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/pod/SelectiveNamespacesTest.java index c41c1fe0e2..8576c264ff 100644 --- a/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/pod/SelectiveNamespacesTest.java +++ b/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/pod/SelectiveNamespacesTest.java @@ -72,7 +72,7 @@ class SelectiveNamespacesTest { private static WireMockServer serviceCMockServer; private static final MockedStatic MOCKED_STATIC = Mockito - .mockStatic(KubernetesServiceInstanceMapper.class); + .mockStatic(KubernetesServiceInstanceMapper.class); @Autowired private WebClient.Builder builder; @@ -102,13 +102,13 @@ static void beforeAll() { // we mock host creation so that it becomes something like : localhost:8888 // then wiremock can catch this request, and we can assert for the result MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("my-service", "a", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("my-service", "b", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("my-service", "c", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); // Configure the kubernetes master url to point to the mock server System.setProperty(Config.KUBERNETES_MASTER_SYSTEM_PROPERTY, "http://localhost:" + wireMockServer.port()); @@ -160,40 +160,48 @@ void test() { String endpointsCListAsString = Serialization.asJson(new EndpointsListBuilder().withItems(endpointsC).build()); wireMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/api/v1/namespaces/a/services/my-service")) - .willReturn(WireMock.aResponse().withBody(serviceAJson).withStatus(200))); + .willReturn(WireMock.aResponse().withBody(serviceAJson).withStatus(200))); wireMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/api/v1/namespaces/b/services/my-service")) - .willReturn(WireMock.aResponse().withBody(serviceBJson).withStatus(200))); + .willReturn(WireMock.aResponse().withBody(serviceBJson).withStatus(200))); wireMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/api/v1/namespaces/c/services/my-service")) - .willReturn(WireMock.aResponse().withBody(serviceCJson).withStatus(200))); + .willReturn(WireMock.aResponse().withBody(serviceCJson).withStatus(200))); wireMockServer.stubFor(WireMock - .get(WireMock.urlEqualTo("/api/v1/namespaces/a/endpoints?fieldSelector=metadata.name%3Dmy-service")) - .willReturn(WireMock.aResponse().withBody(endpointsAListAsString).withStatus(200))); + .get(WireMock.urlEqualTo("/api/v1/namespaces/a/endpoints?fieldSelector=metadata.name%3Dmy-service")) + .willReturn(WireMock.aResponse().withBody(endpointsAListAsString).withStatus(200))); wireMockServer.stubFor(WireMock - .get(WireMock.urlEqualTo("/api/v1/namespaces/b/endpoints?fieldSelector=metadata.name%3Dmy-service")) - .willReturn(WireMock.aResponse().withBody(endpointsBListAsString).withStatus(200))); + .get(WireMock.urlEqualTo("/api/v1/namespaces/b/endpoints?fieldSelector=metadata.name%3Dmy-service")) + .willReturn(WireMock.aResponse().withBody(endpointsBListAsString).withStatus(200))); wireMockServer.stubFor(WireMock - .get(WireMock.urlEqualTo("/api/v1/namespaces/c/endpoints?fieldSelector=metadata.name%3Dmy-service")) - .willReturn(WireMock.aResponse().withBody(endpointsCListAsString).withStatus(200))); + .get(WireMock.urlEqualTo("/api/v1/namespaces/c/endpoints?fieldSelector=metadata.name%3Dmy-service")) + .willReturn(WireMock.aResponse().withBody(endpointsCListAsString).withStatus(200))); serviceAMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); + .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); serviceBMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); + .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); serviceCMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-c-reached").withStatus(200))); - - String firstCallResult = builder.baseUrl(MY_SERVICE_URL).build().method(HttpMethod.GET).retrieve() - .bodyToMono(String.class).block(); - - String secondCallResult = builder.baseUrl(MY_SERVICE_URL).build().method(HttpMethod.GET).retrieve() - .bodyToMono(String.class).block(); + .willReturn(WireMock.aResponse().withBody("service-c-reached").withStatus(200))); + + String firstCallResult = builder.baseUrl(MY_SERVICE_URL) + .build() + .method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .block(); + + String secondCallResult = builder.baseUrl(MY_SERVICE_URL) + .build() + .method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .block(); // since selective namespaces is a Set, we need to be careful with assertion order if (firstCallResult.equals("service-a-reached")) { @@ -205,9 +213,11 @@ void test() { } CachingServiceInstanceListSupplier supplier = (CachingServiceInstanceListSupplier) loadBalancerClientFactory - .getIfAvailable().getProvider("my-service", ServiceInstanceListSupplier.class).getIfAvailable(); + .getIfAvailable() + .getProvider("my-service", ServiceInstanceListSupplier.class) + .getIfAvailable(); Assertions.assertThat(supplier.getDelegate().getClass()) - .isSameAs(DiscoveryClientServiceInstanceListSupplier.class); + .isSameAs(DiscoveryClientServiceInstanceListSupplier.class); wireMockServer.verify(WireMock.exactly(1), WireMock.getRequestedFor(WireMock.urlEqualTo("/api/v1/namespaces/a/services/my-service"))); diff --git a/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/pod/SpecificNamespaceTest.java b/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/pod/SpecificNamespaceTest.java index 53c84fc759..e005d04546 100644 --- a/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/pod/SpecificNamespaceTest.java +++ b/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/pod/SpecificNamespaceTest.java @@ -67,7 +67,7 @@ class SpecificNamespaceTest { private static WireMockServer serviceBMockServer; private static final MockedStatic MOCKED_STATIC = Mockito - .mockStatic(KubernetesServiceInstanceMapper.class); + .mockStatic(KubernetesServiceInstanceMapper.class); @Autowired private WebClient.Builder builder; @@ -93,10 +93,10 @@ static void beforeAll() { // we mock host creation so that it becomes something like : localhost:8888 // then wiremock can catch this request, and we can assert for the result MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("my-service", "a", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("my-service", "b", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); // Configure the kubernetes master url to point to the mock server System.setProperty(Config.KUBERNETES_MASTER_SYSTEM_PROPERTY, "http://localhost:" + wireMockServer.port()); @@ -142,33 +142,39 @@ void test() { String serviceBString = Serialization.asJson(serviceB); wireMockServer.stubFor(WireMock - .get(WireMock.urlEqualTo("/api/v1/namespaces/a/endpoints?fieldSelector=metadata.name%3Dmy-service")) - .willReturn(WireMock.aResponse().withBody(endpointsAListAsString).withStatus(200))); + .get(WireMock.urlEqualTo("/api/v1/namespaces/a/endpoints?fieldSelector=metadata.name%3Dmy-service")) + .willReturn(WireMock.aResponse().withBody(endpointsAListAsString).withStatus(200))); wireMockServer.stubFor(WireMock - .get(WireMock.urlEqualTo("/api/v1/namespaces/b/endpoints?fieldSelector=metadata.name%3Dmy-service")) - .willReturn(WireMock.aResponse().withBody(endpointsBListAsString).withStatus(200))); + .get(WireMock.urlEqualTo("/api/v1/namespaces/b/endpoints?fieldSelector=metadata.name%3Dmy-service")) + .willReturn(WireMock.aResponse().withBody(endpointsBListAsString).withStatus(200))); wireMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/api/v1/namespaces/a/services/my-service")) - .willReturn(WireMock.aResponse().withBody(serviceAString).withStatus(200))); + .willReturn(WireMock.aResponse().withBody(serviceAString).withStatus(200))); wireMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/api/v1/namespaces/b/services/my-service")) - .willReturn(WireMock.aResponse().withBody(serviceBString).withStatus(200))); + .willReturn(WireMock.aResponse().withBody(serviceBString).withStatus(200))); serviceAMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); + .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); serviceBMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); - - String serviceAResult = builder.baseUrl(SERVICE_A_URL).build().method(HttpMethod.GET).retrieve() - .bodyToMono(String.class).block(); + .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); + + String serviceAResult = builder.baseUrl(SERVICE_A_URL) + .build() + .method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .block(); Assertions.assertThat(serviceAResult).isEqualTo("service-a-reached"); CachingServiceInstanceListSupplier supplier = (CachingServiceInstanceListSupplier) loadBalancerClientFactory - .getIfAvailable().getProvider("my-service", ServiceInstanceListSupplier.class).getIfAvailable(); + .getIfAvailable() + .getProvider("my-service", ServiceInstanceListSupplier.class) + .getIfAvailable(); Assertions.assertThat(supplier.getDelegate().getClass()) - .isSameAs(DiscoveryClientServiceInstanceListSupplier.class); + .isSameAs(DiscoveryClientServiceInstanceListSupplier.class); wireMockServer.verify(WireMock.exactly(1), WireMock.getRequestedFor( WireMock.urlEqualTo("/api/v1/namespaces/a/endpoints?fieldSelector=metadata.name%3Dmy-service"))); diff --git a/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/service/AllNamespacesTest.java b/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/service/AllNamespacesTest.java index 77831735be..7bb9f0f98a 100644 --- a/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/service/AllNamespacesTest.java +++ b/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/service/AllNamespacesTest.java @@ -73,7 +73,7 @@ class AllNamespacesTest { private static WireMockServer serviceBMockServer; private static final MockedStatic MOCKED_STATIC = Mockito - .mockStatic(KubernetesServiceInstanceMapper.class); + .mockStatic(KubernetesServiceInstanceMapper.class); @Autowired private WebClient.Builder builder; @@ -99,10 +99,10 @@ static void beforeAll() { // we mock host creation so that it becomes something like : localhost:8888 // then wiremock can catch this request, and we can assert for the result MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("service-a", "a", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("service-b", "b", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); // Configure the kubernetes master url to point to the mock server System.setProperty(Config.KUBERNETES_MASTER_SYSTEM_PROPERTY, "http://localhost:" + wireMockServer.port()); @@ -138,33 +138,45 @@ void test(CapturedOutput output) { String serviceListBJson = Serialization.asJson(new ServiceListBuilder().withItems(serviceB).build()); wireMockServer - .stubFor(WireMock.get(WireMock.urlEqualTo("/api/v1/services?fieldSelector=metadata.name%3Dservice-a")) - .willReturn(WireMock.aResponse().withBody(serviceListAJson).withStatus(200))); + .stubFor(WireMock.get(WireMock.urlEqualTo("/api/v1/services?fieldSelector=metadata.name%3Dservice-a")) + .willReturn(WireMock.aResponse().withBody(serviceListAJson).withStatus(200))); wireMockServer - .stubFor(WireMock.get(WireMock.urlEqualTo("/api/v1/services?fieldSelector=metadata.name%3Dservice-b")) - .willReturn(WireMock.aResponse().withBody(serviceListBJson).withStatus(200))); + .stubFor(WireMock.get(WireMock.urlEqualTo("/api/v1/services?fieldSelector=metadata.name%3Dservice-b")) + .willReturn(WireMock.aResponse().withBody(serviceListBJson).withStatus(200))); serviceAMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); + .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); serviceBMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); - - String serviceAResult = builder.baseUrl(SERVICE_A_URL).build().method(HttpMethod.GET).retrieve() - .bodyToMono(String.class).block(); + .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); + + String serviceAResult = builder.baseUrl(SERVICE_A_URL) + .build() + .method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .block(); Assertions.assertThat(serviceAResult).isEqualTo("service-a-reached"); - String serviceBResult = builder.baseUrl(SERVICE_B_URL).build().method(HttpMethod.GET).retrieve() - .bodyToMono(String.class).block(); + String serviceBResult = builder.baseUrl(SERVICE_B_URL) + .build() + .method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .block(); Assertions.assertThat(serviceBResult).isEqualTo("service-b-reached"); CachingServiceInstanceListSupplier supplierA = (CachingServiceInstanceListSupplier) loadBalancerClientFactory - .getIfAvailable().getProvider("service-a", ServiceInstanceListSupplier.class).getIfAvailable(); + .getIfAvailable() + .getProvider("service-a", ServiceInstanceListSupplier.class) + .getIfAvailable(); Assertions.assertThat(supplierA.getDelegate().getClass()).isSameAs(Fabric8ServicesListSupplier.class); CachingServiceInstanceListSupplier supplierB = (CachingServiceInstanceListSupplier) loadBalancerClientFactory - .getIfAvailable().getProvider("service-b", ServiceInstanceListSupplier.class).getIfAvailable(); + .getIfAvailable() + .getProvider("service-b", ServiceInstanceListSupplier.class) + .getIfAvailable(); Assertions.assertThat(supplierB.getDelegate().getClass()).isSameAs(Fabric8ServicesListSupplier.class); Assertions.assertThat(output.getOut()).contains("serviceID : service-a"); @@ -172,10 +184,10 @@ void test(CapturedOutput output) { Assertions.assertThat(output.getOut()).contains("discovering services in all namespaces"); wireMockServer.verify(WireMock.exactly(1), WireMock - .getRequestedFor(WireMock.urlEqualTo("/api/v1/services?fieldSelector=metadata.name%3Dservice-a"))); + .getRequestedFor(WireMock.urlEqualTo("/api/v1/services?fieldSelector=metadata.name%3Dservice-a"))); wireMockServer.verify(WireMock.exactly(1), WireMock - .getRequestedFor(WireMock.urlEqualTo("/api/v1/services?fieldSelector=metadata.name%3Dservice-b"))); + .getRequestedFor(WireMock.urlEqualTo("/api/v1/services?fieldSelector=metadata.name%3Dservice-b"))); } } diff --git a/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/service/SelectiveNamespacesTest.java b/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/service/SelectiveNamespacesTest.java index efeb890108..e0efbc2cbb 100644 --- a/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/service/SelectiveNamespacesTest.java +++ b/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/service/SelectiveNamespacesTest.java @@ -74,7 +74,7 @@ class SelectiveNamespacesTest { private static WireMockServer serviceCMockServer; private static final MockedStatic MOCKED_STATIC = Mockito - .mockStatic(KubernetesServiceInstanceMapper.class); + .mockStatic(KubernetesServiceInstanceMapper.class); @Autowired private WebClient.Builder builder; @@ -104,13 +104,13 @@ static void beforeAll() { // we mock host creation so that it becomes something like : localhost:8888 // then wiremock can catch this request, and we can assert for the result MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("my-service", "a", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("my-service", "b", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("my-service", "c", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); // Configure the kubernetes master url to point to the mock server System.setProperty(Config.KUBERNETES_MASTER_SYSTEM_PROPERTY, "http://localhost:" + wireMockServer.port()); @@ -154,28 +154,36 @@ void test(CapturedOutput output) { String serviceCJson = Serialization.asJson(serviceC); wireMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/api/v1/namespaces/a/services/my-service")) - .willReturn(WireMock.aResponse().withBody(serviceAJson).withStatus(200))); + .willReturn(WireMock.aResponse().withBody(serviceAJson).withStatus(200))); wireMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/api/v1/namespaces/b/services/my-service")) - .willReturn(WireMock.aResponse().withBody(serviceBJson).withStatus(200))); + .willReturn(WireMock.aResponse().withBody(serviceBJson).withStatus(200))); wireMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/api/v1/namespaces/c/services/my-service")) - .willReturn(WireMock.aResponse().withBody(serviceCJson).withStatus(200))); + .willReturn(WireMock.aResponse().withBody(serviceCJson).withStatus(200))); serviceAMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); + .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); serviceBMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); + .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); serviceCMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-c-reached").withStatus(200))); - - String firstCallResult = builder.baseUrl(MY_SERVICE_URL).build().method(HttpMethod.GET).retrieve() - .bodyToMono(String.class).block(); - - String secondCallResult = builder.baseUrl(MY_SERVICE_URL).build().method(HttpMethod.GET).retrieve() - .bodyToMono(String.class).block(); + .willReturn(WireMock.aResponse().withBody("service-c-reached").withStatus(200))); + + String firstCallResult = builder.baseUrl(MY_SERVICE_URL) + .build() + .method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .block(); + + String secondCallResult = builder.baseUrl(MY_SERVICE_URL) + .build() + .method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .block(); // since selective namespaces is a Set, we need to be careful with assertion order if (firstCallResult.equals("service-a-reached")) { @@ -187,7 +195,9 @@ void test(CapturedOutput output) { } CachingServiceInstanceListSupplier supplier = (CachingServiceInstanceListSupplier) loadBalancerClientFactory - .getIfAvailable().getProvider("my-service", ServiceInstanceListSupplier.class).getIfAvailable(); + .getIfAvailable() + .getProvider("my-service", ServiceInstanceListSupplier.class) + .getIfAvailable(); Assertions.assertThat(supplier.getDelegate().getClass()).isSameAs(Fabric8ServicesListSupplier.class); Assertions.assertThat(output.getOut()).contains("serviceID : my-service"); diff --git a/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/service/SpecificNamespaceTest.java b/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/service/SpecificNamespaceTest.java index 687a3cbb1b..4046a159ce 100644 --- a/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/service/SpecificNamespaceTest.java +++ b/spring-cloud-kubernetes-fabric8-loadbalancer/src/test/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/it/mode/service/SpecificNamespaceTest.java @@ -71,7 +71,7 @@ class SpecificNamespaceTest { private static WireMockServer serviceBMockServer; private static final MockedStatic MOCKED_STATIC = Mockito - .mockStatic(KubernetesServiceInstanceMapper.class); + .mockStatic(KubernetesServiceInstanceMapper.class); @Autowired private WebClient.Builder builder; @@ -97,10 +97,10 @@ static void beforeAll() { // we mock host creation so that it becomes something like : localhost:8888 // then wiremock can catch this request, and we can assert for the result MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("my-service", "a", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("my-service", "b", "cluster.local")) - .thenReturn("localhost"); + .thenReturn("localhost"); // Configure the kubernetes master url to point to the mock server System.setProperty(Config.KUBERNETES_MASTER_SYSTEM_PROPERTY, "http://localhost:" + wireMockServer.port()); @@ -140,23 +140,29 @@ void test(CapturedOutput output) { String serviceBJson = Serialization.asJson(serviceB); wireMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/api/v1/namespaces/a/services/my-service")) - .willReturn(WireMock.aResponse().withBody(serviceAJson).withStatus(200))); + .willReturn(WireMock.aResponse().withBody(serviceAJson).withStatus(200))); wireMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/api/v1/namespaces/b/services/my-service")) - .willReturn(WireMock.aResponse().withBody(serviceBJson).withStatus(200))); + .willReturn(WireMock.aResponse().withBody(serviceBJson).withStatus(200))); serviceAMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); + .willReturn(WireMock.aResponse().withBody("service-a-reached").withStatus(200))); serviceBMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/")) - .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); - - String serviceAResult = builder.baseUrl(MY_SERVICE_URL).build().method(HttpMethod.GET).retrieve() - .bodyToMono(String.class).block(); + .willReturn(WireMock.aResponse().withBody("service-b-reached").withStatus(200))); + + String serviceAResult = builder.baseUrl(MY_SERVICE_URL) + .build() + .method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .block(); Assertions.assertThat(serviceAResult).isEqualTo("service-a-reached"); CachingServiceInstanceListSupplier supplier = (CachingServiceInstanceListSupplier) loadBalancerClientFactory - .getIfAvailable().getProvider("my-service", ServiceInstanceListSupplier.class).getIfAvailable(); + .getIfAvailable() + .getProvider("my-service", ServiceInstanceListSupplier.class) + .getIfAvailable(); Assertions.assertThat(supplier.getDelegate().getClass()).isSameAs(Fabric8ServicesListSupplier.class); Assertions.assertThat(output.getOut()).contains("serviceID : my-service"); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-catalog-watcher/src/test/java/org/springframework/cloud/kubernetes/fabric8/catalog/watch/Fabric8CatalogWatchIT.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-catalog-watcher/src/test/java/org/springframework/cloud/kubernetes/fabric8/catalog/watch/Fabric8CatalogWatchIT.java index bd82dfbb29..652699eaad 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-catalog-watcher/src/test/java/org/springframework/cloud/kubernetes/fabric8/catalog/watch/Fabric8CatalogWatchIT.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-catalog-watcher/src/test/java/org/springframework/cloud/kubernetes/fabric8/catalog/watch/Fabric8CatalogWatchIT.java @@ -146,9 +146,9 @@ void testCatalogWatchWithNamespaceFilterAndEndpointSlices() { */ private void assertLogStatement() throws Exception { String appPodName = K3S - .execInContainer("kubectl", "get", "pods", "-l", - "app=spring-cloud-kubernetes-fabric8-client-catalog-watcher", "-o=name", "--no-headers") - .getStdout(); + .execInContainer("kubectl", "get", "pods", "-l", + "app=spring-cloud-kubernetes-fabric8-client-catalog-watcher", "-o=name", "--no-headers") + .getStdout(); String allLogs = K3S.execInContainer("kubectl", "logs", appPodName.trim()).getStdout(); Assertions.assertTrue(allLogs.contains("stateGenerator is of type: Fabric8EndpointsCatalogWatch")); } @@ -166,8 +166,10 @@ private void test() { await().pollInterval(Duration.ofSeconds(1)).atMost(Duration.ofSeconds(240)).until(() -> { List result = (List) client.method(HttpMethod.GET) - .retrieve().bodyToMono(ParameterizedTypeReference.forType(resolvableType.getType())) - .retryWhen(retrySpec()).block(); + .retrieve() + .bodyToMono(ParameterizedTypeReference.forType(resolvableType.getType())) + .retryWhen(retrySpec()) + .block(); // we get 3 pods as input, but because they are sorted by name in the catalog // watcher implementation @@ -202,8 +204,10 @@ private void test() { await().pollInterval(Duration.ofSeconds(1)).atMost(Duration.ofSeconds(240)).until(() -> { List result = (List) client.method(HttpMethod.GET) - .retrieve().bodyToMono(ParameterizedTypeReference.forType(resolvableType.getType())) - .retryWhen(retrySpec()).block(); + .retrieve() + .bodyToMono(ParameterizedTypeReference.forType(resolvableType.getType())) + .retryWhen(retrySpec()) + .block(); // we need to get the event from KubernetesCatalogWatch, but that happens // on periodic bases. So in order to be sure we got the event we care about diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-catalog-watcher/src/test/java/org/springframework/cloud/kubernetes/fabric8/catalog/watch/Fabric8CatalogWatchWithNamespacesDelegate.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-catalog-watcher/src/test/java/org/springframework/cloud/kubernetes/fabric8/catalog/watch/Fabric8CatalogWatchWithNamespacesDelegate.java index ad1c7543ac..69d4a06352 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-catalog-watcher/src/test/java/org/springframework/cloud/kubernetes/fabric8/catalog/watch/Fabric8CatalogWatchWithNamespacesDelegate.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-catalog-watcher/src/test/java/org/springframework/cloud/kubernetes/fabric8/catalog/watch/Fabric8CatalogWatchWithNamespacesDelegate.java @@ -83,8 +83,10 @@ private static void test(Util util) { await().pollInterval(Duration.ofSeconds(1)).atMost(Duration.ofSeconds(240)).until(() -> { List result = (List) client.method(HttpMethod.GET) - .retrieve().bodyToMono(ParameterizedTypeReference.forType(resolvableType.getType())) - .retryWhen(retrySpec()).block(); + .retrieve() + .bodyToMono(ParameterizedTypeReference.forType(resolvableType.getType())) + .retryWhen(retrySpec()) + .block(); // we get 3 pods as input, but because they are sorted by name in the catalog // watcher implementation @@ -117,8 +119,10 @@ private static void test(Util util) { await().pollInterval(Duration.ofSeconds(1)).atMost(Duration.ofSeconds(240)).until(() -> { List result = (List) client.method(HttpMethod.GET) - .retrieve().bodyToMono(ParameterizedTypeReference.forType(resolvableType.getType())) - .retryWhen(retrySpec()).block(); + .retrieve() + .bodyToMono(ParameterizedTypeReference.forType(resolvableType.getType())) + .retryWhen(retrySpec()) + .block(); // we need to get the event from KubernetesCatalogWatch, but that happens // on periodic bases. So in order to be sure we got the event we care about diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8ApplicationDiscoveryListener.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8ApplicationDiscoveryListener.java index 0ae7606ac2..7ecafcefef 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8ApplicationDiscoveryListener.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8ApplicationDiscoveryListener.java @@ -37,7 +37,7 @@ public class Fabric8ApplicationDiscoveryListener implements ApplicationListener< @Override public void onApplicationEvent(InstanceRegisteredEvent event) { Pod pod = (Pod) ((KubernetesDiscoveryClientHealthIndicatorInitializer.RegisteredEventSource) event.getSource()) - .pod(); + .pod(); LOG.info(() -> "received InstanceRegisteredEvent from pod with 'app' label value : " + pod.getMetadata().getLabels().get("app")); } diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryBoostrapDelegate.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryBoostrapDelegate.java index c4584c3f0c..6917d0d80e 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryBoostrapDelegate.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryBoostrapDelegate.java @@ -39,10 +39,13 @@ final class Fabric8DiscoveryBoostrapDelegate { static void testAllServicesWithBootstrap() { WebClient client = builder().baseUrl("http://localhost/services").build(); - List result = client.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { + List result = client.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(result.size(), 5); Assertions.assertTrue(result.contains("kubernetes")); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryClientHealthDelegate.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryClientHealthDelegate.java index 5f7a34937c..b9bfaa18b7 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryClientHealthDelegate.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryClientHealthDelegate.java @@ -66,20 +66,24 @@ static void testBlockingConfiguration(K3sContainer k3sContainer, String imageNam WebClient healthClient = builder().baseUrl("http://localhost/actuator/health").build(); - String healthResult = healthClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(retrySpec()).block(); + String healthResult = healthClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathStringValue("$.components.discoveryComposite.status").isEqualTo("UP"); + .extractingJsonPathStringValue("$.components.discoveryComposite.status") + .isEqualTo("UP"); - Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)).extractingJsonPathStringValue(BLOCKING_STATUS) - .isEqualTo("UP"); + Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) + .extractingJsonPathStringValue(BLOCKING_STATUS) + .isEqualTo("UP"); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathArrayValue( - "$.components.discoveryComposite.components.discoveryClient.details.services") - .containsExactlyInAnyOrder("spring-cloud-kubernetes-fabric8-client-discovery", "kubernetes", - "busybox-service", "external-name-service", "service-wiremock"); + .extractingJsonPathArrayValue("$.components.discoveryComposite.components.discoveryClient.details.services") + .containsExactlyInAnyOrder("spring-cloud-kubernetes-fabric8-client-discovery", "kubernetes", + "busybox-service", "external-name-service", "service-wiremock"); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)).doesNotHaveJsonPath(REACTIVE_STATUS); @@ -99,33 +103,39 @@ static void testDefaultConfiguration(K3sContainer k3sContainer, String imageName WebClient healthClient = builder().baseUrl("http://localhost/actuator/health").build(); - String healthResult = healthClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(retrySpec()).block(); + String healthResult = healthClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathStringValue("$.components.discoveryComposite.status").isEqualTo("UP"); + .extractingJsonPathStringValue("$.components.discoveryComposite.status") + .isEqualTo("UP"); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathStringValue("$.components.discoveryComposite.components.discoveryClient.status") - .isEqualTo("UP"); + .extractingJsonPathStringValue("$.components.discoveryComposite.components.discoveryClient.status") + .isEqualTo("UP"); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathArrayValue( - "$.components.discoveryComposite.components.discoveryClient.details.services") - .containsExactlyInAnyOrder("spring-cloud-kubernetes-fabric8-client-discovery", "kubernetes", - "external-name-service", "service-wiremock", "busybox-service"); + .extractingJsonPathArrayValue("$.components.discoveryComposite.components.discoveryClient.details.services") + .containsExactlyInAnyOrder("spring-cloud-kubernetes-fabric8-client-discovery", "kubernetes", + "external-name-service", "service-wiremock", "busybox-service"); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathStringValue("$.components.reactiveDiscoveryClients.status").isEqualTo("UP"); + .extractingJsonPathStringValue("$.components.reactiveDiscoveryClients.status") + .isEqualTo("UP"); - Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)).extractingJsonPathStringValue( - "$.components.reactiveDiscoveryClients.components.['Fabric8 Kubernetes Reactive Discovery Client'].status") - .isEqualTo("UP"); + Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) + .extractingJsonPathStringValue( + "$.components.reactiveDiscoveryClients.components.['Fabric8 Kubernetes Reactive Discovery Client'].status") + .isEqualTo("UP"); - Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)).extractingJsonPathArrayValue( - "$.components.reactiveDiscoveryClients.components.['Fabric8 Kubernetes Reactive Discovery Client'].details.services") - .containsExactlyInAnyOrder("spring-cloud-kubernetes-fabric8-client-discovery", "kubernetes", - "external-name-service", "service-wiremock", "busybox-service"); + Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) + .extractingJsonPathArrayValue( + "$.components.reactiveDiscoveryClients.components.['Fabric8 Kubernetes Reactive Discovery Client'].details.services") + .containsExactlyInAnyOrder("spring-cloud-kubernetes-fabric8-client-discovery", "kubernetes", + "external-name-service", "service-wiremock", "busybox-service"); } /** @@ -148,19 +158,25 @@ static void testReactiveConfiguration(K3sContainer k3sContainer, String imageNam WebClient healthClient = builder().baseUrl("http://localhost/actuator/health").build(); - String healthResult = healthClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(retrySpec()).block(); + String healthResult = healthClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathStringValue("$.components.reactiveDiscoveryClients.status").isEqualTo("UP"); + .extractingJsonPathStringValue("$.components.reactiveDiscoveryClients.status") + .isEqualTo("UP"); - Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)).extractingJsonPathStringValue(REACTIVE_STATUS) - .isEqualTo("UP"); + Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) + .extractingJsonPathStringValue(REACTIVE_STATUS) + .isEqualTo("UP"); - Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)).extractingJsonPathArrayValue( - "$.components.reactiveDiscoveryClients.components.['Fabric8 Kubernetes Reactive Discovery Client'].details.services") - .containsExactlyInAnyOrder("spring-cloud-kubernetes-fabric8-client-discovery", "kubernetes", - "external-name-service", "service-wiremock", "busybox-service"); + Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) + .extractingJsonPathArrayValue( + "$.components.reactiveDiscoveryClients.components.['Fabric8 Kubernetes Reactive Discovery Client'].details.services") + .containsExactlyInAnyOrder("spring-cloud-kubernetes-fabric8-client-discovery", "kubernetes", + "external-name-service", "service-wiremock", "busybox-service"); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)).doesNotHaveJsonPath(BLOCKING_STATUS); @@ -168,9 +184,12 @@ static void testReactiveConfiguration(K3sContainer k3sContainer, String imageNam WebClient servicesClient = builder().baseUrl("http://localhost/reactive/services").build(); - List servicesResult = servicesClient.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + List servicesResult = servicesClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertThat(servicesResult).contains("spring-cloud-kubernetes-fabric8-client-discovery"); Assertions.assertThat(servicesResult).contains("kubernetes"); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryDelegate.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryDelegate.java index f4debd425f..5b41469831 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryDelegate.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryDelegate.java @@ -45,10 +45,13 @@ private Fabric8DiscoveryDelegate() { static void testAllServices() { WebClient client = builder().baseUrl("http://localhost/services").build(); - List result = client.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { + List result = client.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(result.size(), 5); Assertions.assertTrue(result.contains("kubernetes")); @@ -61,10 +64,13 @@ static void testAllServices() { static void testExternalNameServiceInstance() { WebClient client = builder().baseUrl("http://localhost/service-instances/external-name-service").build(); - List serviceInstances = client.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { + List serviceInstances = client.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); DefaultKubernetesServiceInstance result = serviceInstances.get(0); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryFilterDelegate.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryFilterDelegate.java index 6e15af666e..bbdd789ce6 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryFilterDelegate.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryFilterDelegate.java @@ -51,21 +51,28 @@ static void filterMatchesBothNamespacesViaThePredicate() { WebClient clientServices = builder().baseUrl("http://localhost/services").build(); @SuppressWarnings("unchecked") - List services = (List) clientServices.method(HttpMethod.GET).retrieve().bodyToMono(List.class) - .retryWhen(retrySpec()).block(); + List services = (List) clientServices.method(HttpMethod.GET) + .retrieve() + .bodyToMono(List.class) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(services.size(), 1); Assertions.assertTrue(services.contains("service-wiremock")); WebClient client = builder().baseUrl("http://localhost/service-instances/service-wiremock").build(); - List serviceInstances = client.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { + List serviceInstances = client.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(serviceInstances.size(), 2); List sorted = serviceInstances.stream() - .sorted(Comparator.comparing(DefaultKubernetesServiceInstance::getNamespace)).toList(); + .sorted(Comparator.comparing(DefaultKubernetesServiceInstance::getNamespace)) + .toList(); DefaultKubernetesServiceInstance first = sorted.get(0); Assertions.assertEquals(first.getServiceId(), "service-wiremock"); @@ -100,17 +107,23 @@ static void filterMatchesOneNamespaceViaThePredicate() { WebClient clientServices = builder().baseUrl("http://localhost/services").build(); @SuppressWarnings("unchecked") - List services = (List) clientServices.method(HttpMethod.GET).retrieve().bodyToMono(List.class) - .retryWhen(retrySpec()).block(); + List services = (List) clientServices.method(HttpMethod.GET) + .retrieve() + .bodyToMono(List.class) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(services.size(), 1); Assertions.assertTrue(services.contains("service-wiremock")); WebClient client = builder().baseUrl("http://localhost/service-instances/service-wiremock").build(); - List serviceInstances = client.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { + List serviceInstances = client.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(serviceInstances.size(), 1); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryNamespaceDelegate.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryNamespaceDelegate.java index 59c7db5ab4..bf9c7998db 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryNamespaceDelegate.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryNamespaceDelegate.java @@ -41,17 +41,23 @@ static void namespaceFilter() { WebClient clientServices = builder().baseUrl("http://localhost/services").build(); @SuppressWarnings("unchecked") - List services = (List) clientServices.method(HttpMethod.GET).retrieve().bodyToMono(List.class) - .retryWhen(retrySpec()).block(); + List services = (List) clientServices.method(HttpMethod.GET) + .retrieve() + .bodyToMono(List.class) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(services.size(), 1); Assertions.assertTrue(services.contains("service-wiremock")); WebClient clientEndpoints = builder().baseUrl("http://localhost/endpoints/service-wiremock").build(); - List endpoints = clientEndpoints.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + List endpoints = clientEndpoints.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(endpoints.size(), 1); Assertions.assertEquals(endpoints.get(0).getMetadata().getNamespace(), "namespace-left"); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryPodMetadataIT.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryPodMetadataIT.java index 9aba3e0821..7fec5fdb8a 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryPodMetadataIT.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-discovery/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/discovery/Fabric8DiscoveryPodMetadataIT.java @@ -141,7 +141,8 @@ void testPodMetadata() throws Exception { // find both pods String[] both = K3S.execInContainer("sh", "-c", "kubectl get pods -l app=busybox -o=name --no-headers") - .getStdout().split("\n"); + .getStdout() + .split("\n"); // add a label to first pod K3S.execInContainer("sh", "-c", "kubectl label pods " + both[0].split("/")[1] + " custom-label=custom-label-value"); @@ -150,30 +151,43 @@ void testPodMetadata() throws Exception { "kubectl annotate pods " + both[1].split("/")[1] + " custom-annotation=custom-annotation-value"); WebClient client = builder().baseUrl("http://localhost/service-instances/busybox-service").build(); - List serviceInstances = client.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { + List serviceInstances = client.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); DefaultKubernetesServiceInstance withCustomLabel = serviceInstances.stream() - .filter(x -> x.podMetadata().getOrDefault("annotations", Map.of()).isEmpty()).toList().get(0); + .filter(x -> x.podMetadata().getOrDefault("annotations", Map.of()).isEmpty()) + .toList() + .get(0); Assertions.assertEquals(withCustomLabel.getServiceId(), "busybox-service"); Assertions.assertNotNull(withCustomLabel.getInstanceId()); Assertions.assertNotNull(withCustomLabel.getHost()); Assertions.assertEquals(withCustomLabel.getMetadata(), Map.of("k8s_namespace", "default", "type", "ClusterIP", "port.busybox-port", "80")); - Assertions.assertTrue(withCustomLabel.podMetadata().get("labels").entrySet().stream() - .anyMatch(x -> x.getKey().equals("custom-label") && x.getValue().equals("custom-label-value"))); + Assertions.assertTrue(withCustomLabel.podMetadata() + .get("labels") + .entrySet() + .stream() + .anyMatch(x -> x.getKey().equals("custom-label") && x.getValue().equals("custom-label-value"))); DefaultKubernetesServiceInstance withCustomAnnotation = serviceInstances.stream() - .filter(x -> !x.podMetadata().getOrDefault("annotations", Map.of()).isEmpty()).toList().get(0); + .filter(x -> !x.podMetadata().getOrDefault("annotations", Map.of()).isEmpty()) + .toList() + .get(0); Assertions.assertEquals(withCustomAnnotation.getServiceId(), "busybox-service"); Assertions.assertNotNull(withCustomAnnotation.getInstanceId()); Assertions.assertNotNull(withCustomAnnotation.getHost()); Assertions.assertEquals(withCustomAnnotation.getMetadata(), Map.of("k8s_namespace", "default", "type", "ClusterIP", "port.busybox-port", "80")); - Assertions.assertTrue(withCustomAnnotation.podMetadata().get("annotations").entrySet().stream().anyMatch( - x -> x.getKey().equals("custom-annotation") && x.getValue().equals("custom-annotation-value"))); + Assertions.assertTrue(withCustomAnnotation.podMetadata() + .get("annotations") + .entrySet() + .stream() + .anyMatch(x -> x.getKey().equals("custom-annotation") && x.getValue().equals("custom-annotation-value"))); testAllOther(); } @@ -247,12 +261,15 @@ private static void manifests(Phase phase) { List existing = new ArrayList<>( deployment.getSpec().getTemplate().getSpec().getContainers().get(0).getEnv()); existing.add(new EnvVarBuilder().withName("SPRING_CLOUD_KUBERNETES_DISCOVERY_METADATA_ADDPODLABELS") - .withValue("true").build()); + .withValue("true") + .build()); existing.add(new EnvVarBuilder().withName("SPRING_CLOUD_KUBERNETES_DISCOVERY_METADATA_ADDPODANNOTATIONS") - .withValue("true").build()); - existing.add( - new EnvVarBuilder().withName("LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_CLOUD_KUBERNETES_FABRIC8_DISCOVERY") - .withValue("DEBUG").build()); + .withValue("true") + .build()); + existing + .add(new EnvVarBuilder().withName("LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_CLOUD_KUBERNETES_FABRIC8_DISCOVERY") + .withValue("DEBUG") + .build()); deployment.getSpec().getTemplate().getSpec().getContainers().get(0).setEnv(existing); Service externalServiceName = Serialization.unmarshal(externalNameServiceStream, Service.class); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-istio/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/istio/Fabric8IstioIT.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-istio/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/istio/Fabric8IstioIT.java index efdb91bdb2..7e6cdf18ff 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-istio/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/istio/Fabric8IstioIT.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-istio/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/istio/Fabric8IstioIT.java @@ -106,8 +106,11 @@ void test() { WebClient client = builder().baseUrl("http://localhost/profiles").build(); @SuppressWarnings("unchecked") - List result = client.method(HttpMethod.GET).retrieve().bodyToMono(List.class).retryWhen(retrySpec()) - .block(); + List result = client.method(HttpMethod.GET) + .retrieve() + .bodyToMono(List.class) + .retryWhen(retrySpec()) + .block(); // istio profile is present Assertions.assertTrue(result.contains("istio")); @@ -144,9 +147,10 @@ private RetryBackoffSpec retrySpec() { private static String istioctlPodName() { try { return K3S - .execInContainer("sh", "-c", - "kubectl get pods -n istio-test -l app=istio-ctl -o=name --no-headers | tr -d '\n'") - .getStdout().split("/")[1]; + .execInContainer("sh", "-c", + "kubectl get pods -n istio-test -l app=istio-ctl -o=name --no-headers | tr -d '\n'") + .getStdout() + .split("/")[1]; } catch (Exception e) { throw new RuntimeException(e); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/BootstrapEnabledPollingReloadConfigMapMountDelegate.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/BootstrapEnabledPollingReloadConfigMapMountDelegate.java index 44625ed594..43dd539a98 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/BootstrapEnabledPollingReloadConfigMapMountDelegate.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/BootstrapEnabledPollingReloadConfigMapMountDelegate.java @@ -58,8 +58,11 @@ static void testPollingReloadConfigMapWithBootstrap(KubernetesClient client, Uti appLabelValue); // (3) WebClient webClient = TestUtil.builder().baseUrl("http://localhost/key").build(); - String result = webClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(TestUtil.retrySpec()).block(); + String result = webClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(TestUtil.retrySpec()) + .block(); // we first read the initial value from the configmap Assertions.assertEquals("as-mount-initial", result); @@ -71,8 +74,13 @@ static void testPollingReloadConfigMapWithBootstrap(KubernetesClient client, Uti configMap.setData(Map.of("application.properties", "from.properties.key=as-mount-changed")); client.configMaps().inNamespace("default").resource(configMap).createOrReplace(); - await().timeout(Duration.ofSeconds(360)).until(() -> webClient.method(HttpMethod.GET).retrieve() - .bodyToMono(String.class).retryWhen(TestUtil.retrySpec()).block().equals("as-mount-changed")); + await().timeout(Duration.ofSeconds(360)) + .until(() -> webClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(TestUtil.retrySpec()) + .block() + .equals("as-mount-changed")); } diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/ConfigMapMountPollingReloadDelegate.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/ConfigMapMountPollingReloadDelegate.java index 67555c43a5..3dc15e2cbb 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/ConfigMapMountPollingReloadDelegate.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/ConfigMapMountPollingReloadDelegate.java @@ -62,8 +62,11 @@ static void testConfigMapMountPollingReload(KubernetesClient client, Util util, appLabelValue); // (3) WebClient webClient = TestUtil.builder().baseUrl("http://localhost/key").build(); - String result = webClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(TestUtil.retrySpec()).block(); + String result = webClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(TestUtil.retrySpec()) + .block(); // we first read the initial value from the configmap Assertions.assertEquals("as-mount-initial", result); @@ -75,8 +78,13 @@ static void testConfigMapMountPollingReload(KubernetesClient client, Util util, configMap.setData(Map.of("application.properties", "from.properties.key=as-mount-changed")); client.configMaps().inNamespace("default").resource(configMap).createOrReplace(); - await().timeout(Duration.ofSeconds(360)).until(() -> webClient.method(HttpMethod.GET).retrieve() - .bodyToMono(String.class).retryWhen(TestUtil.retrySpec()).block().equals("as-mount-changed")); + await().timeout(Duration.ofSeconds(360)) + .until(() -> webClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(TestUtil.retrySpec()) + .block() + .equals("as-mount-changed")); } diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/DataChangesInConfigMapReloadDelegate.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/DataChangesInConfigMapReloadDelegate.java index f3d20d1672..26698fe617 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/DataChangesInConfigMapReloadDelegate.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/DataChangesInConfigMapReloadDelegate.java @@ -58,24 +58,34 @@ static void testDataChangesInConfigMap(KubernetesClient client, K3sContainer con "added secret informer for namespace", IMAGE_NAME); WebClient webClient = builder().baseUrl("http://localhost/" + LEFT_NAMESPACE).build(); - String result = webClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class).retryWhen(retrySpec()) - .block(); + String result = webClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); // we first read the initial value from the left-configmap Assertions.assertEquals("left-initial", result); // then deploy a new version of left-configmap, but without changing its data, // only add a label - ConfigMap configMap = new ConfigMapBuilder().withMetadata(new ObjectMetaBuilder() - .withLabels(Map.of("new-label", "abc")).withNamespace("left").withName("left-configmap").build()) - .withData(Map.of("left.value", "left-initial")).build(); + ConfigMap configMap = new ConfigMapBuilder() + .withMetadata(new ObjectMetaBuilder().withLabels(Map.of("new-label", "abc")) + .withNamespace("left") + .withName("left-configmap") + .build()) + .withData(Map.of("left.value", "left-initial")) + .build(); replaceConfigMap(client, configMap, "left"); await().pollInterval(Duration.ofSeconds(3)).atMost(Duration.ofSeconds(90)).until(() -> { WebClient innerWebClient = builder().baseUrl("http://localhost/" + LEFT_NAMESPACE).build(); - String innerResult = innerWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(retrySpec()).block(); + String innerResult = innerWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); return "left-initial".equals(innerResult); }); @@ -85,16 +95,22 @@ static void testDataChangesInConfigMap(KubernetesClient client, K3sContainer con // change data configMap = new ConfigMapBuilder() - .withMetadata(new ObjectMetaBuilder().withLabels(Map.of("new-label", "abc")).withNamespace("left") - .withName("left-configmap").build()) - .withData(Map.of("left.value", "left-after-change")).build(); + .withMetadata(new ObjectMetaBuilder().withLabels(Map.of("new-label", "abc")) + .withNamespace("left") + .withName("left-configmap") + .build()) + .withData(Map.of("left.value", "left-after-change")) + .build(); replaceConfigMap(client, configMap, "left"); await().pollInterval(Duration.ofSeconds(3)).atMost(Duration.ofSeconds(90)).until(() -> { WebClient innerWebClient = builder().baseUrl("http://localhost/" + LEFT_NAMESPACE).build(); - String innerResult = innerWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(retrySpec()).block(); + String innerResult = innerWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); return "left-after-change".equals(innerResult); }); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/Fabric8EventReloadIT.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/Fabric8EventReloadIT.java index 6309e280dc..780ad9b644 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/Fabric8EventReloadIT.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/Fabric8EventReloadIT.java @@ -103,22 +103,29 @@ void testInformFromOneNamespaceEventNotTriggered() { "added secret informer for namespace", IMAGE_NAME); WebClient webClient = TestUtil.builder().baseUrl("http://localhost/left").build(); - String result = webClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(TestUtil.retrySpec()).block(); + String result = webClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(TestUtil.retrySpec()) + .block(); // we first read the initial value from the left-configmap Assertions.assertEquals("left-initial", result); // then read the value from the right-configmap webClient = TestUtil.builder().baseUrl("http://localhost/right").build(); - result = webClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class).retryWhen(TestUtil.retrySpec()) - .block(); + result = webClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(TestUtil.retrySpec()) + .block(); Assertions.assertEquals("right-initial", result); // then deploy a new version of right-configmap ConfigMap rightConfigMapAfterChange = new ConfigMapBuilder() - .withMetadata(new ObjectMetaBuilder().withNamespace("right").withName("right-configmap").build()) - .withData(Map.of("right.value", "right-after-change")).build(); + .withMetadata(new ObjectMetaBuilder().withNamespace("right").withName("right-configmap").build()) + .withData(Map.of("right.value", "right-after-change")) + .build(); TestUtil.replaceConfigMap(client, rightConfigMapAfterChange, "right"); @@ -126,8 +133,11 @@ void testInformFromOneNamespaceEventNotTriggered() { WebClient finalWebClient = webClient; await().pollInterval(Duration.ofSeconds(1)).atMost(Duration.ofSeconds(30)).until(() -> { - String innerResult = finalWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(TestUtil.retrySpec()).block(); + String innerResult = finalWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(TestUtil.retrySpec()) + .block(); // left configmap has not changed, no restart of app has happened return "left-initial".equals(innerResult); }); @@ -160,22 +170,29 @@ void testInformFromOneNamespaceEventTriggered() { // read the value from the right-configmap WebClient webClient = TestUtil.builder().baseUrl("http://localhost/right").build(); - String result = webClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(TestUtil.retrySpec()).block(); + String result = webClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(TestUtil.retrySpec()) + .block(); Assertions.assertEquals("right-initial", result); // then deploy a new version of right-configmap ConfigMap rightConfigMapAfterChange = new ConfigMapBuilder() - .withMetadata(new ObjectMetaBuilder().withNamespace("right").withName("right-configmap").build()) - .withData(Map.of("right.value", "right-after-change")).build(); + .withMetadata(new ObjectMetaBuilder().withNamespace("right").withName("right-configmap").build()) + .withData(Map.of("right.value", "right-after-change")) + .build(); TestUtil.replaceConfigMap(client, rightConfigMapAfterChange, "right"); String[] resultAfterChange = new String[1]; await().pollInterval(Duration.ofSeconds(3)).atMost(Duration.ofSeconds(90)).until(() -> { WebClient innerWebClient = TestUtil.builder().baseUrl("http://localhost/right").build(); - String innerResult = innerWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(TestUtil.retrySpec()).block(); + String innerResult = innerWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(TestUtil.retrySpec()) + .block(); resultAfterChange[0] = innerResult; return innerResult != null; }); @@ -202,35 +219,45 @@ void testInform() { // read the initial value from the right-configmap WebClient rightWebClient = TestUtil.builder().baseUrl("http://localhost/right").build(); - String rightResult = rightWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(TestUtil.retrySpec()).block(); + String rightResult = rightWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(TestUtil.retrySpec()) + .block(); Assertions.assertEquals("right-initial", rightResult); // then read the initial value from the right-with-label-configmap WebClient rightWithLabelWebClient = TestUtil.builder().baseUrl("http://localhost/with-label").build(); - String rightWithLabelResult = rightWithLabelWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(TestUtil.retrySpec()).block(); + String rightWithLabelResult = rightWithLabelWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(TestUtil.retrySpec()) + .block(); Assertions.assertEquals("right-with-label-initial", rightWithLabelResult); // then deploy a new version of right-configmap ConfigMap rightConfigMapAfterChange = new ConfigMapBuilder() - .withMetadata(new ObjectMetaBuilder().withNamespace("right").withName("right-configmap").build()) - .withData(Map.of("right.value", "right-after-change")).build(); + .withMetadata(new ObjectMetaBuilder().withNamespace("right").withName("right-configmap").build()) + .withData(Map.of("right.value", "right-after-change")) + .build(); TestUtil.replaceConfigMap(client, rightConfigMapAfterChange, "right"); // nothing changes in our app, because we are watching only labeled configmaps await().pollInterval(Duration.ofSeconds(1)).atMost(Duration.ofSeconds(30)).until(() -> { - String innerRightResult = rightWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(TestUtil.retrySpec()).block(); + String innerRightResult = rightWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(TestUtil.retrySpec()) + .block(); return "right-initial".equals(innerRightResult); }); // then deploy a new version of right-with-label-configmap ConfigMap rightWithLabelConfigMapAfterChange = new ConfigMapBuilder() - .withMetadata( - new ObjectMetaBuilder().withNamespace("right").withName("right-configmap-with-label").build()) - .withData(Map.of("right.with.label.value", "right-with-label-after-change")).build(); + .withMetadata(new ObjectMetaBuilder().withNamespace("right").withName("right-configmap-with-label").build()) + .withData(Map.of("right.with.label.value", "right-with-label-after-change")) + .build(); TestUtil.replaceConfigMap(client, rightWithLabelConfigMapAfterChange, "right"); @@ -239,8 +266,11 @@ void testInform() { String[] resultAfterChange = new String[1]; await().pollInterval(Duration.ofSeconds(3)).atMost(Duration.ofSeconds(90)).until(() -> { WebClient innerWebClient = TestUtil.builder().baseUrl("http://localhost/with-label").build(); - String innerResult = innerWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(TestUtil.retrySpec()).block(); + String innerResult = innerWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(TestUtil.retrySpec()) + .block(); resultAfterChange[0] = innerResult; return innerResult != null; }); @@ -248,8 +278,11 @@ void testInform() { // right-configmap now will see the new value also, but only because the other // configmap has triggered the restart - rightResult = rightWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(TestUtil.retrySpec()).block(); + rightResult = rightWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(TestUtil.retrySpec()) + .block(); Assertions.assertEquals("right-after-change", rightResult); } @@ -273,22 +306,29 @@ void testInformFromOneNamespaceEventTriggeredSecretsDisabled() { // read the value from the right-configmap WebClient webClient = TestUtil.builder().baseUrl("http://localhost/right").build(); - String result = webClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(TestUtil.retrySpec()).block(); + String result = webClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(TestUtil.retrySpec()) + .block(); Assertions.assertEquals("right-initial", result); // then deploy a new version of right-configmap ConfigMap rightConfigMapAfterChange = new ConfigMapBuilder() - .withMetadata(new ObjectMetaBuilder().withNamespace("right").withName("right-configmap").build()) - .withData(Map.of("right.value", "right-after-change")).build(); + .withMetadata(new ObjectMetaBuilder().withNamespace("right").withName("right-configmap").build()) + .withData(Map.of("right.value", "right-after-change")) + .build(); TestUtil.replaceConfigMap(client, rightConfigMapAfterChange, "right"); String[] resultAfterChange = new String[1]; await().pollInterval(Duration.ofSeconds(3)).atMost(Duration.ofSeconds(90)).until(() -> { WebClient innerWebClient = TestUtil.builder().baseUrl("http://localhost/right").build(); - String innerResult = innerWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(TestUtil.retrySpec()).block(); + String innerResult = innerWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(TestUtil.retrySpec()) + .block(); resultAfterChange[0] = innerResult; return innerResult != null; }); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/SecretsEventsReloadDelegate.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/SecretsEventsReloadDelegate.java index 2e89605930..1bf56ab5a5 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/SecretsEventsReloadDelegate.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/SecretsEventsReloadDelegate.java @@ -56,22 +56,30 @@ static void testSecretReload(KubernetesClient client, K3sContainer container, St "added configmap informer for namespace", appLabelValue); WebClient webClient = builder().baseUrl("http://localhost/key-from-secret").build(); - String result = webClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class).retryWhen(retrySpec()) - .block(); + String result = webClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals("secret-initial", result); Secret secret = new SecretBuilder() - .withMetadata(new ObjectMetaBuilder().withLabels(Map.of("letter", "a")).withNamespace("default") - .withName("event-reload").build()) - .withData(Map.of("application.properties", - Base64.getEncoder().encodeToString("from.secret.properties.key=secret-initial".getBytes()))) - .build(); + .withMetadata(new ObjectMetaBuilder().withLabels(Map.of("letter", "a")) + .withNamespace("default") + .withName("event-reload") + .build()) + .withData(Map.of("application.properties", + Base64.getEncoder().encodeToString("from.secret.properties.key=secret-initial".getBytes()))) + .build(); client.secrets().inNamespace("default").resource(secret).createOrReplace(); await().pollInterval(Duration.ofSeconds(3)).atMost(Duration.ofSeconds(90)).until(() -> { WebClient innerWebClient = builder().baseUrl("http://localhost/key-from-secret").build(); - String innerResult = innerWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(retrySpec()).block(); + String innerResult = innerWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); return "secret-initial".equals(innerResult); }); @@ -80,18 +88,20 @@ static void testSecretReload(KubernetesClient client, K3sContainer container, St // change data secret = new SecretBuilder() - .withMetadata(new ObjectMetaBuilder().withNamespace("default").withName("event-reload").build()) - .withData(Map.of("application.properties", - Base64.getEncoder() - .encodeToString("from.secret.properties.key=secret-initial-changed".getBytes()))) - .build(); + .withMetadata(new ObjectMetaBuilder().withNamespace("default").withName("event-reload").build()) + .withData(Map.of("application.properties", + Base64.getEncoder().encodeToString("from.secret.properties.key=secret-initial-changed".getBytes()))) + .build(); client.secrets().inNamespace("default").resource(secret).createOrReplace(); await().pollInterval(Duration.ofSeconds(3)).atMost(Duration.ofSeconds(90)).until(() -> { WebClient innerWebClient = builder().baseUrl("http://localhost/key-from-secret").build(); - String innerResult = innerWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(retrySpec()).block(); + String innerResult = innerWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); return "secret-initial-changed".equals(innerResult); }); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/TestUtil.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/TestUtil.java index ac83723776..7ede854c6f 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/TestUtil.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/test/java/org/springframework/cloud/kubernetes/fabric8/client/reload/TestUtil.java @@ -356,9 +356,9 @@ static RetryBackoffSpec retrySpec() { static String logs(K3sContainer container, String appLabelValue) { try { String appPodName = container - .execInContainer("sh", "-c", - "kubectl get pods -l app=" + appLabelValue + " -o=name --no-headers | tr -d '\n'") - .getStdout(); + .execInContainer("sh", "-c", + "kubectl get pods -l app=" + appLabelValue + " -o=name --no-headers | tr -d '\n'") + .getStdout(); Container.ExecResult execResult = container.execInContainer("sh", "-c", "kubectl logs " + appPodName.trim()); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-catalog-watcher/src/test/java/org/springframework/cloud/kubernetes/k8s/client/catalog/watcher/KubernetesClientCatalogWatchIT.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-catalog-watcher/src/test/java/org/springframework/cloud/kubernetes/k8s/client/catalog/watcher/KubernetesClientCatalogWatchIT.java index 26e582ace1..26f1ba3eed 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-catalog-watcher/src/test/java/org/springframework/cloud/kubernetes/k8s/client/catalog/watcher/KubernetesClientCatalogWatchIT.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-catalog-watcher/src/test/java/org/springframework/cloud/kubernetes/k8s/client/catalog/watcher/KubernetesClientCatalogWatchIT.java @@ -151,8 +151,10 @@ private void test() { await().pollInterval(Duration.ofSeconds(1)).atMost(Duration.ofSeconds(240)).until(() -> { List result = (List) client.method(HttpMethod.GET) - .retrieve().bodyToMono(ParameterizedTypeReference.forType(resolvableType.getType())) - .retryWhen(retrySpec()).block(); + .retrieve() + .bodyToMono(ParameterizedTypeReference.forType(resolvableType.getType())) + .retryWhen(retrySpec()) + .block(); // we get 3 pods as input, but because they are sorted by name in the catalog // watcher implementation @@ -188,8 +190,10 @@ private void test() { await().pollInterval(Duration.ofSeconds(1)).atMost(Duration.ofSeconds(240)).until(() -> { List result = (List) client.method(HttpMethod.GET) - .retrieve().bodyToMono(ParameterizedTypeReference.forType(resolvableType.getType())) - .retryWhen(retrySpec()).block(); + .retrieve() + .bodyToMono(ParameterizedTypeReference.forType(resolvableType.getType())) + .retryWhen(retrySpec()) + .block(); // we need to get the event from KubernetesCatalogWatch, but that happens // on periodic bases. So in order to be sure we got the event we care about diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-catalog-watcher/src/test/java/org/springframework/cloud/kubernetes/k8s/client/catalog/watcher/KubernetesClientCatalogWatchNamespacesDelegate.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-catalog-watcher/src/test/java/org/springframework/cloud/kubernetes/k8s/client/catalog/watcher/KubernetesClientCatalogWatchNamespacesDelegate.java index 66283f7199..d13b5c6734 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-catalog-watcher/src/test/java/org/springframework/cloud/kubernetes/k8s/client/catalog/watcher/KubernetesClientCatalogWatchNamespacesDelegate.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-catalog-watcher/src/test/java/org/springframework/cloud/kubernetes/k8s/client/catalog/watcher/KubernetesClientCatalogWatchNamespacesDelegate.java @@ -87,8 +87,10 @@ private static void testForNamespacesFilter() { await().pollInterval(Duration.ofSeconds(1)).atMost(Duration.ofSeconds(240)).until(() -> { List result = (List) client.method(HttpMethod.GET) - .retrieve().bodyToMono(ParameterizedTypeReference.forType(resolvableType.getType())) - .retryWhen(retrySpec()).block(); + .retrieve() + .bodyToMono(ParameterizedTypeReference.forType(resolvableType.getType())) + .retryWhen(retrySpec()) + .block(); if (result != null) { // 2 from namespace-a, 2 from namespace-b @@ -114,7 +116,8 @@ private static void testForNamespacesFilter() { Assertions.assertTrue(resultFour.endpointName().contains("busybox")); List sorted = Arrays.stream(holder) - .sorted(Comparator.comparing(EndpointNameAndNamespace::namespace)).toList(); + .sorted(Comparator.comparing(EndpointNameAndNamespace::namespace)) + .toList(); Assertions.assertEquals(NAMESPACE_A, sorted.get(0).namespace()); Assertions.assertEquals(NAMESPACE_A, sorted.get(1).namespace()); @@ -127,8 +130,10 @@ private static void testForNamespacesFilter() { await().pollInterval(Duration.ofSeconds(1)).atMost(Duration.ofSeconds(240)).until(() -> { List result = (List) client.method(HttpMethod.GET) - .retrieve().bodyToMono(ParameterizedTypeReference.forType(resolvableType.getType())) - .retryWhen(retrySpec()).block(); + .retrieve() + .bodyToMono(ParameterizedTypeReference.forType(resolvableType.getType())) + .retryWhen(retrySpec()) + .block(); // there is no update to receive anymore, as there is nothing in namespacea // and namespaceb diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/ActuatorRefreshIT.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/ActuatorRefreshIT.java index 4237ab13e8..9e1119af98 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/ActuatorRefreshIT.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/ActuatorRefreshIT.java @@ -105,17 +105,20 @@ void after() { void testActuatorRefresh() { WireMock.configureFor(WIREMOCK_HOST, WIREMOCK_PORT); - await().timeout(Duration.ofSeconds(60)).ignoreException(SocketTimeoutException.class) - .until(() -> WireMock - .stubFor(WireMock.post(WireMock.urlEqualTo("/actuator/refresh")) - .willReturn(WireMock.aResponse().withBody("{}").withStatus(200))) - .getResponse().wasConfigured()); + await().timeout(Duration.ofSeconds(60)) + .ignoreException(SocketTimeoutException.class) + .until(() -> WireMock + .stubFor(WireMock.post(WireMock.urlEqualTo("/actuator/refresh")) + .willReturn(WireMock.aResponse().withBody("{}").withStatus(200))) + .getResponse() + .wasConfigured()); createConfigMap(); // Wait a bit before we verify - await().atMost(Duration.ofSeconds(30)).until( - () -> !WireMock.findAll(WireMock.postRequestedFor(WireMock.urlEqualTo("/actuator/refresh"))).isEmpty()); + await().atMost(Duration.ofSeconds(30)) + .until(() -> !WireMock.findAll(WireMock.postRequestedFor(WireMock.urlEqualTo("/actuator/refresh"))) + .isEmpty()); WireMock.verify(WireMock.postRequestedFor(WireMock.urlEqualTo("/actuator/refresh"))); deleteConfigMap(); @@ -134,16 +137,18 @@ void testActuatorRefreshReloadDisabled() { WireMock.configureFor(WIREMOCK_HOST, WIREMOCK_PORT); await().timeout(Duration.ofSeconds(60)) - .until(() -> WireMock - .stubFor(WireMock.post(WireMock.urlEqualTo("/actuator/refresh")) - .willReturn(WireMock.aResponse().withBody("{}").withStatus(200))) - .getResponse().wasConfigured()); + .until(() -> WireMock + .stubFor(WireMock.post(WireMock.urlEqualTo("/actuator/refresh")) + .willReturn(WireMock.aResponse().withBody("{}").withStatus(200))) + .getResponse() + .wasConfigured()); createConfigMap(); // Wait a bit before we verify - await().atMost(Duration.ofSeconds(30)).until( - () -> !WireMock.findAll(WireMock.postRequestedFor(WireMock.urlEqualTo("/actuator/refresh"))).isEmpty()); + await().atMost(Duration.ofSeconds(30)) + .until(() -> !WireMock.findAll(WireMock.postRequestedFor(WireMock.urlEqualTo("/actuator/refresh"))) + .isEmpty()); Commons.waitForLogStatement("creating NOOP strategy because reload is disabled", K3S, SPRING_CLOUD_K8S_CONFIG_WATCHER_APP_NAME); @@ -159,11 +164,11 @@ void testActuatorRefreshReloadDisabled() { private static void configWatcher(Phase phase) { V1ConfigMap configMap = (V1ConfigMap) util - .yaml("config-watcher/spring-cloud-kubernetes-configuration-watcher-configmap.yaml"); + .yaml("config-watcher/spring-cloud-kubernetes-configuration-watcher-configmap.yaml"); V1Deployment deployment = (V1Deployment) util - .yaml("config-watcher/spring-cloud-kubernetes-configuration-watcher-deployment.yaml"); + .yaml("config-watcher/spring-cloud-kubernetes-configuration-watcher-deployment.yaml"); V1Service service = (V1Service) util - .yaml("config-watcher/spring-cloud-kubernetes-configuration-watcher-service.yaml"); + .yaml("config-watcher/spring-cloud-kubernetes-configuration-watcher-service.yaml"); if (phase.equals(Phase.CREATE)) { util.createAndWait(NAMESPACE, configMap, null); @@ -178,21 +183,32 @@ private static void configWatcher(Phase phase) { // Create new configmap to trigger controller to signal app to refresh private void createConfigMap() { - V1ConfigMap configMap = new V1ConfigMapBuilder().editOrNewMetadata().withName("service-wiremock") - .addToLabels("spring.cloud.kubernetes.config", "true").endMetadata().addToData("foo", "bar").build(); + V1ConfigMap configMap = new V1ConfigMapBuilder().editOrNewMetadata() + .withName("service-wiremock") + .addToLabels("spring.cloud.kubernetes.config", "true") + .endMetadata() + .addToData("foo", "bar") + .build(); util.createAndWait(NAMESPACE, configMap, null); } private void deleteConfigMap() { - V1ConfigMap configMap = new V1ConfigMapBuilder().editOrNewMetadata().withName("service-wiremock") - .addToLabels("spring.cloud.kubernetes.config", "true").endMetadata().addToData("foo", "bar").build(); + V1ConfigMap configMap = new V1ConfigMapBuilder().editOrNewMetadata() + .withName("service-wiremock") + .addToLabels("spring.cloud.kubernetes.config", "true") + .endMetadata() + .addToData("foo", "bar") + .build(); util.deleteAndWait(NAMESPACE, configMap, null); } private String logs() { try { - String appPodName = K3S.execInContainer("sh", "-c", "kubectl get pods -l app=" - + SPRING_CLOUD_K8S_CONFIG_WATCHER_APP_NAME + " -o=name --no-headers | tr -d '\n'").getStdout(); + String appPodName = K3S + .execInContainer("sh", "-c", + "kubectl get pods -l app=" + SPRING_CLOUD_K8S_CONFIG_WATCHER_APP_NAME + + " -o=name --no-headers | tr -d '\n'") + .getStdout(); Container.ExecResult execResult = K3S.execInContainer("sh", "-c", "kubectl logs " + appPodName.trim()); return execResult.getStdout(); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/ActuatorRefreshMultipleNamespacesIT.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/ActuatorRefreshMultipleNamespacesIT.java index 08e1e6793d..22c8d0976b 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/ActuatorRefreshMultipleNamespacesIT.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-configuration-watcher/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/ActuatorRefreshMultipleNamespacesIT.java @@ -101,21 +101,30 @@ static void afterAll() throws Exception { void testConfigMapActuatorRefreshMultipleNamespaces() { WireMock.configureFor(WIREMOCK_HOST, WIREMOCK_PORT); await().timeout(Duration.ofSeconds(60)) - .until(() -> WireMock - .stubFor(WireMock.post(WireMock.urlEqualTo("/actuator/refresh")) - .willReturn(WireMock.aResponse().withBody("{}").withStatus(200))) - .getResponse().wasConfigured()); + .until(() -> WireMock + .stubFor(WireMock.post(WireMock.urlEqualTo("/actuator/refresh")) + .willReturn(WireMock.aResponse().withBody("{}").withStatus(200))) + .getResponse() + .wasConfigured()); // left-config-map V1ConfigMap leftConfigMap = new V1ConfigMapBuilder().editOrNewMetadata() - .withLabels(Map.of("spring.cloud.kubernetes.config", "true")).withName("service-wiremock") - .withNamespace(LEFT_NAMESPACE).endMetadata().addToData("color", "purple").build(); + .withLabels(Map.of("spring.cloud.kubernetes.config", "true")) + .withName("service-wiremock") + .withNamespace(LEFT_NAMESPACE) + .endMetadata() + .addToData("color", "purple") + .build(); util.createAndWait(LEFT_NAMESPACE, leftConfigMap, null); // right-config-map V1ConfigMap rightConfigMap = new V1ConfigMapBuilder().editOrNewMetadata() - .withLabels(Map.of("spring.cloud.kubernetes.config", "true")).withName("service-wiremock") - .withNamespace(RIGHT_NAMESPACE).endMetadata().addToData("color", "green").build(); + .withLabels(Map.of("spring.cloud.kubernetes.config", "true")) + .withName("service-wiremock") + .withNamespace(RIGHT_NAMESPACE) + .endMetadata() + .addToData("color", "green") + .build(); util.createAndWait(RIGHT_NAMESPACE, rightConfigMap, null); // comes from handler::onAdd (and as such from "onEvent") @@ -126,8 +135,9 @@ void testConfigMapActuatorRefreshMultipleNamespaces() { Commons.assertReloadLogStatements("ConfigMap service-wiremock was added in namespace right", "", "spring-cloud-kubernetes-configuration-watcher"); - await().atMost(Duration.ofSeconds(30)).until( - () -> !WireMock.findAll(WireMock.postRequestedFor(WireMock.urlEqualTo("/actuator/refresh"))).isEmpty()); + await().atMost(Duration.ofSeconds(30)) + .until(() -> !WireMock.findAll(WireMock.postRequestedFor(WireMock.urlEqualTo("/actuator/refresh"))) + .isEmpty()); WireMock.verify(WireMock.exactly(2), WireMock.postRequestedFor(WireMock.urlEqualTo("/actuator/refresh"))); testSecretActuatorRefreshMultipleNamespaces(); @@ -145,24 +155,32 @@ void testConfigMapActuatorRefreshMultipleNamespaces() { * */ void testSecretActuatorRefreshMultipleNamespaces() { - await().timeout(Duration.ofSeconds(60)).ignoreException(SocketTimeoutException.class) - .until(() -> WireMock - .stubFor(WireMock.post(WireMock.urlEqualTo("/actuator/refresh")) - .willReturn(WireMock.aResponse().withBody("{}").withStatus(200))) - .getResponse().wasConfigured()); + await().timeout(Duration.ofSeconds(60)) + .ignoreException(SocketTimeoutException.class) + .until(() -> WireMock + .stubFor(WireMock.post(WireMock.urlEqualTo("/actuator/refresh")) + .willReturn(WireMock.aResponse().withBody("{}").withStatus(200))) + .getResponse() + .wasConfigured()); // left-secret V1Secret leftSecret = new V1SecretBuilder().editOrNewMetadata() - .withLabels(Map.of("spring.cloud.kubernetes.secret", "true")).withName("service-wiremock") - .withNamespace(LEFT_NAMESPACE).endMetadata() - .addToData("color", Base64.getEncoder().encode("purple".getBytes(StandardCharsets.UTF_8))).build(); + .withLabels(Map.of("spring.cloud.kubernetes.secret", "true")) + .withName("service-wiremock") + .withNamespace(LEFT_NAMESPACE) + .endMetadata() + .addToData("color", Base64.getEncoder().encode("purple".getBytes(StandardCharsets.UTF_8))) + .build(); util.createAndWait(LEFT_NAMESPACE, null, leftSecret); // right-secret V1Secret rightSecret = new V1SecretBuilder().editOrNewMetadata() - .withLabels(Map.of("spring.cloud.kubernetes.secret", "true")).withName("service-wiremock") - .withNamespace(RIGHT_NAMESPACE).endMetadata() - .addToData("color", Base64.getEncoder().encode("green".getBytes(StandardCharsets.UTF_8))).build(); + .withLabels(Map.of("spring.cloud.kubernetes.secret", "true")) + .withName("service-wiremock") + .withNamespace(RIGHT_NAMESPACE) + .endMetadata() + .addToData("color", Base64.getEncoder().encode("green".getBytes(StandardCharsets.UTF_8))) + .build(); util.createAndWait(RIGHT_NAMESPACE, null, rightSecret); // comes from handler::onAdd (and as such from "onEvent") @@ -173,17 +191,18 @@ void testSecretActuatorRefreshMultipleNamespaces() { Commons.assertReloadLogStatements("Secret service-wiremock was added in namespace right", "", "spring-cloud-kubernetes-configuration-watcher"); - await().atMost(Duration.ofSeconds(30)).until( - () -> !WireMock.findAll(WireMock.postRequestedFor(WireMock.urlEqualTo("/actuator/refresh"))).isEmpty()); + await().atMost(Duration.ofSeconds(30)) + .until(() -> !WireMock.findAll(WireMock.postRequestedFor(WireMock.urlEqualTo("/actuator/refresh"))) + .isEmpty()); WireMock.verify(WireMock.exactly(4), WireMock.postRequestedFor(WireMock.urlEqualTo("/actuator/refresh"))); } private static void configWatcher(Phase phase) { V1ConfigMap configMap = (V1ConfigMap) util - .yaml("config-watcher/spring-cloud-kubernetes-configuration-watcher-configmap.yaml"); + .yaml("config-watcher/spring-cloud-kubernetes-configuration-watcher-configmap.yaml"); V1Deployment deployment = (V1Deployment) util - .yaml("config-watcher/spring-cloud-kubernetes-configuration-watcher-deployment.yaml"); + .yaml("config-watcher/spring-cloud-kubernetes-configuration-watcher-deployment.yaml"); List envVars = List.of( new V1EnvVar().name("SPRING_CLOUD_KUBERNETES_RELOAD_NAMESPACES_0").value(LEFT_NAMESPACE), @@ -193,7 +212,7 @@ private static void configWatcher(Phase phase) { deployment.getSpec().getTemplate().getSpec().getContainers().get(0).setEnv(envVars); V1Service service = (V1Service) util - .yaml("config-watcher/spring-cloud-kubernetes-configuration-watcher-service.yaml"); + .yaml("config-watcher/spring-cloud-kubernetes-configuration-watcher-service.yaml"); if (phase.equals(Phase.CREATE)) { util.createAndWait(DEFAULT_NAMESPACE, configMap, null); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery-server/src/test/java/org/springframework/cloud/kubernetes/discoveryclient/it/DiscoveryClientFilterNamespaceDelegate.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery-server/src/test/java/org/springframework/cloud/kubernetes/discoveryclient/it/DiscoveryClientFilterNamespaceDelegate.java index b4b265eee6..2cb325e611 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery-server/src/test/java/org/springframework/cloud/kubernetes/discoveryclient/it/DiscoveryClientFilterNamespaceDelegate.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery-server/src/test/java/org/springframework/cloud/kubernetes/discoveryclient/it/DiscoveryClientFilterNamespaceDelegate.java @@ -55,34 +55,48 @@ private static void testLoadBalancer() { WebClient.Builder builder = builder(); WebClient serviceClient = builder.baseUrl("http://localhost:80/discoveryclient-it/services").build(); - String result = serviceClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class).retryWhen(retrySpec()) - .block(); + String result = serviceClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); - Assertions.assertThat(BASIC_JSON_TESTER.from(result)).extractingJsonPathArrayValue("$") - .contains("service-wiremock"); + Assertions.assertThat(BASIC_JSON_TESTER.from(result)) + .extractingJsonPathArrayValue("$") + .contains("service-wiremock"); // ServiceInstance WebClient serviceInstanceClient = builder - .baseUrl("http://localhost:80/discoveryclient-it/service/service-wiremock").build(); - String serviceInstances = serviceInstanceClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(retrySpec()).block(); - - Assertions.assertThat(BASIC_JSON_TESTER.from(serviceInstances)).extractingJsonPathStringValue("$.[0].serviceId") - .isEqualTo("service-wiremock"); - - Assertions.assertThat(BASIC_JSON_TESTER.from(serviceInstances)).extractingJsonPathStringValue("$.[0].namespace") - .isEqualTo("left"); + .baseUrl("http://localhost:80/discoveryclient-it/service/service-wiremock") + .build(); + String serviceInstances = serviceInstanceClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); + + Assertions.assertThat(BASIC_JSON_TESTER.from(serviceInstances)) + .extractingJsonPathStringValue("$.[0].serviceId") + .isEqualTo("service-wiremock"); + + Assertions.assertThat(BASIC_JSON_TESTER.from(serviceInstances)) + .extractingJsonPathStringValue("$.[0].namespace") + .isEqualTo("left"); } private static void testHealth() { WebClient.Builder builder = builder(); WebClient serviceClient = builder.baseUrl("http://localhost:80/discoveryclient-it/actuator/health").build(); - String health = serviceClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class).retryWhen(retrySpec()) - .block(); + String health = serviceClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); Assertions.assertThat(BASIC_JSON_TESTER.from(health)) - .extractingJsonPathStringValue("$.components.discoveryComposite.status").isEqualTo("UP"); + .extractingJsonPathStringValue("$.components.discoveryComposite.status") + .isEqualTo("UP"); } private static void testForHeartbeat(K3sContainer container) { @@ -101,24 +115,27 @@ private static void testForHeartbeat(K3sContainer container) { // 3. heartbeat listener message WebClient.Builder builder = builder(); WebClient client = builder.baseUrl("http://localhost:80/discoveryclient-it/state").build(); - String result = client.method(HttpMethod.GET).retrieve().bodyToMono(String.class).retryWhen(retrySpec()) - .block(); + String result = client.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); Condition> wireMockService = new Condition<>( map -> map.entrySet().stream().anyMatch(en -> en.getValue().contains("service-wiremock-deployment")), ""); - Condition> discoveryServerService = new Condition<>( - map -> map.entrySet().stream() - .anyMatch(en -> en.getValue().contains("spring-cloud-kubernetes-k8s-client-discovery-server")), - ""); + Condition> discoveryServerService = new Condition<>(map -> map.entrySet() + .stream() + .anyMatch(en -> en.getValue().contains("spring-cloud-kubernetes-k8s-client-discovery-server")), ""); Assertions.assertThat(BASIC_JSON_TESTER.from(result)) - .>extractingJsonPathArrayValue("$.[*]").areAtLeastOne(wireMockService); + .>extractingJsonPathArrayValue("$.[*]") + .areAtLeastOne(wireMockService); Assertions.assertThat(BASIC_JSON_TESTER.from(result)) - .>extractingJsonPathArrayValue("$.[*]") - .areAtLeastOne(discoveryServerService); + .>extractingJsonPathArrayValue("$.[*]") + .areAtLeastOne(discoveryServerService); } private static WebClient.Builder builder() { diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery-server/src/test/java/org/springframework/cloud/kubernetes/discoveryclient/it/DiscoveryClientIT.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery-server/src/test/java/org/springframework/cloud/kubernetes/discoveryclient/it/DiscoveryClientIT.java index b2987a8e7a..92806f1c6d 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery-server/src/test/java/org/springframework/cloud/kubernetes/discoveryclient/it/DiscoveryClientIT.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery-server/src/test/java/org/springframework/cloud/kubernetes/discoveryclient/it/DiscoveryClientIT.java @@ -164,7 +164,7 @@ static void beforeAll() throws Exception { util.createNamespace(NAMESPACE_RIGHT); clusterRoleBinding = (V1ClusterRoleBinding) util - .yaml("namespace-filter/cluster-admin-serviceaccount-role.yaml"); + .yaml("namespace-filter/cluster-admin-serviceaccount-role.yaml"); rbacApi.createClusterRoleBinding(clusterRoleBinding, null, null, null, null); util.wiremock(NAMESPACE_LEFT, "/wiremock-" + NAMESPACE_LEFT, Phase.CREATE, false); @@ -210,11 +210,15 @@ private void testLoadBalancer() { WebClient.Builder builder = builder(); WebClient serviceClient = builder.baseUrl("http://localhost:80/discoveryclient-it/services").build(); - String result = serviceClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class).retryWhen(retrySpec()) - .block(); + String result = serviceClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); - Assertions.assertThat(BASIC_JSON_TESTER.from(result)).extractingJsonPathArrayValue("$") - .contains("spring-cloud-kubernetes-discoveryserver"); + Assertions.assertThat(BASIC_JSON_TESTER.from(result)) + .extractingJsonPathArrayValue("$") + .contains("spring-cloud-kubernetes-discoveryserver"); // since 'spring.cloud.kubernetes.http.discovery.client.catalog.watcher.enabled' // is false by default, we will not receive any heartbeat events, @@ -226,8 +230,11 @@ private void testLoadBalancer() { WebClient.Builder stateBuilder = builder(); WebClient client = stateBuilder.baseUrl("http://localhost:80/discoveryclient-it/state").build(); - String stateResult = client.method(HttpMethod.GET).retrieve().bodyToMono(String.class).retryWhen(retrySpec()) - .block(); + String stateResult = client.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); Assertions.assertThat(BASIC_JSON_TESTER.from(stateResult)).isEqualTo("[]"); try { @@ -237,8 +244,11 @@ private void testLoadBalancer() { throw new RuntimeException(e); } - String stateResultAfter10Seconds = client.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(retrySpec()).block(); + String stateResultAfter10Seconds = client.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); Assertions.assertThat(BASIC_JSON_TESTER.from(stateResultAfter10Seconds)).isEqualTo("[]"); } @@ -249,21 +259,29 @@ void testHealth() { WebClient client = clientBuilder.baseUrl("http://localhost:80/discoveryclient-it/actuator/health").build(); WebClient server = serverBuilder.baseUrl("http://localhost:80/actuator/health").build(); - String clientHealth = client.method(HttpMethod.GET).retrieve().bodyToMono(String.class).retryWhen(retrySpec()) - .block(); - String serverHealth = server.method(HttpMethod.GET).retrieve().bodyToMono(String.class).retryWhen(retrySpec()) - .block(); + String clientHealth = client.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); + String serverHealth = server.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); Assertions.assertThat(BASIC_JSON_TESTER.from(clientHealth)) - .extractingJsonPathStringValue("$.components.discoveryComposite.status").isEqualTo("UP"); + .extractingJsonPathStringValue("$.components.discoveryComposite.status") + .isEqualTo("UP"); Assertions.assertThat(BASIC_JSON_TESTER.from(serverHealth)) - .extractingJsonPathStringValue("$.components.kubernetes.status").isEqualTo("UP"); + .extractingJsonPathStringValue("$.components.kubernetes.status") + .isEqualTo("UP"); } private static void discoveryClient(Phase phase) { V1Deployment deployment = (V1Deployment) util - .yaml("client/spring-cloud-kubernetes-discoveryclient-it-deployment.yaml"); + .yaml("client/spring-cloud-kubernetes-discoveryclient-it-deployment.yaml"); V1Service service = (V1Service) util.yaml("client/spring-cloud-kubernetes-discoveryclient-it-service.yaml"); V1Ingress ingress = (V1Ingress) util.yaml("ingress.yaml"); @@ -277,7 +295,7 @@ private static void discoveryClient(Phase phase) { private static void discoveryServer(Phase phase) { V1Deployment deployment = (V1Deployment) util - .yaml("server/spring-cloud-kubernetes-discoveryserver-deployment.yaml"); + .yaml("server/spring-cloud-kubernetes-discoveryserver-deployment.yaml"); V1Service service = (V1Service) util.yaml("server/spring-cloud-kubernetes-discoveryserver-service.yaml"); if (phase.equals(Phase.CREATE)) { diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoveryClientIT.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoveryClientIT.java index 02c0bc7178..9d64b02ac2 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoveryClientIT.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoveryClientIT.java @@ -108,7 +108,8 @@ void testSimple() throws Exception { // find both pods String[] both = K3S.execInContainer("sh", "-c", "kubectl get pods -l app=busybox -o=name --no-headers") - .getStdout().split("\n"); + .getStdout() + .split("\n"); // add a label to first pod K3S.execInContainer("sh", "-c", "kubectl label pods " + both[0].split("/")[1] + " custom-label=custom-label-value"); @@ -120,10 +121,13 @@ void testSimple() throws Exception { WebClient servicesClient = builder().baseUrl("http://localhost/services").build(); - List servicesResult = servicesClient.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { + List servicesResult = servicesClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(servicesResult.size(), 4); Assertions.assertTrue(servicesResult.contains("kubernetes")); @@ -132,12 +136,16 @@ void testSimple() throws Exception { Assertions.assertTrue(servicesResult.contains("external-name-service")); WebClient ourServiceClient = builder() - .baseUrl("http://localhost/service-instances/spring-cloud-kubernetes-k8s-client-discovery").build(); + .baseUrl("http://localhost/service-instances/spring-cloud-kubernetes-k8s-client-discovery") + .build(); - List ourServiceInstances = ourServiceClient.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { + List ourServiceInstances = ourServiceClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(ourServiceInstances.size(), 1); @@ -152,42 +160,58 @@ void testSimple() throws Exception { Assertions.assertEquals(serviceInstance.getNamespace(), "default"); WebClient busyBoxServiceClient = builder().baseUrl("http://localhost/service-instances/busybox-service") - .build(); + .build(); List busyBoxServiceInstances = busyBoxServiceClient.method(HttpMethod.GET) - .retrieve().bodyToMono(new ParameterizedTypeReference>() { + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(busyBoxServiceInstances.size(), 2); DefaultKubernetesServiceInstance withCustomLabel = busyBoxServiceInstances.stream() - .filter(x -> x.podMetadata().getOrDefault("annotations", Map.of()).isEmpty()).toList().get(0); + .filter(x -> x.podMetadata().getOrDefault("annotations", Map.of()).isEmpty()) + .toList() + .get(0); Assertions.assertEquals(withCustomLabel.getServiceId(), "busybox-service"); Assertions.assertNotNull(withCustomLabel.getInstanceId()); Assertions.assertNotNull(withCustomLabel.getHost()); Assertions.assertEquals(withCustomLabel.getMetadata(), Map.of("k8s_namespace", "default", "type", "ClusterIP", "port.busybox-port", "80")); - Assertions.assertTrue(withCustomLabel.podMetadata().get("labels").entrySet().stream() - .anyMatch(x -> x.getKey().equals("custom-label") && x.getValue().equals("custom-label-value"))); + Assertions.assertTrue(withCustomLabel.podMetadata() + .get("labels") + .entrySet() + .stream() + .anyMatch(x -> x.getKey().equals("custom-label") && x.getValue().equals("custom-label-value"))); DefaultKubernetesServiceInstance withCustomAnnotation = busyBoxServiceInstances.stream() - .filter(x -> !x.podMetadata().getOrDefault("annotations", Map.of()).isEmpty()).toList().get(0); + .filter(x -> !x.podMetadata().getOrDefault("annotations", Map.of()).isEmpty()) + .toList() + .get(0); Assertions.assertEquals(withCustomAnnotation.getServiceId(), "busybox-service"); Assertions.assertNotNull(withCustomAnnotation.getInstanceId()); Assertions.assertNotNull(withCustomAnnotation.getHost()); Assertions.assertEquals(withCustomAnnotation.getMetadata(), Map.of("k8s_namespace", "default", "type", "ClusterIP", "port.busybox-port", "80")); - Assertions.assertTrue(withCustomAnnotation.podMetadata().get("annotations").entrySet().stream().anyMatch( - x -> x.getKey().equals("custom-annotation") && x.getValue().equals("custom-annotation-value"))); + Assertions.assertTrue(withCustomAnnotation.podMetadata() + .get("annotations") + .entrySet() + .stream() + .anyMatch(x -> x.getKey().equals("custom-annotation") && x.getValue().equals("custom-annotation-value"))); // enforces this : // https://github.com/spring-cloud/spring-cloud-kubernetes/issues/1286 WebClient clientForNonExistentService = builder().baseUrl("http://localhost/service-instances/non-existent") - .build(); + .build(); List resultForNonExistentService = clientForNonExistentService.method(HttpMethod.GET) - .retrieve().bodyToMono(new ParameterizedTypeReference>() { + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(resultForNonExistentService.size(), 0); @@ -220,10 +244,13 @@ void testAllNamespaces() { Commons.waitForLogStatement("serviceSharedInformer will use all-namespaces", K3S, IMAGE_NAME); WebClient servicesClient = builder().baseUrl("http://localhost/services").build(); - List servicesResult = servicesClient.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { + List servicesResult = servicesClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(servicesResult.size(), 8); Assertions.assertTrue(servicesResult.contains("kubernetes")); Assertions.assertTrue(servicesResult.contains("spring-cloud-kubernetes-k8s-client-discovery")); @@ -234,21 +261,27 @@ void testAllNamespaces() { // enforces this : // https://github.com/spring-cloud/spring-cloud-kubernetes/issues/1286 WebClient clientForNonExistentService = builder().baseUrl("http://localhost/service-instances/non-existent") - .build(); + .build(); List resultForNonExistentService = clientForNonExistentService.method(HttpMethod.GET) - .retrieve().bodyToMono(new ParameterizedTypeReference>() { + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(resultForNonExistentService.size(), 0); // test ExternalName fields WebClient externalNameClient = builder().baseUrl("http://localhost/service-instances/external-name-service") - .build(); + .build(); List externalNameServices = externalNameClient.method(HttpMethod.GET) - .retrieve().bodyToMono(new ParameterizedTypeReference>() { + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); DefaultKubernetesServiceInstance externalNameService = externalNameServices.get(0); Assertions.assertNotNull(externalNameService.getInstanceId()); Assertions.assertEquals(externalNameService.getHost(), "spring.io"); @@ -290,20 +323,26 @@ void testSpecificNamespace() { Commons.waitForLogStatement("registering lister (for endpoints) in namespace : a", K3S, IMAGE_NAME); WebClient servicesClient = builder().baseUrl("http://localhost/services").build(); - List servicesResult = servicesClient.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { + List servicesResult = servicesClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(servicesResult.size(), 1); Assertions.assertTrue(servicesResult.contains("service-wiremock")); WebClient wiremockInNamespaceAClient = builder().baseUrl("http://localhost/service-instances/service-wiremock") - .build(); + .build(); List wiremockInNamespaceA = wiremockInNamespaceAClient.method(HttpMethod.GET) - .retrieve().bodyToMono(new ParameterizedTypeReference>() { + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(wiremockInNamespaceA.size(), 1); @@ -313,11 +352,14 @@ void testSpecificNamespace() { // enforces this : // https://github.com/spring-cloud/spring-cloud-kubernetes/issues/1286 WebClient clientForNonExistentService = builder().baseUrl("http://localhost/service-instances/non-existent") - .build(); + .build(); List resultForNonExistentService = clientForNonExistentService.method(HttpMethod.GET) - .retrieve().bodyToMono(new ParameterizedTypeReference>() { + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(resultForNonExistentService.size(), 0); @@ -420,20 +462,24 @@ private static void manifests(Phase phase) { List envVars = new ArrayList<>( Optional.ofNullable(deployment.getSpec().getTemplate().getSpec().getContainers().get(0).getEnv()) - .orElse(List.of())); + .orElse(List.of())); V1EnvVar debugLevel = new V1EnvVar() - .name("LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_CLOUD_KUBERNETES_CLIENT_DISCOVERY").value("DEBUG"); + .name("LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_CLOUD_KUBERNETES_CLIENT_DISCOVERY") + .value("DEBUG"); V1EnvVar commonsLevel = new V1EnvVar() - .name("LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_CLOUD_KUBERNETES_COMMONS_DISCOVERY").value("DEBUG"); + .name("LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_CLOUD_KUBERNETES_COMMONS_DISCOVERY") + .value("DEBUG"); V1EnvVar debugLevelForClient = new V1EnvVar() - .name("LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_CLOUD_KUBERNETES_CLIENT").value("DEBUG"); + .name("LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_CLOUD_KUBERNETES_CLIENT") + .value("DEBUG"); V1EnvVar addLabels = new V1EnvVar().name("SPRING_CLOUD_KUBERNETES_DISCOVERY_METADATA_ADDPODLABELS") - .value("TRUE"); + .value("TRUE"); V1EnvVar addAnnotations = new V1EnvVar() - .name("SPRING_CLOUD_KUBERNETES_DISCOVERY_METADATA_ADDPODANNOTATIONS").value("TRUE"); + .name("SPRING_CLOUD_KUBERNETES_DISCOVERY_METADATA_ADDPODANNOTATIONS") + .value("TRUE"); envVars.add(debugLevel); envVars.add(debugLevelForClient); @@ -459,9 +505,10 @@ private RetryBackoffSpec retrySpec() { private void assertServicePresentInNamespaces(List namespaces, String value, String serviceName) { namespaces.forEach(x -> { try { - String service = K3S.execInContainer("sh", "-c", - "kubectl get services -n " + x + " -l app=" + value + " -o=name --no-headers | tr -d '\n'") - .getStdout(); + String service = K3S + .execInContainer("sh", "-c", + "kubectl get services -n " + x + " -l app=" + value + " -o=name --no-headers | tr -d '\n'") + .getStdout(); Assertions.assertEquals(service, "service/" + serviceName); } catch (Exception e) { diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoveryFilterITDelegate.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoveryFilterITDelegate.java index 5e6c6f4bc9..eee7807ff5 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoveryFilterITDelegate.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoveryFilterITDelegate.java @@ -61,17 +61,23 @@ void filterMatchesOneNamespaceViaThePredicate(Util util) { WebClient clientServices = builder().baseUrl("http://localhost/services").build(); @SuppressWarnings("unchecked") - List services = (List) clientServices.method(HttpMethod.GET).retrieve().bodyToMono(List.class) - .retryWhen(retrySpec()).block(); + List services = (List) clientServices.method(HttpMethod.GET) + .retrieve() + .bodyToMono(List.class) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(services.size(), 1); Assertions.assertTrue(services.contains("service-wiremock")); WebClient client = builder().baseUrl("http://localhost/service-instances/service-wiremock").build(); - List serviceInstances = client.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { + List serviceInstances = client.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(serviceInstances.size(), 1); @@ -103,21 +109,28 @@ void filterMatchesBothNamespacesViaThePredicate() { WebClient clientServices = builder().baseUrl("http://localhost/services").build(); @SuppressWarnings("unchecked") - List services = (List) clientServices.method(HttpMethod.GET).retrieve().bodyToMono(List.class) - .retryWhen(retrySpec()).block(); + List services = (List) clientServices.method(HttpMethod.GET) + .retrieve() + .bodyToMono(List.class) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(services.size(), 1); Assertions.assertTrue(services.contains("service-wiremock")); WebClient client = builder().baseUrl("http://localhost/service-instances/service-wiremock").build(); - List serviceInstances = client.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { + List serviceInstances = client.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(serviceInstances.size(), 2); List sorted = serviceInstances.stream() - .sorted(Comparator.comparing(DefaultKubernetesServiceInstance::getNamespace)).toList(); + .sorted(Comparator.comparing(DefaultKubernetesServiceInstance::getNamespace)) + .toList(); DefaultKubernetesServiceInstance first = sorted.get(0); Assertions.assertEquals(first.getServiceId(), "service-wiremock"); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoveryHealthITDelegate.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoveryHealthITDelegate.java index f38f2f2080..8d11b5a29e 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoveryHealthITDelegate.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoveryHealthITDelegate.java @@ -74,20 +74,24 @@ void testBlockingConfiguration(K3sContainer container) { WebClient healthClient = builder().baseUrl("http://localhost/actuator/health").build(); - String healthResult = healthClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(retrySpec()).block(); + String healthResult = healthClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathStringValue("$.components.discoveryComposite.status").isEqualTo("UP"); + .extractingJsonPathStringValue("$.components.discoveryComposite.status") + .isEqualTo("UP"); - Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)).extractingJsonPathStringValue(BLOCKING_STATUS) - .isEqualTo("UP"); + Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) + .extractingJsonPathStringValue(BLOCKING_STATUS) + .isEqualTo("UP"); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathArrayValue( - "$.components.discoveryComposite.components.discoveryClient.details.services") - .containsExactlyInAnyOrder("spring-cloud-kubernetes-k8s-client-discovery", "kubernetes", - "external-name-service"); + .extractingJsonPathArrayValue("$.components.discoveryComposite.components.discoveryClient.details.services") + .containsExactlyInAnyOrder("spring-cloud-kubernetes-k8s-client-discovery", "kubernetes", + "external-name-service"); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)).doesNotHaveJsonPath(REACTIVE_STATUS); @@ -113,19 +117,25 @@ void testReactiveConfiguration(K3sContainer container) { WebClient healthClient = builder().baseUrl("http://localhost/actuator/health").build(); - String healthResult = healthClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(retrySpec()).block(); + String healthResult = healthClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathStringValue("$.components.reactiveDiscoveryClients.status").isEqualTo("UP"); + .extractingJsonPathStringValue("$.components.reactiveDiscoveryClients.status") + .isEqualTo("UP"); - Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)).extractingJsonPathStringValue(REACTIVE_STATUS) - .isEqualTo("UP"); + Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) + .extractingJsonPathStringValue(REACTIVE_STATUS) + .isEqualTo("UP"); - Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)).extractingJsonPathArrayValue( - "$.components.reactiveDiscoveryClients.components.['Kubernetes Reactive Discovery Client'].details.services") - .containsExactlyInAnyOrder("spring-cloud-kubernetes-k8s-client-discovery", "kubernetes", - "external-name-service"); + Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) + .extractingJsonPathArrayValue( + "$.components.reactiveDiscoveryClients.components.['Kubernetes Reactive Discovery Client'].details.services") + .containsExactlyInAnyOrder("spring-cloud-kubernetes-k8s-client-discovery", "kubernetes", + "external-name-service"); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)).doesNotHaveJsonPath(BLOCKING_STATUS); @@ -133,9 +143,12 @@ void testReactiveConfiguration(K3sContainer container) { WebClient servicesClient = builder().baseUrl("http://localhost/reactive/services").build(); - List servicesResult = servicesClient.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + List servicesResult = servicesClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertThat(servicesResult).contains("spring-cloud-kubernetes-k8s-client-discovery"); Assertions.assertThat(servicesResult).contains("kubernetes"); @@ -158,35 +171,44 @@ void testDefaultConfiguration(K3sContainer container) { WebClient healthClient = builder().baseUrl("http://localhost/actuator/health").build(); WebClient infoClient = builder().baseUrl("http://localhost/actuator/info").build(); - String healthResult = healthClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(retrySpec()).block(); - String infoResult = infoClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class).retryWhen(retrySpec()) - .block(); + String healthResult = healthClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); + String infoResult = infoClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathStringValue("$.components.discoveryComposite.status").isEqualTo("UP"); + .extractingJsonPathStringValue("$.components.discoveryComposite.status") + .isEqualTo("UP"); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathStringValue("$.components.discoveryComposite.components.discoveryClient.status") - .isEqualTo("UP"); + .extractingJsonPathStringValue("$.components.discoveryComposite.components.discoveryClient.status") + .isEqualTo("UP"); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathArrayValue( - "$.components.discoveryComposite.components.discoveryClient.details.services") - .containsExactlyInAnyOrder("spring-cloud-kubernetes-k8s-client-discovery", "kubernetes", - "external-name-service"); + .extractingJsonPathArrayValue("$.components.discoveryComposite.components.discoveryClient.details.services") + .containsExactlyInAnyOrder("spring-cloud-kubernetes-k8s-client-discovery", "kubernetes", + "external-name-service"); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathStringValue("$.components.reactiveDiscoveryClients.status").isEqualTo("UP"); + .extractingJsonPathStringValue("$.components.reactiveDiscoveryClients.status") + .isEqualTo("UP"); - Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)).extractingJsonPathStringValue( - "$.components.reactiveDiscoveryClients.components.['Kubernetes Reactive Discovery Client'].status") - .isEqualTo("UP"); + Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) + .extractingJsonPathStringValue( + "$.components.reactiveDiscoveryClients.components.['Kubernetes Reactive Discovery Client'].status") + .isEqualTo("UP"); - Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)).extractingJsonPathArrayValue( - "$.components.reactiveDiscoveryClients.components.['Kubernetes Reactive Discovery Client'].details.services") - .containsExactlyInAnyOrder("spring-cloud-kubernetes-k8s-client-discovery", "kubernetes", - "external-name-service"); + Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) + .extractingJsonPathArrayValue( + "$.components.reactiveDiscoveryClients.components.['Kubernetes Reactive Discovery Client'].details.services") + .containsExactlyInAnyOrder("spring-cloud-kubernetes-k8s-client-discovery", "kubernetes", + "external-name-service"); // assert health/info also assertHealth(healthResult); @@ -195,55 +217,70 @@ void testDefaultConfiguration(K3sContainer container) { private void assertHealth(String healthResult) { Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathStringValue("$.components.kubernetes.status").isEqualTo("UP"); + .extractingJsonPathStringValue("$.components.kubernetes.status") + .isEqualTo("UP"); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathStringValue("$.components.kubernetes.details.hostIp").isNotEmpty(); + .extractingJsonPathStringValue("$.components.kubernetes.details.hostIp") + .isNotEmpty(); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathBooleanValue("$.components.kubernetes.details.inside").isEqualTo(true); + .extractingJsonPathBooleanValue("$.components.kubernetes.details.inside") + .isEqualTo(true); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathStringValue("$.components.kubernetes.details.labels.app") - .isEqualTo("spring-cloud-kubernetes-k8s-client-discovery"); + .extractingJsonPathStringValue("$.components.kubernetes.details.labels.app") + .isEqualTo("spring-cloud-kubernetes-k8s-client-discovery"); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathStringValue("$.components.kubernetes.details.namespace").isNotEmpty(); + .extractingJsonPathStringValue("$.components.kubernetes.details.namespace") + .isNotEmpty(); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathStringValue("$.components.kubernetes.details.nodeName").isNotEmpty(); + .extractingJsonPathStringValue("$.components.kubernetes.details.nodeName") + .isNotEmpty(); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathStringValue("$.components.kubernetes.details.podIp").isNotEmpty(); + .extractingJsonPathStringValue("$.components.kubernetes.details.podIp") + .isNotEmpty(); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathStringValue("$.components.kubernetes.details.podName").isNotEmpty(); + .extractingJsonPathStringValue("$.components.kubernetes.details.podName") + .isNotEmpty(); Assertions.assertThat(BASIC_JSON_TESTER.from(healthResult)) - .extractingJsonPathStringValue("$.components.kubernetes.details.serviceAccount").isNotEmpty(); + .extractingJsonPathStringValue("$.components.kubernetes.details.serviceAccount") + .isNotEmpty(); } private void assertInfo(String infoResult) { - Assertions.assertThat(BASIC_JSON_TESTER.from(infoResult)).extractingJsonPathStringValue("$.kubernetes.hostIp") - .isNotEmpty(); + Assertions.assertThat(BASIC_JSON_TESTER.from(infoResult)) + .extractingJsonPathStringValue("$.kubernetes.hostIp") + .isNotEmpty(); - Assertions.assertThat(BASIC_JSON_TESTER.from(infoResult)).extractingJsonPathBooleanValue("$.kubernetes.inside") - .isEqualTo(true); + Assertions.assertThat(BASIC_JSON_TESTER.from(infoResult)) + .extractingJsonPathBooleanValue("$.kubernetes.inside") + .isEqualTo(true); Assertions.assertThat(BASIC_JSON_TESTER.from(infoResult)) - .extractingJsonPathStringValue("$.kubernetes.namespace").isNotEmpty(); + .extractingJsonPathStringValue("$.kubernetes.namespace") + .isNotEmpty(); - Assertions.assertThat(BASIC_JSON_TESTER.from(infoResult)).extractingJsonPathStringValue("$.kubernetes.nodeName") - .isNotEmpty(); + Assertions.assertThat(BASIC_JSON_TESTER.from(infoResult)) + .extractingJsonPathStringValue("$.kubernetes.nodeName") + .isNotEmpty(); - Assertions.assertThat(BASIC_JSON_TESTER.from(infoResult)).extractingJsonPathStringValue("$.kubernetes.podIp") - .isNotEmpty(); + Assertions.assertThat(BASIC_JSON_TESTER.from(infoResult)) + .extractingJsonPathStringValue("$.kubernetes.podIp") + .isNotEmpty(); - Assertions.assertThat(BASIC_JSON_TESTER.from(infoResult)).extractingJsonPathStringValue("$.kubernetes.podName") - .isNotEmpty(); + Assertions.assertThat(BASIC_JSON_TESTER.from(infoResult)) + .extractingJsonPathStringValue("$.kubernetes.podName") + .isNotEmpty(); Assertions.assertThat(BASIC_JSON_TESTER.from(infoResult)) - .extractingJsonPathStringValue("$.kubernetes.serviceAccount").isNotEmpty(); + .extractingJsonPathStringValue("$.kubernetes.serviceAccount") + .isNotEmpty(); } private WebClient.Builder builder() { @@ -257,17 +294,19 @@ private RetryBackoffSpec retrySpec() { private void assertLogStatement(K3sContainer container, String message) { try { String appPodName = container - .execInContainer("sh", "-c", - "kubectl get pods -l app=" + DEPLOYMENT_NAME + " -o=name --no-headers | tr -d '\n'") - .getStdout(); - - await().pollDelay(Duration.ofSeconds(4)).pollInterval(Duration.ofSeconds(1)).atMost(20, TimeUnit.SECONDS) - .until(() -> { - Container.ExecResult execResult = container.execInContainer("sh", "-c", - "kubectl logs " + appPodName.trim()); - String ok = execResult.getStdout(); - return ok.contains(message); - }); + .execInContainer("sh", "-c", + "kubectl get pods -l app=" + DEPLOYMENT_NAME + " -o=name --no-headers | tr -d '\n'") + .getStdout(); + + await().pollDelay(Duration.ofSeconds(4)) + .pollInterval(Duration.ofSeconds(1)) + .atMost(20, TimeUnit.SECONDS) + .until(() -> { + Container.ExecResult execResult = container.execInContainer("sh", "-c", + "kubectl logs " + appPodName.trim()); + String ok = execResult.getStdout(); + return ok.contains(message); + }); } catch (Exception e) { e.printStackTrace(); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoveryMultipleSelectiveNamespacesITDelegate.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoveryMultipleSelectiveNamespacesITDelegate.java index a996309828..2fcf0b3a1b 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoveryMultipleSelectiveNamespacesITDelegate.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoveryMultipleSelectiveNamespacesITDelegate.java @@ -126,8 +126,10 @@ void testTwoNamespacesBothBlockingAndReactive(K3sContainer container) { private String logs(K3sContainer container) { try { - String appPodName = container.execInContainer("sh", "-c", - "kubectl get pods -l app=" + IMAGE_NAME + " -o=name --no-headers | tr -d '\n'").getStdout(); + String appPodName = container + .execInContainer("sh", "-c", + "kubectl get pods -l app=" + IMAGE_NAME + " -o=name --no-headers | tr -d '\n'") + .getStdout(); Container.ExecResult execResult = container.execInContainer("sh", "-c", "kubectl logs " + appPodName.trim()); @@ -142,10 +144,13 @@ private String logs(K3sContainer container) { private void reactiveCheck() { WebClient servicesClient = builder().baseUrl("http://localhost/reactive/services").build(); - List servicesResult = servicesClient.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { + List servicesResult = servicesClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); // we get two here, but since there is 'distinct' call, only 1 will be reported // but service instances will report 2 nevertheless @@ -153,16 +158,20 @@ private void reactiveCheck() { Assertions.assertTrue(servicesResult.contains("service-wiremock")); WebClient ourServiceClient = builder().baseUrl("http://localhost/reactive/service-instances/service-wiremock") - .build(); + .build(); - List ourServiceInstances = ourServiceClient.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { + List ourServiceInstances = ourServiceClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(ourServiceInstances.size(), 2); ourServiceInstances = ourServiceInstances.stream() - .sorted(Comparator.comparing(DefaultKubernetesServiceInstance::namespace)).toList(); + .sorted(Comparator.comparing(DefaultKubernetesServiceInstance::namespace)) + .toList(); DefaultKubernetesServiceInstance serviceInstanceA = ourServiceInstances.get(0); // we only care about namespace here, as all other fields are tested in various @@ -178,10 +187,13 @@ private void reactiveCheck() { private void blockingCheck() { WebClient servicesClient = builder().baseUrl("http://localhost/services").build(); - List servicesResult = servicesClient.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { + List servicesResult = servicesClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); // we get two here, but since there is 'distinct' call, only 1 will be reported // but service instances will report 2 nevertheless @@ -190,14 +202,18 @@ private void blockingCheck() { WebClient ourServiceClient = builder().baseUrl("http://localhost/service-instances/service-wiremock").build(); - List ourServiceInstances = ourServiceClient.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { + List ourServiceInstances = ourServiceClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(ourServiceInstances.size(), 2); ourServiceInstances = ourServiceInstances.stream() - .sorted(Comparator.comparing(DefaultKubernetesServiceInstance::namespace)).toList(); + .sorted(Comparator.comparing(DefaultKubernetesServiceInstance::namespace)) + .toList(); DefaultKubernetesServiceInstance serviceInstanceA = ourServiceInstances.get(0); // we only care about namespace here, as all other fields are tested in various diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoveryPodMetadataITDelegate.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoveryPodMetadataITDelegate.java index a67dc95c2a..940e3fc75e 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoveryPodMetadataITDelegate.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoveryPodMetadataITDelegate.java @@ -45,10 +45,13 @@ void testSimple() { WebClient servicesClient = builder().baseUrl("http://localhost/services").build(); - List servicesResult = servicesClient.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { + List servicesResult = servicesClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(servicesResult.size(), 3); Assertions.assertTrue(servicesResult.contains("kubernetes")); @@ -56,12 +59,16 @@ void testSimple() { Assertions.assertTrue(servicesResult.contains("external-name-service")); WebClient ourServiceClient = builder() - .baseUrl("http://localhost//service-instances/spring-cloud-kubernetes-k8s-client-discovery").build(); + .baseUrl("http://localhost//service-instances/spring-cloud-kubernetes-k8s-client-discovery") + .build(); - List ourServiceInstances = ourServiceClient.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { + List ourServiceInstances = ourServiceClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(ourServiceInstances.size(), 1); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoverySelectiveNamespacesIT.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoverySelectiveNamespacesIT.java index 43aeb1732b..c4e957b005 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoverySelectiveNamespacesIT.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-discovery/src/test/java/org/springframework/cloud/kubernetes/k8s/client/discovery/KubernetesClientDiscoverySelectiveNamespacesIT.java @@ -241,7 +241,7 @@ void testTwoNamespacesReactiveOnly() { void testTwoNamespacesBothBlockingAndReactive() { KubernetesClientDiscoveryClientUtils.patchToAddBlockingSupport(DEPLOYMENT_NAME, NAMESPACE); new KubernetesClientDiscoveryMultipleSelectiveNamespacesITDelegate() - .testTwoNamespacesBothBlockingAndReactive(K3S); + .testTwoNamespacesBothBlockingAndReactive(K3S); } private static void manifests(Phase phase) { @@ -257,14 +257,15 @@ private static void manifests(Phase phase) { if (phase.equals(Phase.CREATE)) { List envVars = new ArrayList<>( Optional.ofNullable(deployment.getSpec().getTemplate().getSpec().getContainers().get(0).getEnv()) - .orElse(List.of())); + .orElse(List.of())); V1EnvVar debugLevel = new V1EnvVar() - .name("LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_CLOUD_KUBERNETES_CLIENT_DISCOVERY").value("DEBUG"); + .name("LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_CLOUD_KUBERNETES_CLIENT_DISCOVERY") + .value("DEBUG"); V1EnvVar selectiveNamespaceA = new V1EnvVar().name("SPRING_CLOUD_KUBERNETES_DISCOVERY_NAMESPACES_0") - .value(NAMESPACE_A); + .value(NAMESPACE_A); V1EnvVar disableReactiveEnvVar = new V1EnvVar().name("SPRING_CLOUD_DISCOVERY_REACTIVE_ENABLED") - .value("FALSE"); + .value("FALSE"); envVars.add(disableReactiveEnvVar); envVars.add(debugLevel); @@ -277,21 +278,27 @@ private static void manifests(Phase phase) { private void reactiveCheck() { WebClient servicesClient = builder().baseUrl("http://localhost/reactive/services").build(); - List servicesResult = servicesClient.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { + List servicesResult = servicesClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(servicesResult.size(), 1); Assertions.assertTrue(servicesResult.contains("service-wiremock")); WebClient ourServiceClient = builder().baseUrl("http://localhost/reactive/service-instances/service-wiremock") - .build(); + .build(); - List ourServiceInstances = ourServiceClient.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { + List ourServiceInstances = ourServiceClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(ourServiceInstances.size(), 1); @@ -304,20 +311,26 @@ private void reactiveCheck() { private void blockingCheck() { WebClient servicesClient = builder().baseUrl("http://localhost/services").build(); - List servicesResult = servicesClient.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { + List servicesResult = servicesClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(servicesResult.size(), 1); Assertions.assertTrue(servicesResult.contains("service-wiremock")); WebClient ourServiceClient = builder().baseUrl("http://localhost/service-instances/service-wiremock").build(); - List ourServiceInstances = ourServiceClient.method(HttpMethod.GET).retrieve() - .bodyToMono(new ParameterizedTypeReference>() { + List ourServiceInstances = ourServiceClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { - }).retryWhen(retrySpec()).block(); + }) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals(ourServiceInstances.size(), 1); @@ -329,8 +342,10 @@ private void blockingCheck() { private String logs() { try { - String appPodName = K3S.execInContainer("sh", "-c", - "kubectl get pods -l app=" + IMAGE_NAME + " -o=name --no-headers | tr -d '\n'").getStdout(); + String appPodName = K3S + .execInContainer("sh", "-c", + "kubectl get pods -l app=" + IMAGE_NAME + " -o=name --no-headers | tr -d '\n'") + .getStdout(); Container.ExecResult execResult = K3S.execInContainer("sh", "-c", "kubectl logs " + appPodName.trim()); return execResult.getStdout(); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-kafka-configmap-reload-multiple-apps/kafka-configmap-test-app/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/multiple/apps/ConfigurationWatcherMultipleAppsIT.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-kafka-configmap-reload-multiple-apps/kafka-configmap-test-app/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/multiple/apps/ConfigurationWatcherMultipleAppsIT.java index 5ffcf7f682..0fdce32580 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-kafka-configmap-reload-multiple-apps/kafka-configmap-test-app/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/multiple/apps/ConfigurationWatcherMultipleAppsIT.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-kafka-configmap-reload-multiple-apps/kafka-configmap-test-app/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/multiple/apps/ConfigurationWatcherMultipleAppsIT.java @@ -113,12 +113,15 @@ void testRefresh() { // configmap has one label, one that says that we should refresh // and one annotation that says that we should refresh some specific services - V1ConfigMap configMap = new V1ConfigMapBuilder().editOrNewMetadata().withName(CONFIG_MAP_NAME) - .addToLabels("spring.cloud.kubernetes.config", "true") - .addToAnnotations("spring.cloud.kubernetes.configmap.apps", - "spring-cloud-kubernetes-client-configuration-watcher-configmap-app-a, " - + "spring-cloud-kubernetes-client-configuration-watcher-configmap-app-b") - .endMetadata().addToData("foo", "hello world").build(); + V1ConfigMap configMap = new V1ConfigMapBuilder().editOrNewMetadata() + .withName(CONFIG_MAP_NAME) + .addToLabels("spring.cloud.kubernetes.config", "true") + .addToAnnotations("spring.cloud.kubernetes.configmap.apps", + "spring-cloud-kubernetes-client-configuration-watcher-configmap-app-a, " + + "spring-cloud-kubernetes-client-configuration-watcher-configmap-app-b") + .endMetadata() + .addToData("foo", "hello world") + .build(); util.createAndWait(NAMESPACE, configMap, null); WebClient.Builder builderA = builder(); @@ -129,8 +132,11 @@ void testRefresh() { Boolean[] valueA = new Boolean[1]; await().pollInterval(Duration.ofSeconds(3)).atMost(Duration.ofSeconds(240)).until(() -> { - valueA[0] = serviceClientA.method(HttpMethod.GET).retrieve().bodyToMono(Boolean.class) - .retryWhen(retrySpec()).block(); + valueA[0] = serviceClientA.method(HttpMethod.GET) + .retrieve() + .bodyToMono(Boolean.class) + .retryWhen(retrySpec()) + .block(); return valueA[0]; }); @@ -138,8 +144,11 @@ void testRefresh() { Boolean[] valueB = new Boolean[1]; await().pollInterval(Duration.ofSeconds(3)).atMost(Duration.ofSeconds(240)).until(() -> { - valueB[0] = serviceClientB.method(HttpMethod.GET).retrieve().bodyToMono(Boolean.class) - .retryWhen(retrySpec()).block(); + valueB[0] = serviceClientB.method(HttpMethod.GET) + .retrieve() + .bodyToMono(Boolean.class) + .retryWhen(retrySpec()) + .block(); return valueB[0]; }); @@ -151,7 +160,7 @@ private void appA(Phase phase) { V1Deployment deployment = (V1Deployment) util.yaml("app-a/app-a-deployment.yaml"); V1Service service = (V1Service) util.yaml("app-a/app-a-service.yaml"); V1Ingress ingress = (V1Ingress) util - .yaml("ingress/spring-cloud-kubernetes-configuration-watcher-multiple-apps-ingress.yaml"); + .yaml("ingress/spring-cloud-kubernetes-configuration-watcher-multiple-apps-ingress.yaml"); if (phase.equals(Phase.CREATE)) { util.createAndWait(NAMESPACE, null, deployment, service, ingress, true); @@ -175,9 +184,9 @@ else if (phase.equals(Phase.DELETE)) { private void configWatcher(Phase phase) { V1Deployment deployment = (V1Deployment) util - .yaml("config-watcher/spring-cloud-kubernetes-configuration-watcher-bus-kafka-deployment.yaml"); + .yaml("config-watcher/spring-cloud-kubernetes-configuration-watcher-bus-kafka-deployment.yaml"); V1Service service = (V1Service) util - .yaml("config-watcher/spring-cloud-kubernetes-configuration-watcher-service.yaml"); + .yaml("config-watcher/spring-cloud-kubernetes-configuration-watcher-service.yaml"); if (phase.equals(Phase.CREATE)) { util.createAndWait(NAMESPACE, null, deployment, service, null, true); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-rabbitmq-secret-reload-multiple-apps/rabbitmq-secret-test-app/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/multiple/apps/ConfigurationWatcherMultipleAppIT.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-rabbitmq-secret-reload-multiple-apps/rabbitmq-secret-test-app/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/multiple/apps/ConfigurationWatcherMultipleAppIT.java index 2f0429d12a..5266a869b1 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-rabbitmq-secret-reload-multiple-apps/rabbitmq-secret-test-app/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/multiple/apps/ConfigurationWatcherMultipleAppIT.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-rabbitmq-secret-reload-multiple-apps/rabbitmq-secret-test-app/src/test/java/org/springframework/cloud/kubernetes/configuration/watcher/multiple/apps/ConfigurationWatcherMultipleAppIT.java @@ -112,12 +112,14 @@ void testRefresh() { // secret has one label, one that says that we should refresh // and one annotation that says that we should refresh some specific services - V1Secret secret = new V1SecretBuilder().editOrNewMetadata().withName(SECRET_NAME) - .addToLabels("spring.cloud.kubernetes.secret", "true") - .addToAnnotations("spring.cloud.kubernetes.secret.apps", - "spring-cloud-kubernetes-client-configuration-watcher-secret-app-a, " - + "spring-cloud-kubernetes-client-configuration-watcher-secret-app-b") - .endMetadata().build(); + V1Secret secret = new V1SecretBuilder().editOrNewMetadata() + .withName(SECRET_NAME) + .addToLabels("spring.cloud.kubernetes.secret", "true") + .addToAnnotations("spring.cloud.kubernetes.secret.apps", + "spring-cloud-kubernetes-client-configuration-watcher-secret-app-a, " + + "spring-cloud-kubernetes-client-configuration-watcher-secret-app-b") + .endMetadata() + .build(); util.createAndWait(NAMESPACE, null, secret); WebClient.Builder builderA = builder(); @@ -128,8 +130,11 @@ void testRefresh() { Boolean[] valueA = new Boolean[1]; await().pollInterval(Duration.ofSeconds(3)).atMost(Duration.ofSeconds(240)).until(() -> { - valueA[0] = serviceClientA.method(HttpMethod.GET).retrieve().bodyToMono(Boolean.class) - .retryWhen(retrySpec()).block(); + valueA[0] = serviceClientA.method(HttpMethod.GET) + .retrieve() + .bodyToMono(Boolean.class) + .retryWhen(retrySpec()) + .block(); return valueA[0]; }); @@ -137,8 +142,11 @@ void testRefresh() { Boolean[] valueB = new Boolean[1]; await().pollInterval(Duration.ofSeconds(3)).atMost(Duration.ofSeconds(240)).until(() -> { - valueB[0] = serviceClientB.method(HttpMethod.GET).retrieve().bodyToMono(Boolean.class) - .retryWhen(retrySpec()).block(); + valueB[0] = serviceClientB.method(HttpMethod.GET) + .retrieve() + .bodyToMono(Boolean.class) + .retryWhen(retrySpec()) + .block(); return valueB[0]; }); @@ -150,7 +158,7 @@ private void appA(Phase phase) { V1Deployment deployment = (V1Deployment) util.yaml("app-a/app-a-deployment.yaml"); V1Service service = (V1Service) util.yaml("app-a/app-a-service.yaml"); V1Ingress ingress = (V1Ingress) util - .yaml("ingress/spring-cloud-kubernetes-configuration-watcher-multiple-apps-ingress.yaml"); + .yaml("ingress/spring-cloud-kubernetes-configuration-watcher-multiple-apps-ingress.yaml"); if (phase.equals(Phase.CREATE)) { util.createAndWait(NAMESPACE, null, deployment, service, ingress, true); @@ -174,9 +182,9 @@ else if (phase.equals(Phase.DELETE)) { private void configWatcher(Phase phase) { V1Deployment deployment = (V1Deployment) util - .yaml("config-watcher/spring-cloud-kubernetes-configuration-watcher-it-bus-amqp-deployment.yaml"); + .yaml("config-watcher/spring-cloud-kubernetes-configuration-watcher-it-bus-amqp-deployment.yaml"); V1Service service = (V1Service) util - .yaml("config-watcher/spring-cloud-kubernetes-configuration-watcher-service.yaml"); + .yaml("config-watcher/spring-cloud-kubernetes-configuration-watcher-service.yaml"); if (phase.equals(Phase.CREATE)) { util.createAndWait(NAMESPACE, null, deployment, service, null, true); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/configmap/BootstrapEnabledPollingReloadConfigMapMountDelegate.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/configmap/BootstrapEnabledPollingReloadConfigMapMountDelegate.java index ae7d6dea7a..cd78af12ef 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/configmap/BootstrapEnabledPollingReloadConfigMapMountDelegate.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/configmap/BootstrapEnabledPollingReloadConfigMapMountDelegate.java @@ -68,8 +68,11 @@ static void testBootstrapEnabledPollingReloadConfigMapMount(String deploymentNam // (3) WebClient webClient = K8sClientConfigMapReloadITUtil.builder().baseUrl("http://localhost/mount").build(); - String result = webClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(K8sClientConfigMapReloadITUtil.retrySpec()).block(); + String result = webClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(K8sClientConfigMapReloadITUtil.retrySpec()) + .block(); // we first read the initial value from the configmap Assertions.assertEquals("as-mount-initial", result); @@ -82,8 +85,12 @@ static void testBootstrapEnabledPollingReloadConfigMapMount(String deploymentNam null); await().timeout(Duration.ofSeconds(180)) - .until(() -> webClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(K8sClientConfigMapReloadITUtil.retrySpec()).block().equals("as-mount-changed")); + .until(() -> webClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(K8sClientConfigMapReloadITUtil.retrySpec()) + .block() + .equals("as-mount-changed")); } diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/configmap/DataChangesInConfigMapReloadDelegate.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/configmap/DataChangesInConfigMapReloadDelegate.java index 7f7dddc37f..c527145d9f 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/configmap/DataChangesInConfigMapReloadDelegate.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/configmap/DataChangesInConfigMapReloadDelegate.java @@ -59,27 +59,39 @@ static void testSimple(String dockerImage, String deploymentName, K3sContainer k Commons.assertReloadLogStatements("added configmap informer for namespace", "added secret informer for namespace", deploymentName); - WebClient webClient = K8sClientConfigMapReloadITUtil.builder().baseUrl("http://localhost/" + LEFT_NAMESPACE) - .build(); - String result = webClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(K8sClientConfigMapReloadITUtil.retrySpec()).block(); + WebClient webClient = K8sClientConfigMapReloadITUtil.builder() + .baseUrl("http://localhost/" + LEFT_NAMESPACE) + .build(); + String result = webClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(K8sClientConfigMapReloadITUtil.retrySpec()) + .block(); // we first read the initial value from the left-configmap Assertions.assertEquals("left-initial", result); // then deploy a new version of left-configmap, but without changing its data, // only add a label - V1ConfigMap configMap = new V1ConfigMapBuilder().withMetadata(new V1ObjectMetaBuilder() - .withLabels(Map.of("new-label", "abc")).withNamespace("left").withName("left-configmap").build()) - .withData(Map.of("left.value", "left-initial")).build(); + V1ConfigMap configMap = new V1ConfigMapBuilder() + .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("new-label", "abc")) + .withNamespace("left") + .withName("left-configmap") + .build()) + .withData(Map.of("left.value", "left-initial")) + .build(); replaceConfigMap(configMap); await().pollInterval(Duration.ofSeconds(3)).atMost(Duration.ofSeconds(90)).until(() -> { WebClient innerWebClient = K8sClientConfigMapReloadITUtil.builder() - .baseUrl("http://localhost/" + LEFT_NAMESPACE).build(); - String innerResult = innerWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(K8sClientConfigMapReloadITUtil.retrySpec()).block(); + .baseUrl("http://localhost/" + LEFT_NAMESPACE) + .build(); + String innerResult = innerWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(K8sClientConfigMapReloadITUtil.retrySpec()) + .block(); return "left-initial".equals(innerResult); }); @@ -89,17 +101,24 @@ static void testSimple(String dockerImage, String deploymentName, K3sContainer k // change data configMap = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("new-label", "abc")).withNamespace("left") - .withName("left-configmap").build()) - .withData(Map.of("left.value", "left-after-change")).build(); + .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("new-label", "abc")) + .withNamespace("left") + .withName("left-configmap") + .build()) + .withData(Map.of("left.value", "left-after-change")) + .build(); replaceConfigMap(configMap); await().pollInterval(Duration.ofSeconds(3)).atMost(Duration.ofSeconds(90)).until(() -> { WebClient innerWebClient = K8sClientConfigMapReloadITUtil.builder() - .baseUrl("http://localhost/" + LEFT_NAMESPACE).build(); - String innerResult = innerWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(K8sClientConfigMapReloadITUtil.retrySpec()).block(); + .baseUrl("http://localhost/" + LEFT_NAMESPACE) + .build(); + String innerResult = innerWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(K8sClientConfigMapReloadITUtil.retrySpec()) + .block(); return "left-after-change".equals(innerResult); }); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/configmap/K8sClientConfigMapReloadIT.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/configmap/K8sClientConfigMapReloadIT.java index b55ad11bd6..b283ab8687 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/configmap/K8sClientConfigMapReloadIT.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/configmap/K8sClientConfigMapReloadIT.java @@ -109,8 +109,11 @@ void testInformFromOneNamespaceEventNotTriggered() throws Exception { "added secret informer for namespace", "spring-k8s-client-reload"); WebClient webClient = builder().baseUrl("http://localhost/left").build(); - String result = webClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class).retryWhen(retrySpec()) - .block(); + String result = webClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); // we first read the initial value from the left-configmap Assertions.assertEquals("left-initial", result); @@ -122,8 +125,9 @@ void testInformFromOneNamespaceEventNotTriggered() throws Exception { // then deploy a new version of right-configmap V1ConfigMap rightConfigMapAfterChange = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMeta().namespace("right").name("right-configmap")) - .withData(Map.of("right.value", "right-after-change")).build(); + .withMetadata(new V1ObjectMeta().namespace("right").name("right-configmap")) + .withData(Map.of("right.value", "right-after-change")) + .build(); replaceConfigMap(rightConfigMapAfterChange, "right-configmap"); @@ -167,22 +171,29 @@ void testInformFromOneNamespaceEventTriggered() throws Exception { // read the value from the right-configmap WebClient webClient = builder().baseUrl("http://localhost/right").build(); - String result = webClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class).retryWhen(retrySpec()) - .block(); + String result = webClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals("right-initial", result); // then deploy a new version of right-configmap V1ConfigMap rightConfigMapAfterChange = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMeta().namespace("right").name("right-configmap")) - .withData(Map.of("right.value", "right-after-change")).build(); + .withMetadata(new V1ObjectMeta().namespace("right").name("right-configmap")) + .withData(Map.of("right.value", "right-after-change")) + .build(); replaceConfigMap(rightConfigMapAfterChange, "right-configmap"); String[] resultAfterChange = new String[1]; await().pollInterval(Duration.ofSeconds(3)).atMost(Duration.ofSeconds(90)).until(() -> { WebClient innerWebClient = builder().baseUrl("http://localhost/right").build(); - String innerResult = innerWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(retrySpec()).block(); + String innerResult = innerWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); resultAfterChange[0] = innerResult; return innerResult != null; @@ -210,20 +221,27 @@ void testInform() throws Exception { // read the initial value from the right-configmap WebClient rightWebClient = builder().baseUrl("http://localhost/right").build(); - String rightResult = rightWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(retrySpec()).block(); + String rightResult = rightWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals("right-initial", rightResult); // then read the initial value from the right-with-label-configmap WebClient rightWithLabelWebClient = builder().baseUrl("http://localhost/with-label").build(); - String rightWithLabelResult = rightWithLabelWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(retrySpec()).block(); + String rightWithLabelResult = rightWithLabelWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals("right-with-label-initial", rightWithLabelResult); // then deploy a new version of right-configmap V1ConfigMap rightConfigMapAfterChange = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMeta().namespace("right").name("right-configmap")) - .withData(Map.of("right.value", "right-after-change")).build(); + .withMetadata(new V1ObjectMeta().namespace("right").name("right-configmap")) + .withData(Map.of("right.value", "right-after-change")) + .build(); replaceConfigMap(rightConfigMapAfterChange, "right-configmap"); @@ -231,14 +249,18 @@ void testInform() throws Exception { LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(5)); // nothing changes in our app, because we are watching only labeled configmaps - rightResult = rightWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class).retryWhen(retrySpec()) - .block(); + rightResult = rightWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals("right-initial", rightResult); // then deploy a new version of right-with-label-configmap V1ConfigMap rightWithLabelConfigMapAfterChange = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMeta().namespace("right").name("right-configmap-with-label")) - .withData(Map.of("right.with.label.value", "right-with-label-after-change")).build(); + .withMetadata(new V1ObjectMeta().namespace("right").name("right-configmap-with-label")) + .withData(Map.of("right.with.label.value", "right-with-label-after-change")) + .build(); replaceConfigMap(rightWithLabelConfigMapAfterChange, "right-configmap-with-label"); @@ -247,8 +269,11 @@ void testInform() throws Exception { String[] resultAfterChange = new String[1]; await().pollInterval(Duration.ofSeconds(3)).atMost(Duration.ofSeconds(90)).until(() -> { WebClient innerWebClient = builder().baseUrl("http://localhost/with-label").build(); - String innerResult = innerWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(retrySpec()).block(); + String innerResult = innerWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); resultAfterChange[0] = innerResult; return innerResult != null; }); @@ -256,8 +281,11 @@ void testInform() throws Exception { // right-configmap now will see the new value also, but only because the other // configmap has triggered the restart - rightResult = rightWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class).retryWhen(retrySpec()) - .block(); + rightResult = rightWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals("right-after-change", rightResult); util.deleteAndWait("right", rightWithLabelConfigMap, null); } @@ -278,22 +306,29 @@ void testInformFromOneNamespaceEventTriggeredSecretsDisabled() throws Exception // read the value from the right-configmap WebClient webClient = builder().baseUrl("http://localhost/right").build(); - String result = webClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class).retryWhen(retrySpec()) - .block(); + String result = webClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); Assertions.assertEquals("right-initial", result); // then deploy a new version of right-configmap V1ConfigMap rightConfigMapAfterChange = new V1ConfigMapBuilder() - .withMetadata(new V1ObjectMeta().namespace("right").name("right-configmap")) - .withData(Map.of("right.value", "right-after-change")).build(); + .withMetadata(new V1ObjectMeta().namespace("right").name("right-configmap")) + .withData(Map.of("right.value", "right-after-change")) + .build(); replaceConfigMap(rightConfigMapAfterChange, "right-configmap"); String[] resultAfterChange = new String[1]; await().pollInterval(Duration.ofSeconds(3)).atMost(Duration.ofSeconds(90)).until(() -> { WebClient innerWebClient = builder().baseUrl("http://localhost/right").build(); - String innerResult = innerWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(retrySpec()).block(); + String innerResult = innerWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); resultAfterChange[0] = innerResult; return innerResult != null; diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/configmap/K8sClientConfigMapReloadITUtil.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/configmap/K8sClientConfigMapReloadITUtil.java index 9d50fd639c..2043b40e0f 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/configmap/K8sClientConfigMapReloadITUtil.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/configmap/K8sClientConfigMapReloadITUtil.java @@ -436,9 +436,9 @@ static RetryBackoffSpec retrySpec() { static String logs(String appLabelValue, K3sContainer k3sContainer) { try { String appPodName = k3sContainer - .execInContainer("sh", "-c", - "kubectl get pods -l app=" + appLabelValue + " -o=name --no-headers | tr -d '\n'") - .getStdout(); + .execInContainer("sh", "-c", + "kubectl get pods -l app=" + appLabelValue + " -o=name --no-headers | tr -d '\n'") + .getStdout(); Container.ExecResult execResult = k3sContainer.execInContainer("sh", "-c", "kubectl logs " + appPodName.trim()); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/configmap/PollingReloadConfigMapMountDelegate.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/configmap/PollingReloadConfigMapMountDelegate.java index 2c9db477d4..7b97a62115 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/configmap/PollingReloadConfigMapMountDelegate.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/configmap/PollingReloadConfigMapMountDelegate.java @@ -70,8 +70,11 @@ static void testPollingReloadConfigMapMount(String deploymentName, K3sContainer // (3) WebClient webClient = K8sClientConfigMapReloadITUtil.builder().baseUrl("http://localhost/mount").build(); - String result = webClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(K8sClientConfigMapReloadITUtil.retrySpec()).block(); + String result = webClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(K8sClientConfigMapReloadITUtil.retrySpec()) + .block(); // we first read the initial value from the configmap Assertions.assertEquals("as-mount-initial", result); @@ -84,8 +87,12 @@ static void testPollingReloadConfigMapMount(String deploymentName, K3sContainer null); await().timeout(Duration.ofSeconds(180)) - .until(() -> webClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(K8sClientConfigMapReloadITUtil.retrySpec()).block().equals("as-mount-changed")); + .until(() -> webClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(K8sClientConfigMapReloadITUtil.retrySpec()) + .block() + .equals("as-mount-changed")); } diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/secret/DataChangesInSecretsReloadDelegate.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/secret/DataChangesInSecretsReloadDelegate.java index bb100878b9..709ae77c75 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/secret/DataChangesInSecretsReloadDelegate.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/secret/DataChangesInSecretsReloadDelegate.java @@ -55,8 +55,11 @@ static void testDataChangesInSecretsReload(K3sContainer k3sContainer, String dep "added configmap informer for namespace", deploymentName); WebClient webClient = builder().baseUrl("http://localhost/key").build(); - String result = webClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class).retryWhen(retrySpec()) - .block(); + String result = webClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); // we first read the initial value from the secret Assertions.assertEquals("initial", result); @@ -64,16 +67,22 @@ static void testDataChangesInSecretsReload(K3sContainer k3sContainer, String dep // then deploy a new version of left-configmap, but without changing its data, // only add a label V1Secret secret = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("new-label", "abc")).withNamespace(NAMESPACE) - .withName("event-reload").build()) - .withData(Map.of("application.properties", "from.properties.key=initial".getBytes())).build(); + .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("new-label", "abc")) + .withNamespace(NAMESPACE) + .withName("event-reload") + .build()) + .withData(Map.of("application.properties", "from.properties.key=initial".getBytes())) + .build(); replaceSecret(secret, "event-reload"); await().pollInterval(Duration.ofSeconds(3)).atMost(Duration.ofSeconds(90)).until(() -> { WebClient innerWebClient = builder().baseUrl("http://localhost/key").build(); - String innerResult = innerWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(retrySpec()).block(); + String innerResult = innerWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); return "initial".equals(innerResult); }); @@ -83,16 +92,22 @@ static void testDataChangesInSecretsReload(K3sContainer k3sContainer, String dep // change data secret = new V1SecretBuilder() - .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("new-label", "abc")).withNamespace(NAMESPACE) - .withName("event-reload").build()) - .withData(Map.of("application.properties", "from.properties.key=change-initial".getBytes())).build(); + .withMetadata(new V1ObjectMetaBuilder().withLabels(Map.of("new-label", "abc")) + .withNamespace(NAMESPACE) + .withName("event-reload") + .build()) + .withData(Map.of("application.properties", "from.properties.key=change-initial".getBytes())) + .build(); replaceSecret(secret, "event-reload"); await().pollInterval(Duration.ofSeconds(3)).atMost(Duration.ofSeconds(90)).until(() -> { WebClient innerWebClient = builder().baseUrl("http://localhost/key").build(); - String innerResult = innerWebClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(retrySpec()).block(); + String innerResult = innerWebClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block(); return "change-initial".equals(innerResult); }); diff --git a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/secret/K8sClientSecretsReloadIT.java b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/secret/K8sClientSecretsReloadIT.java index 84cc869a0d..c5685af0b0 100644 --- a/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/secret/K8sClientSecretsReloadIT.java +++ b/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/test/java/org/springframework/cloud/kubernetes/k8s/client/reload/secret/K8sClientSecretsReloadIT.java @@ -110,9 +110,14 @@ void testSecretEventReload() throws Exception { WebClient.Builder builder = builder(); WebClient secretClient = builder.baseUrl(PROPERTY_URL).build(); - await().timeout(Duration.ofSeconds(120)).pollInterval(Duration.ofSeconds(2)) - .until(() -> secretClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(retrySpec()).block().equals("initial")); + await().timeout(Duration.ofSeconds(120)) + .pollInterval(Duration.ofSeconds(2)) + .until(() -> secretClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block() + .equals("initial")); V1Secret v1Secret = (V1Secret) util.yaml("secret.yaml"); Map secretData = v1Secret.getData(); @@ -120,9 +125,14 @@ void testSecretEventReload() throws Exception { v1Secret.setData(secretData); coreV1Api.replaceNamespacedSecret("event-reload", NAMESPACE, v1Secret, null, null, null, null); - await().timeout(Duration.ofSeconds(120)).pollInterval(Duration.ofSeconds(2)) - .until(() -> secretClient.method(HttpMethod.GET).retrieve().bodyToMono(String.class) - .retryWhen(retrySpec()).block().equals("after-change")); + await().timeout(Duration.ofSeconds(120)) + .pollInterval(Duration.ofSeconds(2)) + .until(() -> secretClient.method(HttpMethod.GET) + .retrieve() + .bodyToMono(String.class) + .retryWhen(retrySpec()) + .block() + .equals("after-change")); } private void recreateSecret() { diff --git a/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/integration/tests/commons/Commons.java b/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/integration/tests/commons/Commons.java index 9cf7b0b27e..50c457f095 100644 --- a/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/integration/tests/commons/Commons.java +++ b/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/integration/tests/commons/Commons.java @@ -90,8 +90,11 @@ private Commons() { public static final String TEMP_FOLDER = new File(System.getProperty("java.io.tmpdir")).getAbsolutePath(); private static final K3sContainer CONTAINER = new FixedPortsK3sContainer(DockerImageName.parse(Commons.RANCHER)) - .configureFixedPorts(EXPOSED_PORTS).withFileSystemBind(TEMP_FOLDER, TEMP_FOLDER) - .withFileSystemBind(TMP_IMAGES, TMP_IMAGES).withCommand(Commons.RANCHER_COMMAND).withReuse(true); + .configureFixedPorts(EXPOSED_PORTS) + .withFileSystemBind(TEMP_FOLDER, TEMP_FOLDER) + .withFileSystemBind(TMP_IMAGES, TMP_IMAGES) + .withCommand(Commons.RANCHER_COMMAND) + .withReuse(true); public static K3sContainer container() { return CONTAINER; @@ -107,36 +110,40 @@ public static void loadSpringCloudKubernetesImage(String project, K3sContainer c public static void assertReloadLogStatements(String left, String right, String appLabel) { try { - String appPodName = CONTAINER.execInContainer("sh", "-c", - "kubectl get pods -l app=" + appLabel + " -o=name --no-headers | tr -d '\n'").getStdout(); + String appPodName = CONTAINER + .execInContainer("sh", "-c", + "kubectl get pods -l app=" + appLabel + " -o=name --no-headers | tr -d '\n'") + .getStdout(); LOG.info("appPodName : ->" + appPodName + "<-"); // we issue a pollDelay to let the logs sync in, otherwise the results are not // going to be correctly asserted - await().pollDelay(20, TimeUnit.SECONDS).pollInterval(Duration.ofSeconds(5)).atMost(Duration.ofSeconds(120)) - .until(() -> { - - Container.ExecResult result = CONTAINER.execInContainer("sh", "-c", - "kubectl logs " + appPodName.trim() + "| grep " + "'" + left + "'"); - String error = result.getStderr(); - String ok = result.getStdout(); - - LOG.info("error is : -->" + error + "<--"); - - if (ok != null && !ok.isBlank()) { - - if (!right.isBlank()) { - String notPresent = CONTAINER - .execInContainer("sh", "-c", - "kubectl logs " + appPodName.trim() + "| grep " + "'" + right + "'") - .getStdout(); - Assertions.assertTrue(notPresent == null || notPresent.isBlank()); - } - - return true; + await().pollDelay(20, TimeUnit.SECONDS) + .pollInterval(Duration.ofSeconds(5)) + .atMost(Duration.ofSeconds(120)) + .until(() -> { + + Container.ExecResult result = CONTAINER.execInContainer("sh", "-c", + "kubectl logs " + appPodName.trim() + "| grep " + "'" + left + "'"); + String error = result.getStderr(); + String ok = result.getStdout(); + + LOG.info("error is : -->" + error + "<--"); + + if (ok != null && !ok.isBlank()) { + + if (!right.isBlank()) { + String notPresent = CONTAINER + .execInContainer("sh", "-c", + "kubectl logs " + appPodName.trim() + "| grep " + "'" + right + "'") + .getStdout(); + Assertions.assertTrue(notPresent == null || notPresent.isBlank()); } - LOG.info("log statement not yet present"); - return false; - }); + + return true; + } + LOG.info("log statement not yet present"); + return false; + }); } catch (Exception e) { throw new RuntimeException(e); @@ -175,8 +182,10 @@ public static void load(K3sContainer container, String tarName, String imageName if (dockerImagesRootDir.exists() && dockerImagesRootDir.isDirectory()) { File[] tars = dockerImagesRootDir.listFiles(); if (tars != null && tars.length > 0) { - Optional found = Arrays.stream(tars).map(File::getName).filter(x -> x.contains(tarName)) - .findFirst(); + Optional found = Arrays.stream(tars) + .map(File::getName) + .filter(x -> x.contains(tarName)) + .findFirst(); if (found.isPresent()) { LOG.info("running in github actions, will load from : " + Commons.TMP_IMAGES + " tar : " + found.get()); @@ -233,10 +242,11 @@ public static void validateImage(String image, K3sContainer container) { try (ListImagesCmd listImagesCmd = container.getDockerClient().listImagesCmd()) { List images = listImagesCmd.exec(); images.stream() - .filter(x -> Arrays.stream(x.getRepoTags() == null ? new String[] {} : x.getRepoTags()) - .anyMatch(y -> y.contains(image))) - .findFirst().orElseThrow(() -> new IllegalArgumentException("Image : " + image - + " not build locally. " + "You need to build it first, and then run the test")); + .filter(x -> Arrays.stream(x.getRepoTags() == null ? new String[] {} : x.getRepoTags()) + .anyMatch(y -> y.contains(image))) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("Image : " + image + " not build locally. " + + "You need to build it first, and then run the test")); } } @@ -291,14 +301,15 @@ public static void waitForLogStatement(String message, K3sContainer k3sContainer await().atMost(Duration.ofMinutes(2)).pollInterval(Duration.ofSeconds(4)).until(() -> { - String appPodName = k3sContainer.execInContainer("sh", "-c", - "kubectl get pods -l app=" + appLabelValue - + " -o custom-columns=POD:metadata.name,STATUS:status.phase" - + " | grep -i 'running' | awk '{print $1}' | tr -d '\n' ") - .getStdout(); + String appPodName = k3sContainer + .execInContainer("sh", "-c", + "kubectl get pods -l app=" + appLabelValue + + " -o custom-columns=POD:metadata.name,STATUS:status.phase" + + " | grep -i 'running' | awk '{print $1}' | tr -d '\n' ") + .getStdout(); String execResult = k3sContainer.execInContainer("sh", "-c", "kubectl logs " + appPodName.trim()) - .getStdout(); + .getStdout(); return execResult.contains(message); }); } diff --git a/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/integration/tests/commons/Images.java b/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/integration/tests/commons/Images.java index 9aff9473a8..47021c563f 100644 --- a/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/integration/tests/commons/Images.java +++ b/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/integration/tests/commons/Images.java @@ -110,8 +110,11 @@ public static void loadRabbitmq(K3sContainer container) { private static String imageVersion(String imageNameForDownload) { BufferedReader reader = new BufferedReader( new InputStreamReader(Commons.class.getClassLoader().getResourceAsStream("current-images.txt"))); - return reader.lines().filter(line -> line.contains(imageNameForDownload)).map(line -> line.split(":")[1]) - .findFirst().orElseThrow(); + return reader.lines() + .filter(line -> line.contains(imageNameForDownload)) + .map(line -> line.split(":")[1]) + .findFirst() + .orElseThrow(); } } diff --git a/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/integration/tests/commons/K8SUtils.java b/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/integration/tests/commons/K8SUtils.java index 747c2e433a..d191fb4576 100644 --- a/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/integration/tests/commons/K8SUtils.java +++ b/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/integration/tests/commons/K8SUtils.java @@ -158,15 +158,26 @@ public Object readYaml(String urlString) throws Exception { public static Object readYamlFromClasspath(String fileName) throws Exception { ClassLoader classLoader = K8SUtils.class.getClassLoader(); String file = new BufferedReader(new InputStreamReader(classLoader.getResourceAsStream(fileName))).lines() - .collect(Collectors.joining("\n")); + .collect(Collectors.joining("\n")); return Yaml.load(file); } public V1Service createService(String name, Map labels, Map specSelectors, String type, String portName, int port, int targetPort, String namespace) throws ApiException { - V1Service wiremockService = new V1ServiceBuilder().editOrNewMetadata().withName(name).addToLabels(labels) - .endMetadata().editOrNewSpec().addToSelector(specSelectors).withType(type).addNewPort() - .withName(portName).withPort(port).withNewTargetPort(targetPort).endPort().endSpec().build(); + V1Service wiremockService = new V1ServiceBuilder().editOrNewMetadata() + .withName(name) + .addToLabels(labels) + .endMetadata() + .editOrNewSpec() + .addToSelector(specSelectors) + .withType(type) + .addNewPort() + .withName(portName) + .withPort(port) + .withNewTargetPort(targetPort) + .endPort() + .endSpec() + .build(); return api.createNamespacedService(namespace, wiremockService, null, null, null, null); } @@ -176,22 +187,52 @@ public V1Deployment createDeployment(String name, Map selectorMa String livenessProbePath, String serviceAccountName, Collection envVars, String namespace) throws ApiException { - V1Deployment wiremockDeployment = new V1DeploymentBuilder().editOrNewMetadata().withName(name).endMetadata() - .editOrNewSpec().withNewSelector().addToMatchLabels(selectorMatchLabels).endSelector() - .editOrNewTemplate().editOrNewMetadata().addToLabels(templateMetadataLabels).endMetadata() - .editOrNewSpec().withServiceAccountName(serviceAccountName).addNewContainer().withName(containerName) - .withImage(image).withImagePullPolicy(pullPolicy).addNewPort().withContainerPort(containerPort) - .endPort().editOrNewReadinessProbe().editOrNewHttpGet().withNewPort(readinessProbePort) - .withPath(readinessProbePath).endHttpGet().endReadinessProbe().editOrNewLivenessProbe() - .editOrNewHttpGet().withNewPort(livenessProbePort).withPath(livenessProbePath).endHttpGet() - .endLivenessProbe().addAllToEnv(envVars).endContainer().endSpec().endTemplate().endSpec().build(); + V1Deployment wiremockDeployment = new V1DeploymentBuilder().editOrNewMetadata() + .withName(name) + .endMetadata() + .editOrNewSpec() + .withNewSelector() + .addToMatchLabels(selectorMatchLabels) + .endSelector() + .editOrNewTemplate() + .editOrNewMetadata() + .addToLabels(templateMetadataLabels) + .endMetadata() + .editOrNewSpec() + .withServiceAccountName(serviceAccountName) + .addNewContainer() + .withName(containerName) + .withImage(image) + .withImagePullPolicy(pullPolicy) + .addNewPort() + .withContainerPort(containerPort) + .endPort() + .editOrNewReadinessProbe() + .editOrNewHttpGet() + .withNewPort(readinessProbePort) + .withPath(readinessProbePath) + .endHttpGet() + .endReadinessProbe() + .editOrNewLivenessProbe() + .editOrNewHttpGet() + .withNewPort(livenessProbePort) + .withPath(livenessProbePath) + .endHttpGet() + .endLivenessProbe() + .addAllToEnv(envVars) + .endContainer() + .endSpec() + .endTemplate() + .endSpec() + .build(); return appsApi.createNamespacedDeployment(namespace, wiremockDeployment, null, null, null, null); } public void waitForEndpointReady(String name, String namespace) { - await().pollInterval(Duration.ofSeconds(1)).atMost(600, TimeUnit.SECONDS) - .until(() -> isEndpointReady(name, namespace)); + await().pollInterval(Duration.ofSeconds(1)) + .atMost(600, TimeUnit.SECONDS) + .until(() -> isEndpointReady(name, namespace)); } public boolean isEndpointReady(String name, String namespace) throws ApiException { @@ -205,8 +246,9 @@ public boolean isEndpointReady(String name, String namespace) throws ApiExceptio } public void waitForReplicationController(String name, String namespace) { - await().pollInterval(Duration.ofSeconds(1)).atMost(600, TimeUnit.SECONDS) - .until(() -> isReplicationControllerReady(name, namespace)); + await().pollInterval(Duration.ofSeconds(1)) + .atMost(600, TimeUnit.SECONDS) + .until(() -> isReplicationControllerReady(name, namespace)); } public boolean isReplicationControllerReady(String name, String namespace) throws ApiException { @@ -224,15 +266,17 @@ public boolean isReplicationControllerReady(String name, String namespace) throw } public void waitForDeployment(String deploymentName, String namespace) { - await().pollInterval(Duration.ofSeconds(1)).atMost(600, TimeUnit.SECONDS) - .until(() -> isDeploymentReady(deploymentName, namespace)); + await().pollInterval(Duration.ofSeconds(1)) + .atMost(600, TimeUnit.SECONDS) + .until(() -> isDeploymentReady(deploymentName, namespace)); } public void waitForIngress(String ingressName, String namespace) { await().timeout(Duration.ofSeconds(90)).pollInterval(Duration.ofSeconds(3)).until(() -> { try { V1IngressLoadBalancerStatus status = networkingApi.readNamespacedIngress(ingressName, namespace, null) - .getStatus().getLoadBalancer(); + .getStatus() + .getLoadBalancer(); if (status == null) { log.info("ingress : " + ingressName + " not ready yet (loadbalancer not yet present)"); @@ -295,7 +339,7 @@ public void setUp(String namespace) throws Exception { V1ServiceAccount serviceAccount = getConfigK8sClientItServiceAccount(); CheckedSupplier accountSupplier = () -> api - .readNamespacedServiceAccount(serviceAccount.getMetadata().getName(), namespace, null); + .readNamespacedServiceAccount(serviceAccount.getMetadata().getName(), namespace, null); CheckedSupplier accountDefaulter = () -> api.createNamespacedServiceAccount(namespace, serviceAccount, null, null, null, null); notExistsHandler(accountSupplier, accountDefaulter); @@ -312,18 +356,21 @@ public void setUp(String namespace) throws Exception { public void deleteNamespace(String name) throws Exception { api.deleteNamespace(name, null, null, null, null, null, null); - await().pollInterval(Duration.ofSeconds(1)).atMost(30, TimeUnit.SECONDS) - .until(() -> api.listNamespace(null, null, null, null, null, null, null, null, null, null, null) - .getItems().stream().noneMatch(x -> x.getMetadata().getName().equals(name))); + await().pollInterval(Duration.ofSeconds(1)) + .atMost(30, TimeUnit.SECONDS) + .until(() -> api.listNamespace(null, null, null, null, null, null, null, null, null, null, null) + .getItems() + .stream() + .noneMatch(x -> x.getMetadata().getName().equals(name))); } public void setUpClusterWide(String serviceAccountNamespace, Set namespaces) throws Exception { V1ServiceAccount serviceAccount = getConfigK8sClientItClusterServiceAccount(); CheckedSupplier accountSupplier = () -> api - .readNamespacedServiceAccount(serviceAccount.getMetadata().getName(), serviceAccountNamespace, null); + .readNamespacedServiceAccount(serviceAccount.getMetadata().getName(), serviceAccountNamespace, null); CheckedSupplier accountDefaulter = () -> api - .createNamespacedServiceAccount(serviceAccountNamespace, serviceAccount, null, null, null, null); + .createNamespacedServiceAccount(serviceAccountNamespace, serviceAccount, null, null, null, null); notExistsHandler(accountSupplier, accountDefaulter); V1ClusterRole clusterRole = getConfigK8sClientItClusterRole(); diff --git a/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/integration/tests/commons/fabric8_client/Util.java b/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/integration/tests/commons/fabric8_client/Util.java index 9e7b9917fc..e19f68b7b3 100644 --- a/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/integration/tests/commons/fabric8_client/Util.java +++ b/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/integration/tests/commons/fabric8_client/Util.java @@ -74,7 +74,7 @@ public final class Util { public Util(K3sContainer container) { this.container = container; this.client = new KubernetesClientBuilder().withConfig(Config.fromKubeconfig(container.getKubeConfigYaml())) - .build(); + .build(); } /** @@ -89,11 +89,19 @@ public void createAndWait(String namespace, String name, @Nullable Deployment de try { if (deployment != null) { - String imageFromDeployment = deployment.getSpec().getTemplate().getSpec().getContainers().get(0) - .getImage(); + String imageFromDeployment = deployment.getSpec() + .getTemplate() + .getSpec() + .getContainers() + .get(0) + .getImage(); if (changeVersion) { - deployment.getSpec().getTemplate().getSpec().getContainers().get(0) - .setImage(imageFromDeployment + ":" + pomVersion()); + deployment.getSpec() + .getTemplate() + .getSpec() + .getContainers() + .get(0) + .setImage(imageFromDeployment + ":" + pomVersion()); } else { String[] image = imageFromDeployment.split(":", 2); @@ -175,11 +183,17 @@ public InputStream inputStream(String fileName) { public void createNamespace(String name) { try { - client.namespaces().resource(new NamespaceBuilder().withNewMetadata().withName(name).and().build()) - .create(); - - await().pollInterval(Duration.ofSeconds(1)).atMost(30, TimeUnit.SECONDS).until(() -> client.namespaces() - .list().getItems().stream().anyMatch(x -> x.getMetadata().getName().equals(name))); + client.namespaces() + .resource(new NamespaceBuilder().withNewMetadata().withName(name).and().build()) + .create(); + + await().pollInterval(Duration.ofSeconds(1)) + .atMost(30, TimeUnit.SECONDS) + .until(() -> client.namespaces() + .list() + .getItems() + .stream() + .anyMatch(x -> x.getMetadata().getName().equals(name))); } catch (Exception e) { throw new RuntimeException(e); @@ -188,11 +202,17 @@ public void createNamespace(String name) { public void deleteNamespace(String name) { try { - client.namespaces().resource(new NamespaceBuilder().withNewMetadata().withName(name).and().build()) - .delete(); - - await().pollInterval(Duration.ofSeconds(1)).atMost(30, TimeUnit.SECONDS).until(() -> client.namespaces() - .list().getItems().stream().noneMatch(x -> x.getMetadata().getName().equals(name))); + client.namespaces() + .resource(new NamespaceBuilder().withNewMetadata().withName(name).and().build()) + .delete(); + + await().pollInterval(Duration.ofSeconds(1)) + .atMost(30, TimeUnit.SECONDS) + .until(() -> client.namespaces() + .list() + .getItems() + .stream() + .noneMatch(x -> x.getMetadata().getName().equals(name))); } catch (Exception e) { throw new RuntimeException(e); @@ -212,8 +232,10 @@ public void setUpClusterWide(String serviceAccountNamespace, Set namespa ServiceAccount serviceAccountFromStream = client.serviceAccounts().load(serviceAccountAsStream).item(); serviceAccountFromStream.getMetadata().setNamespace(serviceAccountNamespace); - if (client.serviceAccounts().inNamespace(serviceAccountNamespace) - .withName(serviceAccountFromStream.getMetadata().getName()).get() == null) { + if (client.serviceAccounts() + .inNamespace(serviceAccountNamespace) + .withName(serviceAccountFromStream.getMetadata().getName()) + .get() == null) { client.serviceAccounts().inNamespace(serviceAccountNamespace).resource(serviceAccountFromStream).create(); } @@ -221,8 +243,11 @@ public void setUpClusterWide(String serviceAccountNamespace, Set namespa namespaces.forEach(namespace -> { roleBindingFromStream.getMetadata().setNamespace(namespace); - if (client.rbac().roleBindings().inNamespace(namespace) - .withName(roleBindingFromStream.getMetadata().getName()).get() == null) { + if (client.rbac() + .roleBindings() + .inNamespace(namespace) + .withName(roleBindingFromStream.getMetadata().getName()) + .get() == null) { client.rbac().roleBindings().inNamespace(namespace).resource(roleBindingFromStream).create(); } }); @@ -265,8 +290,12 @@ public void setUpIstioctl(String namespace, Phase phase) { InputStream istioctlDeploymentStream = inputStream("istio/istioctl-deployment.yaml"); Deployment istioctlDeployment = Serialization.unmarshal(istioctlDeploymentStream, Deployment.class); - String imageWithoutVersion = istioctlDeployment.getSpec().getTemplate().getSpec().getContainers().get(0) - .getImage(); + String imageWithoutVersion = istioctlDeployment.getSpec() + .getTemplate() + .getSpec() + .getContainers() + .get(0) + .getImage(); String imageWithVersion = imageWithoutVersion + ":" + Images.istioVersion(); istioctlDeployment.getSpec().getTemplate().getSpec().getContainers().get(0).setImage(imageWithVersion); @@ -281,8 +310,13 @@ public void setUpIstioctl(String namespace, Phase phase) { private void waitForConfigMap(String namespace, ConfigMap configMap, Phase phase) { String configMapName = configMapName(configMap); await().pollInterval(Duration.ofSeconds(1)).atMost(600, TimeUnit.SECONDS).until(() -> { - int size = (int) client.configMaps().inNamespace(namespace).list().getItems().stream() - .filter(x -> x.getMetadata().getName().equals(configMapName)).count(); + int size = (int) client.configMaps() + .inNamespace(namespace) + .list() + .getItems() + .stream() + .filter(x -> x.getMetadata().getName().equals(configMapName)) + .count(); if (size == 0) { return !phase.equals(Phase.CREATE); } @@ -333,8 +367,13 @@ public void wiremock(String namespace, String path, Phase phase, boolean withIng private void waitForSecret(String namespace, Secret secret, Phase phase) { String secretName = secretName(secret); await().pollInterval(Duration.ofSeconds(1)).atMost(600, TimeUnit.SECONDS).until(() -> { - int size = (int) client.secrets().inNamespace(namespace).list().getItems().stream() - .filter(x -> x.getMetadata().getName().equals(secretName)).count(); + int size = (int) client.secrets() + .inNamespace(namespace) + .list() + .getItems() + .stream() + .filter(x -> x.getMetadata().getName().equals(secretName)) + .count(); if (size == 0) { return !phase.equals(Phase.CREATE); } @@ -369,8 +408,9 @@ private void waitForDeploymentToBeDeleted(String namespace, Deployment deploymen private void waitForDeployment(String namespace, Deployment deployment) { String deploymentName = deploymentName(deployment); - await().pollInterval(Duration.ofSeconds(2)).atMost(600, TimeUnit.SECONDS) - .until(() -> isDeploymentReady(namespace, deploymentName)); + await().pollInterval(Duration.ofSeconds(2)) + .atMost(600, TimeUnit.SECONDS) + .until(() -> isDeploymentReady(namespace, deploymentName)); } private boolean isDeploymentReady(String namespace, String deploymentName) { @@ -423,16 +463,21 @@ public void patchWithReplace(String imageName, String deploymentName, String nam Map labels) { String body = patchBody.replace("image_name_here", imageName); - client.apps().deployments().inNamespace(namespace).withName(deploymentName) - .patch(PatchContext.of(PatchType.JSON_MERGE), body); + client.apps() + .deployments() + .inNamespace(namespace) + .withName(deploymentName) + .patch(PatchContext.of(PatchType.JSON_MERGE), body); waitForDeploymentAfterPatch(deploymentName, namespace, labels); } private void waitForDeploymentAfterPatch(String deploymentName, String namespace, Map labels) { try { - await().pollDelay(Duration.ofSeconds(4)).pollInterval(Duration.ofSeconds(3)).atMost(60, TimeUnit.SECONDS) - .until(() -> isDeploymentReadyAfterPatch(deploymentName, namespace, labels)); + await().pollDelay(Duration.ofSeconds(4)) + .pollInterval(Duration.ofSeconds(3)) + .atMost(60, TimeUnit.SECONDS) + .until(() -> isDeploymentReadyAfterPatch(deploymentName, namespace, labels)); } catch (Exception e) { throw new RuntimeException(e); @@ -448,8 +493,11 @@ private boolean isDeploymentReadyAfterPatch(String deploymentName, String namesp fail("No deployment with name " + deploymentName); } - Deployment deployment = deployments.getItems().stream() - .filter(x -> x.getMetadata().getName().equals(deploymentName)).findFirst().orElseThrow(); + Deployment deployment = deployments.getItems() + .stream() + .filter(x -> x.getMetadata().getName().equals(deploymentName)) + .findFirst() + .orElseThrow(); // if no replicas are defined, it means only 1 is needed int replicas = Optional.ofNullable(deployment.getSpec().getReplicas()).orElse(1); @@ -466,23 +514,36 @@ private boolean isDeploymentReadyAfterPatch(String deploymentName, String namesp private void innerSetup(String namespace, InputStream serviceAccountAsStream, InputStream roleBindingAsStream, InputStream roleAsStream) { - ServiceAccount serviceAccountFromStream = client.serviceAccounts().inNamespace(namespace) - .load(serviceAccountAsStream).item(); - if (client.serviceAccounts().inNamespace(namespace).withName(serviceAccountFromStream.getMetadata().getName()) - .get() == null) { + ServiceAccount serviceAccountFromStream = client.serviceAccounts() + .inNamespace(namespace) + .load(serviceAccountAsStream) + .item(); + if (client.serviceAccounts() + .inNamespace(namespace) + .withName(serviceAccountFromStream.getMetadata().getName()) + .get() == null) { client.serviceAccounts().inNamespace(namespace).resource(serviceAccountFromStream).create(); } - RoleBinding roleBindingFromStream = client.rbac().roleBindings().inNamespace(namespace) - .load(roleBindingAsStream).item(); - if (client.rbac().roleBindings().inNamespace(namespace).withName(roleBindingFromStream.getMetadata().getName()) - .get() == null) { + RoleBinding roleBindingFromStream = client.rbac() + .roleBindings() + .inNamespace(namespace) + .load(roleBindingAsStream) + .item(); + if (client.rbac() + .roleBindings() + .inNamespace(namespace) + .withName(roleBindingFromStream.getMetadata().getName()) + .get() == null) { client.rbac().roleBindings().inNamespace(namespace).resource(roleBindingFromStream).create(); } Role roleFromStream = client.rbac().roles().inNamespace(namespace).load(roleAsStream).item(); - if (client.rbac().roles().inNamespace(namespace).withName(roleFromStream.getMetadata().getName()) - .get() == null) { + if (client.rbac() + .roles() + .inNamespace(namespace) + .withName(roleFromStream.getMetadata().getName()) + .get() == null) { client.rbac().roles().inNamespace(namespace).resource(roleFromStream).create(); } } diff --git a/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/integration/tests/commons/native_client/Util.java b/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/integration/tests/commons/native_client/Util.java index 2d225082d3..c9de654263 100644 --- a/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/integration/tests/commons/native_client/Util.java +++ b/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/integration/tests/commons/native_client/Util.java @@ -120,11 +120,19 @@ public void createAndWait(String namespace, String name, V1Deployment deployment coreV1Api.createNamespacedService(namespace, service, null, null, null, null); if (deployment != null) { - String imageFromDeployment = deployment.getSpec().getTemplate().getSpec().getContainers().get(0) - .getImage(); + String imageFromDeployment = deployment.getSpec() + .getTemplate() + .getSpec() + .getContainers() + .get(0) + .getImage(); if (changeVersion) { - deployment.getSpec().getTemplate().getSpec().getContainers().get(0) - .setImage(imageFromDeployment + ":" + pomVersion()); + deployment.getSpec() + .getTemplate() + .getSpec() + .getContainers() + .get(0) + .setImage(imageFromDeployment + ":" + pomVersion()); } else { String[] image = imageFromDeployment.split(":", 2); @@ -204,7 +212,10 @@ public void deleteAndWait(String namespace, V1Deployment deployment, V1Service s try { String deploymentName = deploymentName(deployment); Map podLabels = appsV1Api.readNamespacedDeployment(deploymentName, namespace, null) - .getSpec().getTemplate().getMetadata().getLabels(); + .getSpec() + .getTemplate() + .getMetadata() + .getLabels(); appsV1Api.deleteNamespacedDeployment(deploymentName, namespace, null, null, null, null, null, null); coreV1Api.deleteCollectionNamespacedPod(namespace, null, null, null, null, null, labelSelector(podLabels), null, null, null, null, null, null, null, null); @@ -291,7 +302,7 @@ else if (phase.equals(Phase.DELETE)) { public Object yaml(String fileName) { ClassLoader classLoader = Util.class.getClassLoader(); String file = new BufferedReader(new InputStreamReader(classLoader.getResourceAsStream(fileName))).lines() - .collect(Collectors.joining("\n")); + .collect(Collectors.joining("\n")); try { return Yaml.load(file); } @@ -305,9 +316,9 @@ public void setUp(String namespace) { try { V1ServiceAccount serviceAccount = (V1ServiceAccount) yaml("setup/service-account.yaml"); CheckedSupplier accountSupplier = () -> coreV1Api - .readNamespacedServiceAccount(serviceAccount.getMetadata().getName(), namespace, null); + .readNamespacedServiceAccount(serviceAccount.getMetadata().getName(), namespace, null); CheckedSupplier accountDefaulter = () -> coreV1Api - .createNamespacedServiceAccount(namespace, serviceAccount, null, null, null, null); + .createNamespacedServiceAccount(namespace, serviceAccount, null, null, null, null); notExistsHandler(accountSupplier, accountDefaulter); V1RoleBinding roleBinding = (V1RoleBinding) yaml("setup/role-binding.yaml"); @@ -329,10 +340,10 @@ public void setUpClusterWideClusterRoleBinding(String serviceAccountNamespace) { try { V1ServiceAccount serviceAccount = (V1ServiceAccount) yaml("cluster/service-account.yaml"); - CheckedSupplier accountSupplier = () -> coreV1Api.readNamespacedServiceAccount( - serviceAccount.getMetadata().getName(), serviceAccountNamespace, null); + CheckedSupplier accountSupplier = () -> coreV1Api + .readNamespacedServiceAccount(serviceAccount.getMetadata().getName(), serviceAccountNamespace, null); CheckedSupplier accountDefaulter = () -> coreV1Api - .createNamespacedServiceAccount(serviceAccountNamespace, serviceAccount, null, null, null, null); + .createNamespacedServiceAccount(serviceAccountNamespace, serviceAccount, null, null, null, null); notExistsHandler(accountSupplier, accountDefaulter); V1ClusterRole clusterRole = (V1ClusterRole) yaml("cluster/cluster-role.yaml"); @@ -372,10 +383,10 @@ public void setUpClusterWide(String serviceAccountNamespace, Set namespa try { V1ServiceAccount serviceAccount = (V1ServiceAccount) yaml("cluster/service-account.yaml"); - CheckedSupplier accountSupplier = () -> coreV1Api.readNamespacedServiceAccount( - serviceAccount.getMetadata().getName(), serviceAccountNamespace, null); + CheckedSupplier accountSupplier = () -> coreV1Api + .readNamespacedServiceAccount(serviceAccount.getMetadata().getName(), serviceAccountNamespace, null); CheckedSupplier accountDefaulter = () -> coreV1Api - .createNamespacedServiceAccount(serviceAccountNamespace, serviceAccount, null, null, null, null); + .createNamespacedServiceAccount(serviceAccountNamespace, serviceAccount, null, null, null, null); notExistsHandler(accountSupplier, accountDefaulter); V1ClusterRole clusterRole = (V1ClusterRole) yaml("cluster/cluster-role.yaml"); @@ -435,9 +446,12 @@ public void deleteNamespace(String name) { throw new RuntimeException(e); } - await().pollInterval(Duration.ofSeconds(1)).atMost(30, TimeUnit.SECONDS) - .until(() -> coreV1Api.listNamespace(null, null, null, null, null, null, null, null, null, null, null) - .getItems().stream().noneMatch(x -> x.getMetadata().getName().equals(name))); + await().pollInterval(Duration.ofSeconds(1)) + .atMost(30, TimeUnit.SECONDS) + .until(() -> coreV1Api.listNamespace(null, null, null, null, null, null, null, null, null, null, null) + .getItems() + .stream() + .noneMatch(x -> x.getMetadata().getName().equals(name))); } public void wiremock(String namespace, String path, Phase phase) { @@ -533,8 +547,10 @@ private String secretName(V1Secret secret) { private void waitForDeployment(String namespace, V1Deployment deployment) { String deploymentName = deploymentName(deployment); - await().pollDelay(Duration.ofSeconds(5)).pollInterval(Duration.ofSeconds(5)).atMost(900, TimeUnit.SECONDS) - .until(() -> isDeploymentReady(deploymentName, namespace)); + await().pollDelay(Duration.ofSeconds(5)) + .pollInterval(Duration.ofSeconds(5)) + .atMost(900, TimeUnit.SECONDS) + .until(() -> isDeploymentReady(deploymentName, namespace)); } private void waitForConfigMap(String namespace, V1ConfigMap configMap, Phase phase) { @@ -575,7 +591,8 @@ private void waitForIngress(String namespace, V1Ingress ingress) { await().timeout(Duration.ofSeconds(90)).pollInterval(Duration.ofSeconds(3)).until(() -> { try { V1IngressLoadBalancerStatus status = networkingV1Api.readNamespacedIngress(ingressName, namespace, null) - .getStatus().getLoadBalancer(); + .getStatus() + .getLoadBalancer(); if (status == null) { LOG.info("ingress : " + ingressName + " not ready yet (loadbalancer not yet present)"); @@ -624,8 +641,11 @@ private void waitForDeploymentToBeDeleted(String deploymentName, String namespac private void waitForDeploymentPodsToBeDeleted(Map labels, String namespace) { await().timeout(Duration.ofSeconds(180)).until(() -> { try { - int currentNumberOfPods = coreV1Api.listNamespacedPod(namespace, null, null, null, null, - labelSelector(labels), null, null, null, null, null, null).getItems().size(); + int currentNumberOfPods = coreV1Api + .listNamespacedPod(namespace, null, null, null, null, labelSelector(labels), null, null, null, null, + null, null) + .getItems() + .size(); return currentNumberOfPods == 0; } catch (ApiException e) { @@ -685,8 +705,10 @@ private void logDeploymentConditions(List conditions) { private static void waitForDeploymentAfterPatch(String deploymentName, String namespace, Map podLabels) { try { - await().pollDelay(Duration.ofSeconds(4)).pollInterval(Duration.ofSeconds(3)).atMost(60, TimeUnit.SECONDS) - .until(() -> isDeploymentReadyAfterPatch(deploymentName, namespace, podLabels)); + await().pollDelay(Duration.ofSeconds(4)) + .pollInterval(Duration.ofSeconds(3)) + .atMost(60, TimeUnit.SECONDS) + .until(() -> isDeploymentReadyAfterPatch(deploymentName, namespace, podLabels)); } catch (Exception e) { if (e instanceof ApiException apiException) { @@ -717,8 +739,11 @@ private static boolean isDeploymentReadyAfterPatch(String deploymentName, String return false; } - int pods = new CoreV1Api().listNamespacedPod(namespace, null, null, null, null, labelSelector(podLabels), null, - null, null, null, null, null).getItems().size(); + int pods = new CoreV1Api() + .listNamespacedPod(namespace, null, null, null, null, labelSelector(podLabels), null, null, null, null, + null, null) + .getItems() + .size(); if (pods != replicas) { LOG.info("number of pods not yet stabilized"); diff --git a/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/tests/discovery/TestsDiscovery.java b/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/tests/discovery/TestsDiscovery.java index f3605769e8..271c35996c 100644 --- a/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/tests/discovery/TestsDiscovery.java +++ b/spring-cloud-kubernetes-test-support/src/main/java/org/springframework/cloud/kubernetes/tests/discovery/TestsDiscovery.java @@ -48,23 +48,31 @@ public static void main(String[] args) throws Exception { List targetTestClasses = targetClasses.stream().map(x -> x.replace("classes", "test-classes")).toList(); List jars = classpathEntries.stream().filter(x -> x.contains(".jar")).toList(); - List urls = Stream.of(targetClasses, targetTestClasses, jars).flatMap(List::stream) - .map(x -> toURL(new File(x).toPath().toUri())).toList(); + List urls = Stream.of(targetClasses, targetTestClasses, jars) + .flatMap(List::stream) + .map(x -> toURL(new File(x).toPath().toUri())) + .toList(); - Set paths = Stream.of(targetClasses, targetTestClasses, jars).flatMap(List::stream).map(Paths::get) - .collect(Collectors.toSet()); + Set paths = Stream.of(targetClasses, targetTestClasses, jars) + .flatMap(List::stream) + .map(Paths::get) + .collect(Collectors.toSet()); replaceClassloader(urls); LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() - .selectors(DiscoverySelectors.selectClasspathRoots(paths)).build(); + .selectors(DiscoverySelectors.selectClasspathRoots(paths)) + .build(); try (LauncherSession session = LauncherFactory.openSession()) { Launcher launcher = session.getLauncher(); TestPlan testPlan = launcher.discover(request); - testPlan.getRoots().stream().flatMap(x -> testPlan.getChildren(x).stream()) - .map(TestIdentifier::getLegacyReportingName).sorted() - .forEach(test -> System.out.println("spring.cloud.k8s.test.to.run -> " + test)); + testPlan.getRoots() + .stream() + .flatMap(x -> testPlan.getChildren(x).stream()) + .map(TestIdentifier::getLegacyReportingName) + .sorted() + .forEach(test -> System.out.println("spring.cloud.k8s.test.to.run -> " + test)); } }