Home > Back-end >  How do you mock Python Kubernetes client CoreV1Api
How do you mock Python Kubernetes client CoreV1Api

Time:02-17

I am using Kubernetes client: Kubernetes

My function:

    def __get_gateway_token_secret(self):
    try:
        self.__get_kubernetes_config()
        api = client.CoreV1Api()
        secret = api.read_namespaced_secret(self.secret_name, self.namespace)
        logging.debug(f'Kubernetes secret found: {base64.b64decode(secret.data["value"])}')
    except Exception as e:
        logging.error(f'Error retrieving Kubernetes Secret: {e}')
        raise e
    return secret

Unit test:

@patch.object(K8s, '_K8s__get_kubernetes_config')
def test_get_gateway_token_secret_returns_secret(self, kubernetes_config_mock):
    kubernetes_config_mock.return_value = MagicMock()

    api = client.CoreV1Api()
    test_object = K8s()

    with patch.object(api, 'read_namespaced_secret', return_value='test'):
        result = test_object._K8s__get_gateway_token_secret()

I am mocking __get_kubernetes_config() private method just fine. I need to mock "api.read_namespaced_secret()" call. I've tried "with patch.object" as shown above, but that's making an actual call. Is it possible to mock?

CodePudding user response:

Everything (or almost everything) is possible to mock :)

In this example you're mocking method on actual instance of CoreV1Api, but inside your method __get_gateway_token_secret you're creating a distinct new instance of CoreV1APi.

You should apply patch to class, not an instance. Or refactor your code.

  • Related