Skip to content

Commit 9c3fc55

Browse files
authored
Remove powermock (Azure#28350)
* Update DefaultAzureCredentialTest * Update AuthorizationCodeCredentialTest * Add assertNotNull * Update AzurePowerShellCredentialTest * Update ClientCertificateCredentialTest * Update DeviceCodeCredentialTest * Update AzureApplicationCredentialTest * Update AzureCliCredentialTest * Update CertificateutilTests * Add java.sql to module-info.java * Update ClientSecretCredentialTest Modified `testInvalidSecrets` to not also test valid secrets. * Update IntelliJKDBXDatabaseParsingTest * Updated IdentityUtilTests * Remove dead store * Update UsernamePasswordCredentialTest * checkstyle cleanups * Update HttpPipelineAdapterTests * Update ManagedIdentityCredentialTest * fix warnings * Update InteractiveBrowserCredentialTest * update pom * First test update to IdentityClientTests * First test update to IdentityClientTests * Remove runWith, add missing @test attribute * Finish IdentityClientTests * remove commented old dependency * Add x-version-update * Add package-private static method for getting URLs to IdentityClient to enable testing on java 8. * Match mockito-inlinie version to external_dependencies.txt * remove test dependency on java.sql * Undo mistakenly changed string
1 parent f0eb81f commit 9c3fc55

18 files changed

+1148
-1228
lines changed

sdk/identity/azure-identity/pom.xml

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -54,18 +54,6 @@
5454
<version>4.13.2</version> <!-- {x-version-update;junit:junit;external_dependency} -->
5555
<scope>test</scope>
5656
</dependency>
57-
<dependency>
58-
<groupId>org.powermock</groupId>
59-
<artifactId>powermock-module-junit4</artifactId>
60-
<version>2.0.9</version> <!-- {x-version-update;org.powermock:powermock-module-junit4;external_dependency} -->
61-
<scope>test</scope>
62-
</dependency>
63-
<dependency>
64-
<groupId>org.powermock</groupId>
65-
<artifactId>powermock-api-mockito2</artifactId>
66-
<version>2.0.9</version> <!-- {x-version-update;org.powermock:powermock-api-mockito2;external_dependency} -->
67-
<scope>test</scope>
68-
</dependency>
6957
<dependency>
7058
<groupId>net.java.dev.jna</groupId>
7159
<artifactId>jna-platform</artifactId>
@@ -98,6 +86,12 @@
9886
<version>2.2</version> <!-- {x-version-update;org.hamcrest:hamcrest;external_dependency} -->
9987
<scope>test</scope>
10088
</dependency>
89+
<dependency>
90+
<groupId>org.mockito</groupId>
91+
<artifactId>mockito-inline</artifactId>
92+
<version>4.0.0</version> <!-- {x-version-update;org.mockito:mockito-inline;external_dependency} -->
93+
<scope>test</scope>
94+
</dependency>
10195
</dependencies>
10296

10397
<build>

sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentityClient.java

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1042,7 +1042,7 @@ public Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identit
10421042
payload.append("&api-version=");
10431043
payload.append(URLEncoder.encode("2019-11-01", StandardCharsets.UTF_8.name()));
10441044

1045-
URL url = new URL(String.format("%s?%s", identityEndpoint, payload));
1045+
URL url = getUrl(String.format("%s?%s", identityEndpoint, payload));
10461046

10471047

10481048
String secretKey = null;
@@ -1152,7 +1152,7 @@ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext reque
11521152

11531153
HttpURLConnection connection = null;
11541154

1155-
URL url = new URL(authorityUrl);
1155+
URL url = getUrl(authorityUrl);
11561156

11571157
try {
11581158
connection = (HttpURLConnection) url.openConnection();
@@ -1216,7 +1216,7 @@ public Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(Stri
12161216

12171217
try {
12181218

1219-
URL url = new URL(String.format("%s?%s", endpoint, payload));
1219+
URL url = getUrl(String.format("%s?%s", endpoint, payload));
12201220
connection = (HttpsURLConnection) url.openConnection();
12211221

12221222
IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER);
@@ -1304,7 +1304,7 @@ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEn
13041304
payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name()));
13051305
}
13061306
try {
1307-
URL url = new URL(String.format("%s?%s", endpoint, payload));
1307+
URL url = getUrl(String.format("%s?%s", endpoint, payload));
13081308
connection = (HttpURLConnection) url.openConnection();
13091309

13101310
connection.setRequestMethod("GET");
@@ -1332,6 +1332,9 @@ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEn
13321332
});
13331333
}
13341334

