<p>I am using Kubernetes client: <a href="https://pypi.org/project/kubernetes/" rel="nofollow noreferrer">Kubernetes</a></p>
<p>My function:</p>
<pre><code>    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[&quot;value&quot;])}')
    except Exception as e:
        logging.error(f'Error retrieving Kubernetes Secret: {e}')
        raise e
    return secret
</code></pre>
<p>Unit test:</p>
<pre><code>@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()
</code></pre>
<p>I am mocking __get_kubernetes_config() private method just fine.  I need to mock &quot;api.read_namespaced_secret()&quot; call.  I've tried &quot;with patch.object&quot; as shown above, but that's making an actual call.  Is it possible to mock?</p>

obautista
<p>Everything (or almost everything) is possible to mock :)</p>
<p>In this example you're mocking method on actual instance of <code>CoreV1Api</code>, but inside your method <code>__get_gateway_token_secret</code> you're creating a distinct new instance of <code>CoreV1APi</code>.</p>
<p>You should apply patch to class, not an instance. Or refactor your code.</p>
