Kubernetes Advanced
Before going further, make sure that you have quarkus-kubernetes dependency in your pom.xml .
|
In the previous examples we used the autogenerated files together with YAML fragments defined in src/main/kubernetes
for deploying to Kubernetes/OpenShift.
As involuntary mistakes can occur in manually created YAML files, it would be great to test those before applying them in any namespace.
To make testing against a mock Kubernetes API extremely simple, Quarkus provides the WithKubernetesTestServer
annotation which automatically launches a mock of the Kubernetes API server and sets the proper environment variables needed.
To take advantage of these features, the quarkus-test-kubernetes-client
dependency needs to be added in pom.xml
:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-test-kubernetes-client</artifactId>
<scope>test</scope>
</dependency>
Integration tests to avoid Kubernetes YAML issues
In the folder src/main/kubernetes
add pdb.yml
file with the following content:
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
spec:
minAvailable: 1
selector:
matchLabels:
app.kubernetes.io/name: quarkus-app-workshop
Typically you will install src/main/kubernetes/pdb.yml
in an Kubernetes/OpenShift environment and will observe that the configuration is rejected.
However, you can avoid such a scenario by creating an integration test for the PodDisruptionBudget
resource defined in the file:
package org.acme;
import io.fabric8.kubernetes.api.model.policy.v1.PodDisruptionBudget;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.server.mock.KubernetesServer;
import io.quarkus.test.junit.DisabledOnNativeImage;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.kubernetes.client.KubernetesTestServer;
import io.quarkus.test.kubernetes.client.WithKubernetesTestServer;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
@WithKubernetesTestServer(1)
@QuarkusTest
@DisabledOnNativeImage(2)
public class PodDisruptionBudgetTest {
@KubernetesTestServer(3)
KubernetesServer mocKubernetesServer;
@Test
public void testPdbFromFile() {
String path = "./src/main/kubernetes/pdb.yml";(4)
PodDisruptionBudget pdb = mocKubernetesServer.getClient().policy().v1().podDisruptionBudget().load(path).get();
assertThrows(KubernetesClientException.class, () -> mocKubernetesServer.getClient().policy().v1().podDisruptionBudget().create(pdb));(5)
}
}
1 | Annotate the test as one working in a mocked Kubernetes context. |
2 | Exclude this test when running the native executable. |
3 | Add the mock Kubernetes server context. |
4 | Specify the path to the resource under test. |
5 | Try to create the Kubernetes resource based on the configuration inside file. |
By running the test (via ContinuousTesting/IDE/application package) you can get exceptions but also what is wrong with the resource.