patch_kubernetes

safir.testing.kubernetes.patch_kubernetes()

Replace the Kubernetes API with a mock class.

Returns:

The mock Kubernetes API object.

Return type:

MockKubernetesApi

Notes

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.

Examples

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

from safir.testing.kubernetes import MockKubernetesApi, patch_kubernetes

@pytest.fixture
def mock_kubernetes() -> Iterator[MockKubernetesApi]:
    yield from patch_kubernetes()