Replace the Kubernetes API with a mock class.


mock_kubernetes – The mock Kubernetes API object.

Return type:



This function will mock out the Kuberentes library configuration API in a manner compatible with safir.kubernetes.initialize_kubernetes, ensuring that it does nothing during test. It will replace the Kubernetes ApiClient object with a MagicMock and then redirect CoreV1Api and CustomObjectsApi to a MockKubernetesApi instance.

To use this mock successfully, you must not import ApiClient, CoreV1Api, or CustomObjectsApi directly into the local namespace, or they will not be correctly patched. Instead, use:

from kubernetes_asyncio import client

and then use client.ApiClient and so forth.


Normally this should be called from a fixture in tests/ such as the following:

from safir.testing.kubernetes import MockKubernetesApi, patch_kubernetes

def mock_kubernetes() -> Iterator[MockKubernetesApi]:
    yield from patch_kubernetes()