Miretpl commented on code in PR #71349:
URL: https://github.com/apache/airflow/pull/71349#discussion_r4672734005


##########
providers/google/tests/unit/google/cloud/hooks/test_kubernetes_engine.py:
##########
@@ -582,6 +590,212 @@ async def test_read_logs(self, read_namespaced_pod_log, 
get_conn_mock, async_hoo
         assert "Test string #1" in logs
         assert "Test string #2" in logs
 
+    @staticmethod
+    def _mock_token(tokens):
+        token = mock.create_autospec(_CredentialsToken, instance=True)
+        token.get.side_effect = list(tokens)
+        return token
+
+    @pytest.mark.asyncio
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook.get_token"), 
autospec=True)
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook._build_client"), 
autospec=True)
+    async def test_get_conn_caches_client_and_token(self, mock_build_client, 
mock_get_token, async_hook):
+        mock_get_token.return_value = self._mock_token(["token-1", "token-1"])
+        mock_build_client.return_value = 
mock.MagicMock(spec=async_client.ApiClient, default_headers={})
+
+        async with async_hook.get_conn() as conn_first:
+            pass
+        async with async_hook.get_conn() as conn_second:
+            pass
+
+        assert conn_first is conn_second
+        mock_build_client.assert_called_once_with(async_hook)
+        mock_get_token.assert_awaited_once()
+
+    @pytest.mark.asyncio
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook.get_token"), 
autospec=True)
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook._build_client"), 
autospec=True)
+    async def test_get_conn_refreshes_authorization_header_per_entry(
+        self, mock_build_client, mock_get_token, async_hook
+    ):
+        mock_get_token.return_value = self._mock_token(["token-1", "token-2"])
+        kube_client = mock.MagicMock(spec=async_client.ApiClient, 
default_headers={})
+        mock_build_client.return_value = kube_client
+
+        async with async_hook.get_conn():
+            assert kube_client.default_headers["Authorization"] == "Bearer 
token-1"
+        async with async_hook.get_conn():
+            assert kube_client.default_headers["Authorization"] == "Bearer 
token-2"
+
+    @pytest.mark.asyncio
+    @pytest.mark.parametrize("elapsed", [301, 601])
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook.get_token"), 
autospec=True)
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook._build_client"), 
autospec=True)
+    async def test_cached_client_refreshes_short_lived_credentials(
+        self, mock_build_client, mock_get_token, async_hook, elapsed
+    ):
+        credentials = mock.MagicMock(spec=Credentials)
+        credentials.token = "token-1"
+        credentials.expiry = datetime(2026, 1, 1, 0, 10)
+        mock_get_token.return_value = _CredentialsToken(credentials)
+        kube_client = mock_build_client.return_value
+        kube_client.default_headers = {}
+
+        with time_machine.travel("2026-01-01 00:00:00+00:00", tick=False) as 
clock:
+            async with async_hook.get_conn() as first_client:
+                assert first_client.default_headers["Authorization"] == 
"Bearer token-1"
+
+            clock.shift(timedelta(seconds=elapsed))
+            credentials.token = "token-2"
+            credentials.expiry = datetime(2026, 1, 1, 0, 20)
+            async with async_hook.get_conn() as second_client:
+                assert second_client is first_client
+                assert second_client.default_headers["Authorization"] == 
"Bearer token-2"
+
+        mock_build_client.assert_called_once()
+        mock_get_token.assert_awaited_once()
+        assert credentials.refresh.call_count == 2
+
+    @pytest_asyncio.fixture
+    async def authenticated_async_hook(self, async_hook):
+        try:
+            yield async_hook
+        finally:
+            await async_hook.close()
+
+    @staticmethod
+    def _mock_api_response(status=200):
+        response = mock.Mock(
+            spec=RESTResponse,
+            status=status,
+            reason="test response",
+            data=b'{"metadata": {"name": "test-pod-name"}, "items": []}',
+        )
+        response.getheader.return_value = "application/json"
+        response.getheaders.return_value = {}
+        return response
+
+    @pytest.mark.asyncio
+    @pytest.mark.parametrize("operation", ["get_pod", "list_pods"])
+    @time_machine.travel("2026-01-01 00:00:00+00:00", tick=False)
+    @mock.patch("kubernetes_asyncio.client.rest.RESTClientObject.request", 
autospec=True)
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook._get_config"), 
autospec=True)
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook.get_token"), 
autospec=True)
+    async def test_cached_client_refreshes_rejected_credentials(
+        self, mock_get_token, mock_get_config, mock_request, 
authenticated_async_hook, operation
+    ):
+        hook = authenticated_async_hook
+        credentials = mock.Mock(spec=Credentials, token="token-1", 
expiry=datetime(2026, 1, 1, 1))
+        mock_get_token.side_effect = lambda *args, **kwargs: 
_CredentialsToken(credentials)
+        mock_get_config.return_value = 
async_client.Configuration(host=CLUSTER_URL)
+        mock_request.side_effect = [
+            self._mock_api_response(),
+            
async_client.ApiException(http_resp=self._mock_api_response(status=401)),
+            self._mock_api_response(),
+        ]
+        kwargs = {"namespace": POD_NAMESPACE}
+        kwargs.update({"name": POD_NAME} if operation == "get_pod" else 
{"label_selector": "job-name=test"})
+
+        await getattr(hook, operation)(**kwargs)
+        cached_client = hook._cached_kube_client
+        credentials.token = "token-2"
+        await getattr(hook, operation)(**kwargs)
+
+        assert hook._cached_kube_client is cached_client
+        assert cached_client.default_headers["Authorization"] == "Bearer 
token-2"
+        assert [call.kwargs["headers"]["Authorization"] for call in 
mock_request.call_args_list] == [
+            "Bearer token-1",
+            "Bearer token-1",
+            "Bearer token-2",
+        ]
+        assert credentials.refresh.call_count == 2
+
+    @pytest.mark.asyncio
+    @pytest.mark.parametrize(
+        ("initial_status", "retry_status"),
+        [(401, 401), (401, 403), (401, None), (403, None), (404, None)],
+    )
+    @time_machine.travel("2026-01-01 00:00:00+00:00", tick=False)
+    @mock.patch("kubernetes_asyncio.client.rest.RESTClientObject.request", 
autospec=True)
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook._get_config"), 
autospec=True)
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook.get_token"), 
autospec=True)
+    async def test_cached_client_retries_rejected_credentials_only_once(
+        self,
+        mock_get_token,
+        mock_get_config,
+        mock_request,
+        authenticated_async_hook,
+        initial_status,
+        retry_status,
+    ):
+        hook = authenticated_async_hook
+        credentials = mock.Mock(spec=Credentials, token="token", 
expiry=datetime(2026, 1, 1, 1))
+        mock_get_token.side_effect = lambda *args, **kwargs: 
_CredentialsToken(credentials)
+        mock_get_config.return_value = 
async_client.Configuration(host=CLUSTER_URL)
+        initial_error = 
async_client.ApiException(http_resp=self._mock_api_response(status=initial_status))
+        responses = [self._mock_api_response(), initial_error]
+        final_error = initial_error
+        if retry_status is not None:
+            final_error = 
async_client.ApiException(http_resp=self._mock_api_response(status=retry_status))
+            responses.append(final_error)
+        mock_request.side_effect = responses
+
+        await hook.get_pod(name=POD_NAME, namespace=POD_NAMESPACE)
+        if retry_status is not None:
+            credentials.token = "refreshed-token"
+        permission_denied = (retry_status or initial_status) == 403
+        expected_exception = KubernetesApiPermissionError if permission_denied 
else async_client.ApiException
+        with pytest.raises(expected_exception) as error:
+            await hook.get_pod(name=POD_NAME, namespace=POD_NAMESPACE)
+
+        if permission_denied:
+            assert error.value.__cause__ is final_error
+        else:
+            assert error.value is final_error
+        assert mock_request.call_count == len(responses)
+        assert credentials.refresh.call_count == (2 if initial_status == 401 
else 1)
+
+    @pytest.mark.asyncio
+    @time_machine.travel("2026-01-01 00:00:00+00:00", tick=False)
+    @mock.patch("kubernetes_asyncio.client.rest.RESTClientObject.request", 
autospec=True)
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook._get_config"), 
autospec=True)
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook.get_token"), 
autospec=True)
+    async def test_cached_client_propagates_credential_refresh_failure(
+        self, mock_get_token, mock_get_config, mock_request, 
authenticated_async_hook
+    ):
+        hook = authenticated_async_hook
+        credentials = mock.Mock(spec=Credentials, token="token", 
expiry=datetime(2026, 1, 1, 1))
+        credentials.refresh.side_effect = [None, RefreshError("credential 
refresh failed")]
+        mock_get_token.side_effect = lambda *args, **kwargs: 
_CredentialsToken(credentials)
+        mock_get_config.return_value = 
async_client.Configuration(host=CLUSTER_URL)
+        mock_request.side_effect = [
+            self._mock_api_response(),
+            
async_client.ApiException(http_resp=self._mock_api_response(status=401)),
+        ]
+
+        await hook.get_pod(name=POD_NAME, namespace=POD_NAMESPACE)
+        with pytest.raises(RefreshError, match="credential refresh failed"):
+            await hook.get_pod(name=POD_NAME, namespace=POD_NAMESPACE)
+
+        assert mock_request.call_count == 2
+        assert credentials.refresh.call_count == 2
+
+    @pytest.mark.asyncio
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook.get_token"), 
new_callable=mock.AsyncMock)
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook._build_client"))
+    async def test_close_releases_client_and_token(self, mock_build_client, 
mock_get_token, async_hook):
+        mock_get_token.return_value = self._mock_token(["token-1"])
+        kube_client = mock.MagicMock(default_headers={}, 
close=mock.AsyncMock())

Review Comment:
   Could you specify `spec` here?



##########
providers/google/tests/unit/google/cloud/hooks/test_kubernetes_engine.py:
##########
@@ -582,6 +590,212 @@ async def test_read_logs(self, read_namespaced_pod_log, 
get_conn_mock, async_hoo
         assert "Test string #1" in logs
         assert "Test string #2" in logs
 
+    @staticmethod
+    def _mock_token(tokens):
+        token = mock.create_autospec(_CredentialsToken, instance=True)
+        token.get.side_effect = list(tokens)
+        return token
+
+    @pytest.mark.asyncio
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook.get_token"), 
autospec=True)
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook._build_client"), 
autospec=True)
+    async def test_get_conn_caches_client_and_token(self, mock_build_client, 
mock_get_token, async_hook):
+        mock_get_token.return_value = self._mock_token(["token-1", "token-1"])
+        mock_build_client.return_value = 
mock.MagicMock(spec=async_client.ApiClient, default_headers={})
+
+        async with async_hook.get_conn() as conn_first:
+            pass
+        async with async_hook.get_conn() as conn_second:
+            pass
+
+        assert conn_first is conn_second
+        mock_build_client.assert_called_once_with(async_hook)
+        mock_get_token.assert_awaited_once()
+
+    @pytest.mark.asyncio
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook.get_token"), 
autospec=True)
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook._build_client"), 
autospec=True)
+    async def test_get_conn_refreshes_authorization_header_per_entry(
+        self, mock_build_client, mock_get_token, async_hook
+    ):
+        mock_get_token.return_value = self._mock_token(["token-1", "token-2"])
+        kube_client = mock.MagicMock(spec=async_client.ApiClient, 
default_headers={})
+        mock_build_client.return_value = kube_client
+
+        async with async_hook.get_conn():
+            assert kube_client.default_headers["Authorization"] == "Bearer 
token-1"
+        async with async_hook.get_conn():
+            assert kube_client.default_headers["Authorization"] == "Bearer 
token-2"
+
+    @pytest.mark.asyncio
+    @pytest.mark.parametrize("elapsed", [301, 601])
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook.get_token"), 
autospec=True)
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook._build_client"), 
autospec=True)
+    async def test_cached_client_refreshes_short_lived_credentials(
+        self, mock_build_client, mock_get_token, async_hook, elapsed
+    ):
+        credentials = mock.MagicMock(spec=Credentials)
+        credentials.token = "token-1"
+        credentials.expiry = datetime(2026, 1, 1, 0, 10)
+        mock_get_token.return_value = _CredentialsToken(credentials)
+        kube_client = mock_build_client.return_value
+        kube_client.default_headers = {}
+
+        with time_machine.travel("2026-01-01 00:00:00+00:00", tick=False) as 
clock:
+            async with async_hook.get_conn() as first_client:
+                assert first_client.default_headers["Authorization"] == 
"Bearer token-1"
+
+            clock.shift(timedelta(seconds=elapsed))
+            credentials.token = "token-2"
+            credentials.expiry = datetime(2026, 1, 1, 0, 20)
+            async with async_hook.get_conn() as second_client:
+                assert second_client is first_client
+                assert second_client.default_headers["Authorization"] == 
"Bearer token-2"
+
+        mock_build_client.assert_called_once()
+        mock_get_token.assert_awaited_once()
+        assert credentials.refresh.call_count == 2
+
+    @pytest_asyncio.fixture
+    async def authenticated_async_hook(self, async_hook):
+        try:
+            yield async_hook
+        finally:
+            await async_hook.close()
+
+    @staticmethod
+    def _mock_api_response(status=200):
+        response = mock.Mock(
+            spec=RESTResponse,
+            status=status,
+            reason="test response",
+            data=b'{"metadata": {"name": "test-pod-name"}, "items": []}',
+        )
+        response.getheader.return_value = "application/json"
+        response.getheaders.return_value = {}
+        return response
+
+    @pytest.mark.asyncio
+    @pytest.mark.parametrize("operation", ["get_pod", "list_pods"])
+    @time_machine.travel("2026-01-01 00:00:00+00:00", tick=False)
+    @mock.patch("kubernetes_asyncio.client.rest.RESTClientObject.request", 
autospec=True)
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook._get_config"), 
autospec=True)
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook.get_token"), 
autospec=True)
+    async def test_cached_client_refreshes_rejected_credentials(
+        self, mock_get_token, mock_get_config, mock_request, 
authenticated_async_hook, operation
+    ):
+        hook = authenticated_async_hook
+        credentials = mock.Mock(spec=Credentials, token="token-1", 
expiry=datetime(2026, 1, 1, 1))
+        mock_get_token.side_effect = lambda *args, **kwargs: 
_CredentialsToken(credentials)
+        mock_get_config.return_value = 
async_client.Configuration(host=CLUSTER_URL)
+        mock_request.side_effect = [
+            self._mock_api_response(),
+            
async_client.ApiException(http_resp=self._mock_api_response(status=401)),
+            self._mock_api_response(),
+        ]
+        kwargs = {"namespace": POD_NAMESPACE}
+        kwargs.update({"name": POD_NAME} if operation == "get_pod" else 
{"label_selector": "job-name=test"})
+
+        await getattr(hook, operation)(**kwargs)
+        cached_client = hook._cached_kube_client
+        credentials.token = "token-2"
+        await getattr(hook, operation)(**kwargs)
+
+        assert hook._cached_kube_client is cached_client
+        assert cached_client.default_headers["Authorization"] == "Bearer 
token-2"
+        assert [call.kwargs["headers"]["Authorization"] for call in 
mock_request.call_args_list] == [
+            "Bearer token-1",
+            "Bearer token-1",
+            "Bearer token-2",
+        ]
+        assert credentials.refresh.call_count == 2
+
+    @pytest.mark.asyncio
+    @pytest.mark.parametrize(
+        ("initial_status", "retry_status"),
+        [(401, 401), (401, 403), (401, None), (403, None), (404, None)],
+    )
+    @time_machine.travel("2026-01-01 00:00:00+00:00", tick=False)
+    @mock.patch("kubernetes_asyncio.client.rest.RESTClientObject.request", 
autospec=True)
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook._get_config"), 
autospec=True)
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook.get_token"), 
autospec=True)
+    async def test_cached_client_retries_rejected_credentials_only_once(
+        self,
+        mock_get_token,
+        mock_get_config,
+        mock_request,
+        authenticated_async_hook,
+        initial_status,
+        retry_status,
+    ):
+        hook = authenticated_async_hook
+        credentials = mock.Mock(spec=Credentials, token="token", 
expiry=datetime(2026, 1, 1, 1))
+        mock_get_token.side_effect = lambda *args, **kwargs: 
_CredentialsToken(credentials)
+        mock_get_config.return_value = 
async_client.Configuration(host=CLUSTER_URL)
+        initial_error = 
async_client.ApiException(http_resp=self._mock_api_response(status=initial_status))
+        responses = [self._mock_api_response(), initial_error]
+        final_error = initial_error
+        if retry_status is not None:
+            final_error = 
async_client.ApiException(http_resp=self._mock_api_response(status=retry_status))
+            responses.append(final_error)
+        mock_request.side_effect = responses
+
+        await hook.get_pod(name=POD_NAME, namespace=POD_NAMESPACE)
+        if retry_status is not None:
+            credentials.token = "refreshed-token"
+        permission_denied = (retry_status or initial_status) == 403
+        expected_exception = KubernetesApiPermissionError if permission_denied 
else async_client.ApiException
+        with pytest.raises(expected_exception) as error:
+            await hook.get_pod(name=POD_NAME, namespace=POD_NAMESPACE)
+
+        if permission_denied:
+            assert error.value.__cause__ is final_error
+        else:
+            assert error.value is final_error
+        assert mock_request.call_count == len(responses)
+        assert credentials.refresh.call_count == (2 if initial_status == 401 
else 1)
+
+    @pytest.mark.asyncio
+    @time_machine.travel("2026-01-01 00:00:00+00:00", tick=False)
+    @mock.patch("kubernetes_asyncio.client.rest.RESTClientObject.request", 
autospec=True)
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook._get_config"), 
autospec=True)
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook.get_token"), 
autospec=True)
+    async def test_cached_client_propagates_credential_refresh_failure(
+        self, mock_get_token, mock_get_config, mock_request, 
authenticated_async_hook
+    ):
+        hook = authenticated_async_hook
+        credentials = mock.Mock(spec=Credentials, token="token", 
expiry=datetime(2026, 1, 1, 1))
+        credentials.refresh.side_effect = [None, RefreshError("credential 
refresh failed")]
+        mock_get_token.side_effect = lambda *args, **kwargs: 
_CredentialsToken(credentials)
+        mock_get_config.return_value = 
async_client.Configuration(host=CLUSTER_URL)
+        mock_request.side_effect = [
+            self._mock_api_response(),
+            
async_client.ApiException(http_resp=self._mock_api_response(status=401)),
+        ]
+
+        await hook.get_pod(name=POD_NAME, namespace=POD_NAMESPACE)
+        with pytest.raises(RefreshError, match="credential refresh failed"):
+            await hook.get_pod(name=POD_NAME, namespace=POD_NAMESPACE)
+
+        assert mock_request.call_count == 2
+        assert credentials.refresh.call_count == 2
+
+    @pytest.mark.asyncio
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook.get_token"), 
new_callable=mock.AsyncMock)
+    @mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook._build_client"))

Review Comment:
   Could you specify `autospec` here?



##########
providers/google/pyproject.toml:
##########
@@ -172,7 +172,7 @@ dependencies = [
     "apache-airflow-providers-apache-beam>=6.2.2",
 ]
 "cncf.kubernetes" = [
-    "apache-airflow-providers-cncf-kubernetes>=10.25.0",
+    "apache-airflow-providers-cncf-kubernetes>=10.25.0",  # use next version

Review Comment:
   ```suggestion
       "apache-airflow-providers-cncf-kubernetes>=11.1.0",
   ```
   The review comment was okay-ish when we had one PR for this change as a 
notification for the release manager, but now that we split the change and the 
Kubernetes one was already published, we can just change the version here 
directly.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to