1335+
static URL getUrl(String uri) throws MalformedURLException {
1336+
return new URL(uri);
1337+
}
13351338
/**
13361339
* Asynchronously acquire a token from the Virtual Machine IMDS endpoint.
13371340
*
@@ -1369,7 +1372,7 @@ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request)
13691372
URL url = null;
13701373
HttpURLConnection connection = null;
13711374
try {
1372-
url = new URL(String.format("%s?%s", endpoint, payload));
1375+
url = getUrl(String.format("%s?%s", endpoint, payload));
13731376

13741377
connection = (HttpURLConnection) url.openConnection();
13751378
connection.setRequestMethod("GET");
@@ -1447,7 +1450,7 @@ private Mono<Boolean> checkIMDSAvailable(String endpoint) {
14471450
}
14481451
return Mono.fromCallable(() -> {
14491452
HttpURLConnection connection = null;
1450-
URL url = new URL(String.format("%s?%s", endpoint, payload));
1453+
URL url = getUrl(String.format("%s?%s", endpoint, payload));
14511454

14521455
try {
14531456
connection = (HttpURLConnection) url.openConnection();

sdk/identity/azure-identity/src/test/java/com/azure/identity/AuthorizationCodeCredentialTest.java

Lines changed: 30 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,10 @@
66
import com.azure.core.credential.TokenRequestContext;
77
import com.azure.identity.implementation.IdentityClient;
88
import com.azure.identity.util.TestUtils;
9+
import org.junit.Assert;
910
import org.junit.Test;
10-
import org.junit.runner.RunWith;
11+
import org.mockito.MockedConstruction;
1112
import org.mockito.exceptions.misusing.InvalidUseOfMatchersException;
12-
import org.powermock.api.mockito.PowerMockito;
13-
import org.powermock.core.classloader.annotations.PowerMockIgnore;
14-
import org.powermock.core.classloader.annotations.PrepareForTest;
15-
import org.powermock.modules.junit4.PowerMockRunner;
1613
import reactor.core.publisher.Mono;
1714
import reactor.test.StepVerifier;
1815

@@ -23,11 +20,9 @@
2320

2421
import static org.mockito.ArgumentMatchers.any;
2522
import static org.mockito.ArgumentMatchers.eq;
23+
import static org.mockito.Mockito.mockConstruction;
2624
import static org.mockito.Mockito.when;
2725

28-
@RunWith(PowerMockRunner.class)
29-
@PrepareForTest(fullyQualifiedNames = "com.azure.identity.*")
30-
@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*"})
3126
public class AuthorizationCodeCredentialTest {
3227

3328
private final String clientId = UUID.randomUUID().toString();
@@ -44,32 +39,34 @@ public void testValidAuthorizationCode() throws Exception {
4439
OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
4540

4641
// mock
47-
IdentityClient identityClient = PowerMockito.mock(IdentityClient.class);
48-
when(identityClient.authenticateWithAuthorizationCode(eq(request1), eq(authCode1), eq(redirectUri)))
49-
.thenReturn(TestUtils.getMockMsalToken(token1, expiresAt));
50-
when(identityClient.authenticateWithPublicClientCache(any(), any()))
51-
.thenAnswer(invocation -> {
52-
TokenRequestContext argument = (TokenRequestContext) invocation.getArguments()[0];
53-
if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request2.getScopes().get(0))) {
54-
return TestUtils.getMockMsalToken(token2, expiresAt);
55-
} else if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request1.getScopes().get(0))) {
56-
return Mono.error(new UnsupportedOperationException("nothing cached"));
57-
} else {
58-
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
59-
}
60-
});
61-
PowerMockito.whenNew(IdentityClient.class).withAnyArguments().thenReturn(identityClient);
42+
try (MockedConstruction<IdentityClient> identityclientMock = mockConstruction(IdentityClient.class, (identityClient, context) -> {
43+
when(identityClient.authenticateWithAuthorizationCode(eq(request1), eq(authCode1), eq(redirectUri)))
44+
.thenReturn(TestUtils.getMockMsalToken(token1, expiresAt));
45+
when(identityClient.authenticateWithPublicClientCache(any(), any()))
46+
.thenAnswer(invocation -> {
47+
TokenRequestContext argument = (TokenRequestContext) invocation.getArguments()[0];
48+
if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request2.getScopes().get(0))) {
49+
return TestUtils.getMockMsalToken(token2, expiresAt);
50+
} else if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request1.getScopes().get(0))) {
51+
return Mono.error(new UnsupportedOperationException("nothing cached"));
52+
} else {
53+
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
54+
}
55+
});
56+
})) {
6257

63-
// test
64-
AuthorizationCodeCredential credential = new AuthorizationCodeCredentialBuilder()
58+
// test
59+
AuthorizationCodeCredential credential = new AuthorizationCodeCredentialBuilder()
6560
.clientId(clientId).authorizationCode(authCode1).redirectUrl(redirectUri.toString()).build();
66-
StepVerifier.create(credential.getToken(request1))
67-
.expectNextMatches(accessToken -> token1.equals(accessToken.getToken())
68-
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
69-
.verifyComplete();
70-
StepVerifier.create(credential.getToken(request2))
71-
.expectNextMatches(accessToken -> token2.equals(accessToken.getToken())
72-
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
73-
.verifyComplete();
61+
StepVerifier.create(credential.getToken(request1))
62+
.expectNextMatches(accessToken -> token1.equals(accessToken.getToken())
63+
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
64+
.verifyComplete();
65+
StepVerifier.create(credential.getToken(request2))
66+
.expectNextMatches(accessToken -> token2.equals(accessToken.getToken())
67+
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
68+
.verifyComplete();
69+
Assert.assertNotNull(identityclientMock);
70+
}
7471
}
7572
}

sdk/identity/azure-identity/src/test/java/com/azure/identity/AzureApplicationCredentialTest.java

Lines changed: 62 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,9 @@
77
import com.azure.core.util.Configuration;
88
import com.azure.identity.implementation.IdentityClient;
99
import com.azure.identity.util.TestUtils;
10+
import org.junit.Assert;
1011
import org.junit.Test;
11-
import org.junit.runner.RunWith;
12-
import org.powermock.api.mockito.PowerMockito;
13-
import org.powermock.core.classloader.annotations.PowerMockIgnore;
14-
import org.powermock.core.classloader.annotations.PrepareForTest;
15-
import org.powermock.modules.junit4.PowerMockRunner;
12+
import org.mockito.MockedConstruction;
1613
import reactor.core.publisher.Mono;
1714
import reactor.test.StepVerifier;
1815

@@ -21,48 +18,39 @@
2118
import java.util.UUID;
2219

2320
import static org.mockito.ArgumentMatchers.*;
21+
import static org.mockito.Mockito.mockConstruction;
2422
import static org.mockito.Mockito.when;
2523

26-
@RunWith(PowerMockRunner.class)
27-
@PrepareForTest(fullyQualifiedNames = "com.azure.identity.*")
28-
@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.net.ssl.*",
29-
"io.netty.handler.ssl.*", "io.netty.buffer.*", "io.netty.channel.*"})
3024
public class AzureApplicationCredentialTest {
3125

3226
private static final String TENANT_ID = "contoso.com";
3327
private static final String CLIENT_ID = UUID.randomUUID().toString();
3428

3529
@Test
3630
public void testUseEnvironmentCredential() throws Exception {
37-
Configuration configuration = Configuration.getGlobalConfiguration();
38-
39-
try {
40-
// setup
41-
String secret = "secret";
42-
String token1 = "token1";
43-
TokenRequestContext request1 = new TokenRequestContext().addScopes("https://management.azure.com");
44-
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
45-
configuration.put("AZURE_CLIENT_ID", CLIENT_ID);
46-
configuration.put("AZURE_CLIENT_SECRET", secret);
47-
configuration.put("AZURE_TENANT_ID", TENANT_ID);
48-
49-
// mock
50-
IdentityClient identityClient = PowerMockito.mock(IdentityClient.class);
31+
Configuration configuration = Configuration.getGlobalConfiguration().clone();
32+
33+
// setup
34+
String secret = "secret";
35+
String token1 = "token1";
36+
TokenRequestContext request1 = new TokenRequestContext().addScopes("https://management.azure.com");
37+
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
38+
configuration.put("AZURE_CLIENT_ID", CLIENT_ID);
39+
configuration.put("AZURE_CLIENT_SECRET", secret);
40+
configuration.put("AZURE_TENANT_ID", TENANT_ID);
41+
42+
// mock
43+
try (MockedConstruction<IdentityClient> identityClientMock = mockConstruction(IdentityClient.class, (identityClient, context) -> {
5144
when(identityClient.authenticateWithConfidentialClientCache(any())).thenReturn(Mono.empty());
5245
when(identityClient.authenticateWithConfidentialClient(request1)).thenReturn(TestUtils.getMockAccessToken(token1, expiresOn));
53-
PowerMockito.whenNew(IdentityClient.class).withArguments(eq(TENANT_ID), eq(CLIENT_ID), eq(secret), isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), eq(false), isNull(), any()).thenReturn(identityClient);
54-
46+
})) {
5547
// test
56-
AzureApplicationCredential credential = new AzureApplicationCredentialBuilder().build();
48+
AzureApplicationCredential credential = new AzureApplicationCredentialBuilder().configuration(configuration).build();
5749
StepVerifier.create(credential.getToken(request1))
5850
.expectNextMatches(accessToken -> token1.equals(accessToken.getToken())
5951
&& expiresOn.getSecond() == accessToken.getExpiresAt().getSecond())
6052
.verifyComplete();
61-
} finally {
62-
// clean up
63-
configuration.remove("AZURE_CLIENT_ID");
64-
configuration.remove("AZURE_CLIENT_SECRET");
65-
configuration.remove("AZURE_TENANT_ID");
53+
Assert.assertNotNull(identityClientMock);
6654
}
6755
}
6856

@@ -74,22 +62,21 @@ public void testUseManagedIdentityCredential() throws Exception {
7462
OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
7563

7664
// mock
77-
IdentityClient identityClient = PowerMockito.mock(IdentityClient.class);
78-
when(identityClient.authenticateToIMDSEndpoint(request)).thenReturn(TestUtils.getMockAccessToken(token1, expiresAt));
79-
PowerMockito.whenNew(IdentityClient.class).withAnyArguments().thenReturn(identityClient);
80-
81-
IntelliJCredential intelliJCredential = PowerMockito.mock(IntelliJCredential.class);
82-
when(intelliJCredential.getToken(request))
83-
.thenReturn(Mono.empty());
84-
PowerMockito.whenNew(IntelliJCredential.class).withAnyArguments()
85-
.thenReturn(intelliJCredential);
86-
87-
// test
88-
AzureApplicationCredential credential = new AzureApplicationCredentialBuilder().build();
89-
StepVerifier.create(credential.getToken(request))
90-
.expectNextMatches(accessToken -> token1.equals(accessToken.getToken())
91-
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
92-
.verifyComplete();
65+
try (MockedConstruction<IdentityClient> identityClientMock = mockConstruction(IdentityClient.class, (identityClient, context) -> {
66+
when(identityClient.authenticateToIMDSEndpoint(request)).thenReturn(TestUtils.getMockAccessToken(token1, expiresAt));
67+
68+
}); MockedConstruction<IntelliJCredential> intelliCredentialMock = mockConstruction(IntelliJCredential.class, (intelliJCredential, context) -> {
69+
when(intelliJCredential.getToken(request)).thenReturn(Mono.empty());
70+
})) {
71+
// test
72+
AzureApplicationCredential credential = new AzureApplicationCredentialBuilder().build();
73+
StepVerifier.create(credential.getToken(request))
74+
.expectNextMatches(accessToken -> token1.equals(accessToken.getToken())
75+
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
76+
.verifyComplete();
77+
Assert.assertNotNull(identityClientMock);
78+
Assert.assertNotNull(intelliCredentialMock);
79+
}
9380
}
9481

9582
@Test
@@ -98,37 +85,39 @@ public void testNoCredentialWorks() throws Exception {
9885
TokenRequestContext request = new TokenRequestContext().addScopes("https://management.azure.com");
9986

10087
// mock
101-
IdentityClient identityClient = PowerMockito.mock(IdentityClient.class);
102-
when(identityClient.authenticateToIMDSEndpoint(request))
103-
.thenReturn(Mono.error(new CredentialUnavailableException("Cannot get token from managed identity")));
104-
PowerMockito.whenNew(IdentityClient.class).withAnyArguments()
105-
.thenReturn(identityClient);
106-
107-
// test
108-
AzureApplicationCredential credential = new AzureApplicationCredentialBuilder().build();
109-
StepVerifier.create(credential.getToken(request))
110-
.expectErrorMatches(t -> t instanceof CredentialUnavailableException && t.getMessage()
111-
.startsWith("EnvironmentCredential authentication unavailable. "))
112-
.verify();
88+
try (MockedConstruction<IdentityClient> identityClientMock = mockConstruction(IdentityClient.class, (identityClient, context) -> {
89+
when(identityClient.authenticateToIMDSEndpoint(request))
90+
.thenReturn(Mono.error(new CredentialUnavailableException("Cannot get token from managed identity")));
91+
})) {
92+
// test
93+
AzureApplicationCredential credential = new AzureApplicationCredentialBuilder().build();
94+
StepVerifier.create(credential.getToken(request))
95+
.expectErrorMatches(t -> t instanceof CredentialUnavailableException && t.getMessage()
96+
.startsWith("EnvironmentCredential authentication unavailable. "))
97+
.verify();
98+
Assert.assertNotNull(identityClientMock);
99+
}
113100
}
114101

115102
@Test
116103
public void testCredentialUnavailable() throws Exception {
104+
// setup
117105
TokenRequestContext request = new TokenRequestContext().addScopes("https://management.azure.com");
118106

119-
ManagedIdentityCredential managedIdentityCredential = PowerMockito.mock(ManagedIdentityCredential.class);
120-
when(managedIdentityCredential.getToken(request))
121-
.thenReturn(Mono.error(
122-
new CredentialUnavailableException("Cannot get token from Managed Identity credential")));
123-
PowerMockito.whenNew(ManagedIdentityCredential.class).withAnyArguments()
124-
.thenReturn(managedIdentityCredential);
125-
126-
// test
127-
AzureApplicationCredential credential = new AzureApplicationCredentialBuilder()
128-
.build();
129-
StepVerifier.create(credential.getToken(request))
130-
.expectErrorMatches(t -> t instanceof CredentialUnavailableException && t.getMessage()
131-
.startsWith("EnvironmentCredential authentication unavailable. "))
132-
.verify();
107+
// mock
108+
try (MockedConstruction<ManagedIdentityCredential> managedIdentityCredentialMock = mockConstruction(ManagedIdentityCredential.class, (managedIdentityCredential, context) -> {
109+
when(managedIdentityCredential.getToken(request))
110+
.thenReturn(Mono.error(
111+
new CredentialUnavailableException("Cannot get token from Managed Identity credential")));
112+
})) {
113+
// test
114+
AzureApplicationCredential credential = new AzureApplicationCredentialBuilder()
115+
.build();
116+
StepVerifier.create(credential.getToken(request))
117+
.expectErrorMatches(t -> t instanceof CredentialUnavailableException && t.getMessage()
118+
.startsWith("EnvironmentCredential authentication unavailable. "))
119+
.verify();
120+
Assert.assertNotNull(managedIdentityCredentialMock);
121+
}
133122
}
134123
}

0 commit comments

Comments
 (0)