@@ -105,26 +105,56 @@ async def test_get_valid_credentials_with_valid_existing_creds(
105105 ],
106106 )
107107 @pytest .mark .asyncio
108+ @patch .object (_google_credentials , "Request" , autospec = True )
108109 async def test_get_valid_credentials_with_existing_non_oauth_creds (
109- self , manager , mock_tool_context , valid
110+ self , mock_request_class , manager , mock_tool_context , valid
110111 ):
111- """Test that existing non-oauth credentials are returned immediately .
112+ """Test that existing non-oauth credentials handle refresh logic correctly .
112113
113- When credentials are of non-oauth type, no refresh or OAuth flow
114- is triggered irrespective of whether or not it is valid .
114+ When credentials are of non-oauth type, a refresh is triggered if they
115+ are invalid. No OAuth flow is ever triggered .
115116 """
116- # Create mock credentials that are already valid
117+ # Create mock credentials with the specified validity
117118 mock_creds = create_autospec (AuthCredentials , instance = True )
118119 mock_creds .valid = valid
119120 manager .credentials_config .credentials = mock_creds
120121
121122 result = await manager .get_valid_credentials (mock_tool_context )
122123
123124 assert result == mock_creds
125+ # Verify refresh behavior
126+ if valid :
127+ mock_creds .refresh .assert_not_called ()
128+ else :
129+ mock_creds .refresh .assert_called_once_with (
130+ mock_request_class .return_value
131+ )
132+
124133 # Verify no OAuth flow was triggered
125134 mock_tool_context .get_auth_response .assert_not_called ()
126135 mock_tool_context .request_credential .assert_not_called ()
127136
137+ @pytest .mark .asyncio
138+ @patch .object (_google_credentials , "Request" , autospec = True )
139+ async def test_get_valid_credentials_with_non_oauth_refresh_failure (
140+ self , mock_request_class , manager , mock_tool_context
141+ ):
142+ """Test that non-oauth refresh failures are caught gracefully.
143+
144+ Even if refresh fails, we should still return the credentials as they
145+ might work for some downstream libraries.
146+ """
147+ mock_creds = create_autospec (AuthCredentials , instance = True )
148+ mock_creds .valid = False
149+ mock_creds .refresh .side_effect = Exception ("Refresh failed" )
150+ manager .credentials_config .credentials = mock_creds
151+
152+ result = await manager .get_valid_credentials (mock_tool_context )
153+
154+ # Credentials should still be returned
155+ assert result == mock_creds
156+ mock_creds .refresh .assert_called_once_with (mock_request_class .return_value )
157+
128158 @pytest .mark .asyncio
129159 async def test_get_credentials_from_cache_when_none_in_manager (
130160 self , manager , mock_tool_context
0 commit comments