Skip to content

Commit df5af9a

Browse files
committed
test(auth): verify ID token caching
Add explicit unit test coverage in IdTokenCredentialsTest to verify that IdTokenCredentials successfully caches fetched ID tokens and prevents subsequent network calls when the token is not expired. Other language client libraries (such as Python and Go) verify that ID token caching behaves as expected, but the Java client library was missing explicit test coverage to assert that the token provider's retrieve method is called exactly once across multiple credential calls.
1 parent 051aea7 commit df5af9a

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,14 @@
3232
package com.google.auth.oauth2;
3333

3434
import static org.junit.jupiter.api.Assertions.assertEquals;
35+
import static org.mockito.ArgumentMatchers.any;
36+
import static org.mockito.ArgumentMatchers.anyString;
37+
import static org.mockito.Mockito.mock;
38+
import static org.mockito.Mockito.times;
39+
import static org.mockito.Mockito.verify;
40+
import static org.mockito.Mockito.when;
3541

42+
import com.google.api.client.util.Clock;
3643
import java.io.IOException;
3744
import org.junit.jupiter.api.Test;
3845

@@ -110,4 +117,29 @@ void serialize() throws IOException, ClassNotFoundException {
110117
IdTokenCredentials deserializedCredentials = serializeAndDeserialize(tokenCredential);
111118
assertEquals(tokenCredential, deserializedCredentials);
112119
}
120+
121+
@Test
122+
void caching() throws IOException {
123+
IdTokenProvider mockProvider = mock(IdTokenProvider.class);
124+
IdToken idToken = IdToken.create(ComputeEngineCredentialsTest.STANDARD_ID_TOKEN);
125+
when(mockProvider.idTokenWithAudience(anyString(), any())).thenReturn(idToken);
126+
127+
IdTokenCredentials credentials =
128+
IdTokenCredentials.newBuilder()
129+
.setIdTokenProvider(mockProvider)
130+
.setTargetAudience("https://foo.bar")
131+
.build();
132+
credentials.clock =
133+
new Clock() {
134+
@Override
135+
public long currentTimeMillis() {
136+
return 1564471451000L; // 2019-07-30T08:24:11Z (STANDARD_ID_TOKEN iat)
137+
}
138+
};
139+
140+
credentials.refreshIfExpired();
141+
credentials.refreshIfExpired();
142+
143+
verify(mockProvider, times(1)).idTokenWithAudience(anyString(), any());
144+
}
113145
}

0 commit comments

Comments
 (0)