<p>I want to mock a response from the Python Kubernetes client. Below code of my Kubernetes service:</p>
<pre class="lang-py prettyprint-override"><code>import os

from kubernetes.client.rest import ApiException
from kubernetes import client
from kubernetes.config import load_config
from exceptions.logs_not_found_exceptions import LogsNotFound
import logging

log = logging.getLogger(&quot;services/kubernetes_service.py&quot;)


class KubernetesService:
    def __init__(self):
        super().__init__()
        if os.getenv(&quot;DISABLE_KUBERNETES_CONFIG&quot;) == &quot;False&quot;:
            load_config()

        self.api_instance = client.CoreV1Api()

    def get_namespaces(self):
        try:
            api_response = self.api_instance.list_namespace()
            dict_response = api_response.to_dict()

            namespaces = []
            for item in dict_response['items']:
                namespaces.append(item['metadata']['name'])

            log.info(f&quot;Retrieved the namespaces: {namespaces}&quot;)
            return namespaces
        except ApiException as e:
            raise e
</code></pre>
<p>When I want to mock this using mock.patch I'm getting a ModuleNotFoundError. Below code of my Test class</p>
<pre class="lang-py prettyprint-override"><code>import os
from unittest import mock
from tests.unit_tests import utils
from services.kubernetes_service import KubernetesService

class TestKubernetesService:
    @mock.patch.dict(os.environ, {&quot;DISABLE_KUBERNETES_CONFIG&quot;: &quot;True&quot;})
    def test_get_namespaces(self):
        self.service = KubernetesService()
        print(self.service.api_instance)
        with mock.patch('services.kubernetes_service.KubernetesService.api_instance.list_namespace',
                        return_value=utils.kubernetes_namespaces_response()):
            actual_result = self.service.get_namespaces()
            assert actual_result == ['default', 'kube-node-lease', 'kube-public', 'kube-system']

</code></pre>
<p>When I edit the path in <code>mock.patch</code> from <code>services.kubernetes_service.KubernetesService.api_instance.list_namespace</code> to <code>services.kubernetes_service.KubernetesService.get_namespaces</code> it successfully mocks the return value I put in. But I want to mock the response of the line <code>self.api_instance.list_namespace()</code> in the KubernetesService class.</p>
<p>Someone an idea?</p>

Lucas Scheepers
<p>In your example, you try to patch an instance attribute of the class (<code>api_instance</code>). This cannot be done by just referencing it from the class, as it is not a class attribute - you need an instance instead.</p>
<p>There are generally two standard methods to mock an instance attribute:</p>
<ul>
<li>mock the whole class, in which case the <code>return_value</code> attribute on the mocked class will be a mock that replaces any instance of the class and can therefore be used for mocking instance attributes</li>
<li>mock a concrete instance using <a href="https://docs.python.org/3/library/unittest.mock.html#patch-object" rel="nofollow noreferrer">mock.patch.object</a> or similar - this requires that you have access to the instance in your test</li>
</ul>
<p>Mocking the whole class is not an option in your case, as you need to use the functionality of the class, but as you have access to the instance via <code>self.service</code>, you can use <code>patch.object</code>:</p>
<pre class="lang-py prettyprint-override"><code>    def test_get_namespaces(self):
        self.service = KubernetesService()
        with mock.patch.object(self.service.api_instance, 'list_namespace', 
                               return_value=utils.kubernetes_namespaces_response()):
            actual_result = self.service.get_namespaces()
            assert actual_result == ['default', 'kube-node-lease', 'kube-public', 'kube-system']
</code></pre>
