I'm using Spring Boot 2.3.9.RELEASE and have an auto-configuration class annotated with @ConditionalOnCloudPlatform(CloudPlatform.KUBERNETES)
. In the tests for this auto-configuration class I want to verify that this auto-configuration is only executed when running on Kubernetes.
I have these two tests:
@Test
void should_load_config_when_on_kubernetes() {
new ApplicationContextRunner()
.withUserConfiguration(DefaultConfiguration.class)
.withSystemProperties("spring.main.cloud-platform=kubernetes")
.run(context -> assertThat(context).hasSingleBean(LocalPod.class));
}
@Test
void should_not_load_configuration_when_not_on_kubernetes() {
new ApplicationContextRunner()
.withUserConfiguration(DefaultConfiguration.class)
.withSystemProperties("spring.main.cloud-platform=none")
.run(context -> assertThat(context).doesNotHaveBean(LocalPod.class));
}
These tests pass locally on my machine, but on GitLab CI these tests are executed in a GitLab Runner running on Kubernetes. In that setup the second test fails. The reason for this seems to be that the logic for @ConditionalOnCloudPlatform
in OnCloudPlatformCondition
calls CloudPlatform.isActive(Environment)
, which is implemented like this:
public boolean isActive(Environment environment) {
return isEnforced(environment) || isDetected(environment);
}
This means that even when setting spring.main.cloud-platform=none
to force the cloud platform to be CloudPlatform.NONE
in a test, the actual cloud platform the code is running on will still be detected, so you can't simulate not running on a cloud platform in a test.
I would expect CloudPlatform.isActive
to be implemented like this, so detection is only used if a cloud platform is not explicitly forced:
public boolean isActive(Environment environment) {
if (isEnforced(environment)) return true;
return isDetected(environment);
}
Comment From: wilkinsona
Thanks for the report. That sounds like a bug to me. Not only will the condition behave incorrectly but I think both NONE
and KUBERNETES
will say that they're active while CloudPlatform.getActive(Environment)
with return NONE
.
Comment From: philwebb
Closing in favor of PR #25455