fabric8io / kubernetes-client

Java client for Kubernetes & OpenShift
http://fabric8.io
Apache License 2.0
3.4k stars 1.46k forks source link

Mocked KubernetesResponseComposer default response has no metadata #1317

Closed scotts closed 4 years ago

scotts commented 5 years ago

Because KubernetesResponseComposer has no mocked metadata in its compose method, trying to test custom resource definitions with a mocked server throws a NullPointerException when trying to start the controller for that custom resource. The relevant stack trace:

java.lang.NullPointerException
    at org.microbean.kubernetes.controller.Reflector.start(Reflector.java:838)
    at org.microbean.kubernetes.controller.Controller.start(Controller.java:549)

Looking closely at Reflector, it assumes that the response from the client will have metadata with a resource version. However, the current default response for nothing being in the mocked server, as implemented in KubernetesResponseComposter, clearly does not have metadata: "{\"apiVersion\":\"v1\",\"kind\":\"List\", \"items\": [%s]}"

There is a workaround for users that does not require changes to the library, which is to define your own response and pass that in to the mocked server. First, define:

public class MetadataKubeResponseComposer extends KubernetesResponseComposer {
    @Override
    public String compose(Collection<String> collection) {
        return String.format(
            "{\"apiVersion\":\"v1\",\"kind\":\"List\", \"items\": [%s], \"metadata\": {\"resourceVersion\":\"v1alpha1\"}}\n",
            String.join(",", collection));
    }
}

And then use it when creating a mocked server. Note that I was already not using KubernetesServer because of issue #1243:

final boolean https = false;
KubernetesMockServer server = new KubernetesMockServer(
    new Context(),
    new MockWebServer(),
    new HashMap<ServerRequest, Queue<ServerResponse>>(),
    new KubernetesCrudDispatcher(
        new KubernetesAttributesExtractor(),
        new MetadataKubeResponseComposer()), // class defined above
    https);
stale[bot] commented 5 years ago

This issue has been automatically marked as stale because it has not had any activity since 90 days. It will be closed if no further activity occurs within 7 days. Thank you for your contributions!