@@ -446,6 +446,57 @@ def test_cache_starts_empty(self):
446446 """Cache should be empty at the start due to the clear_credential_cache fixture."""
447447 assert len (_credential_cache ) == 0
448448
449+ def test_cached_credential_refreshes_token_after_expiry (self ):
450+ """Verify that the cached credential instance returns fresh tokens on each call.
451+
452+ This simulates what happens when Azure Identity SDK refreshes an expired
453+ token internally: because we cache the credential (not the token), each
454+ _acquire_token() call invokes get_token() on the same instance, giving
455+ the SDK the opportunity to return a refreshed token when the old one has
456+ expired.
457+ """
458+ import sys
459+
460+ azure_identity = sys .modules ["azure.identity" ]
461+ original = azure_identity .DefaultAzureCredential
462+
463+ call_count = 0
464+ tokens = ["initial_token_abc123" , "refreshed_token_xyz789" ]
465+
466+ class MockCredentialWithRefresh :
467+ def get_token (self , scope ):
468+ nonlocal call_count
469+ idx = min (call_count , len (tokens ) - 1 )
470+ call_count += 1
471+
472+ class Token :
473+ token = tokens [idx ]
474+
475+ return Token ()
476+
477+ try :
478+ azure_identity .DefaultAzureCredential = MockCredentialWithRefresh
479+
480+ # First call — gets initial token
481+ _ , raw_token_1 = AADAuth ._acquire_token ("default" )
482+ assert raw_token_1 == "initial_token_abc123"
483+ assert call_count == 1
484+
485+ # Same credential instance is cached
486+ cached = _credential_cache ["default" ]
487+ assert isinstance (cached , MockCredentialWithRefresh )
488+
489+ # Second call — same credential instance, but SDK returns refreshed token
490+ # (simulating post-expiry refresh)
491+ _ , raw_token_2 = AADAuth ._acquire_token ("default" )
492+ assert raw_token_2 == "refreshed_token_xyz789"
493+ assert call_count == 2
494+
495+ # Credential instance is still the same (not recreated)
496+ assert _credential_cache ["default" ] is cached
497+ finally :
498+ azure_identity .DefaultAzureCredential = original
499+
449500
450501class TestAcquireTokenImportError :
451502 """Test the ImportError path when azure-identity is not installed."""
0 commit comments