Skip to content

Commit af1bb2c

Browse files
fix: remove deprecated wifi management from tests (#2044)
The use of `WifiManager`'s `setWifiEnabled(...)` was originally added to this code base with the intention of toggling on/off connectivity, to test offline scenarios. From the beginning, this usage was flawed. The Android emulator will happily continue to serve traffic through a fake cellular connection. So, unless you pre-arrange a device to not have any other source of connetivity than WiFi, the call to `setWifiEnabled(...)` is useless. Worse, as of API 29, this method is officially deprecated. Oh well. As a replacement, use the UIAutomator-based `InternetConnectivity` utility that had recently been added to this codebase under `-testutils`. This utility works by clicking the airplane mode button in the device's settings drop-down. This change removes the use of a deprecated API, and also improves the correctness of the offline tests. One that had been `@Ignore`d is re-enabled. This commit includes assorted code quality fixes in the effected files, as well.
1 parent c46aae4 commit af1bb2c

File tree

7 files changed

+103
-128
lines changed

7 files changed

+103
-128
lines changed

aws-android-sdk-mobile-client/build.gradle

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ android {
1010
targetSdkVersion 29
1111
versionCode 1
1212
versionName '1.0'
13+
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
1314
}
1415

1516
compileOptions {
@@ -53,6 +54,7 @@ dependencies {
5354
androidTestImplementation 'androidx.appcompat:appcompat:1.1.0'
5455
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
5556
androidTestImplementation 'androidx.test:rules:1.2.0'
57+
androidTestImplementation 'androidx.test:runner:1.2.0'
5658

5759
androidTestImplementation (project(':aws-android-sdk-auth-facebook')) {
5860
exclude group: 'com.google.android', module: 'android'

aws-android-sdk-mobile-client/src/androidTest/AndroidManifest.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<?xml version="1.0" encoding="utf-8"?>
22
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
33
xmlns:amazon="http://schemas.amazon.com/apk/res/android"
4-
package="com.amazonaws.mobile.client">
4+
package="com.amazonaws.mobile.client.test">
55

66
<uses-permission android:name="android.permission.INTERNET" />
77
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

aws-android-sdk-mobile-client/src/androidTest/java/com/amazonaws/mobile/client/AWSMobileClientOfflineTest.java

Lines changed: 47 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -16,49 +16,42 @@
1616
*/
1717
package com.amazonaws.mobile.client;
1818

19-
import android.content.Context;
20-
import android.net.wifi.WifiManager;
21-
22-
import androidx.test.core.app.ApplicationProvider;
23-
19+
import com.amazonaws.mobile.client.test.R;
2420
import com.amazonaws.mobile.config.AWSConfiguration;
2521

2622
import org.json.JSONException;
23+
import org.json.JSONObject;
2724
import org.junit.After;
25+
import org.junit.AfterClass;
2826
import org.junit.Before;
2927
import org.junit.BeforeClass;
30-
import org.junit.Ignore;
3128
import org.junit.Test;
3229

3330
import java.util.Queue;
3431
import java.util.concurrent.ConcurrentLinkedQueue;
3532
import java.util.concurrent.CountDownLatch;
3633

34+
import static androidx.test.core.app.ApplicationProvider.getApplicationContext;
35+
import static com.amazonaws.testutils.util.InternetConnectivity.goOffline;
36+
import static com.amazonaws.testutils.util.InternetConnectivity.goOnline;
3737
import static org.junit.Assert.assertEquals;
3838
import static org.junit.Assert.assertNotNull;
3939
import static org.junit.Assert.assertTrue;
40-
import static org.junit.Assert.fail;
4140

4241
/**
43-
* Userpool and identity pool were create with Amplify CLI 0.1.23 Default configuration
42+
* User pool and identity pool were create with Amplify CLI 0.1.23 Default configuration
4443
*/
45-
public class AWSMobileClientOfflineTest extends AWSMobileClientTestBase {
46-
47-
Context appContext;
48-
AWSMobileClient auth;
49-
UserStateListener listener;
50-
51-
public static void setWifi(final Context appContext, final boolean state) {
52-
WifiManager wifiManager = (WifiManager)appContext.getSystemService(Context.WIFI_SERVICE);
53-
wifiManager.setWifiEnabled(state);
54-
}
44+
public final class AWSMobileClientOfflineTest extends AWSMobileClientTestBase {
45+
private static AWSMobileClient auth;
46+
private UserStateListener listener;
5547

5648
@BeforeClass
57-
public static void setup() throws Exception {
58-
Context appContext = ApplicationProvider.getApplicationContext();
59-
setWifi(appContext, false);
60-
final CountDownLatch latch = new CountDownLatch(1);
61-
AWSMobileClient.getInstance().initialize(appContext, new Callback<UserStateDetails>() {
49+
public static void beforeSuite() throws Exception {
50+
goOffline();
51+
CountDownLatch latch = new CountDownLatch(1);
52+
auth = AWSMobileClient.getInstance();
53+
AWSConfiguration config = new AWSConfiguration(getApplicationContext(), R.raw.fakeawsconfiguration);
54+
auth.initialize(getApplicationContext(), config, new Callback<UserStateDetails>() {
6255
@Override
6356
public void onResult(UserStateDetails result) {
6457
latch.countDown();
@@ -71,68 +64,56 @@ public void onError(Exception e) {
7164
});
7265
latch.await();
7366

74-
final AWSConfiguration awsConfiguration = AWSMobileClient.getInstance().getConfiguration();
75-
76-
assertNotNull(awsConfiguration.optJsonObject("CognitoUserPool"));
77-
try {
78-
assertEquals("us-west-2", awsConfiguration.optJsonObject("CognitoUserPool").getString("Region"));
79-
} catch (JSONException e) {
80-
e.printStackTrace();
81-
fail(e.getMessage());
82-
}
67+
AWSConfiguration awsConfiguration = auth.getConfiguration();
68+
JSONObject userPoolConfig = awsConfiguration.optJsonObject("CognitoUserPool");
69+
assertNotNull(userPoolConfig);
70+
assertEquals("us-west-2", userPoolConfig.getString("Region"));
8371
}
8472

8573
@Before
86-
public void cleanUp() {
87-
appContext = ApplicationProvider.getApplicationContext();
88-
auth = AWSMobileClient.getInstance();
74+
public void beforeTest() {
8975
auth.signOut();
9076
}
9177

9278
@After
93-
public void cleanAfter() {
79+
public void afterTest() {
9480
auth.removeUserStateListener(listener);
9581
auth.listeners.clear();
9682
}
9783

98-
@Test
99-
public void useAppContext() throws Exception {
100-
// Context of the app under test.
101-
Context appContext = ApplicationProvider.getApplicationContext();
102-
103-
final AWSConfiguration awsConfiguration = new AWSConfiguration(appContext);
104-
105-
assertNotNull(awsConfiguration.optJsonObject("CognitoUserPool"));
106-
assertEquals("us-west-2", awsConfiguration.optJsonObject("CognitoUserPool").getString("Region"));
84+
@AfterClass
85+
public static void afterSuite() {
86+
goOnline();
87+
}
10788

108-
assertEquals("com.amazonaws.mobile.client.test", appContext.getPackageName());
89+
@Test
90+
public void useAppContext() throws JSONException {
91+
AWSConfiguration awsConfiguration = new AWSConfiguration(getApplicationContext(), R.raw.fakeawsconfiguration);
92+
JSONObject userPoolConfig = awsConfiguration.optJsonObject("CognitoUserPool");
93+
assertNotNull(userPoolConfig);
94+
assertEquals("us-west-2", userPoolConfig.getString("Region"));
95+
assertEquals(
96+
"com.amazonaws.mobile.client.test",
97+
getApplicationContext().getPackageName()
98+
);
10999
}
110100

111101
@Test
112102
public void testGetConfiguration() throws JSONException {
113-
final AWSConfiguration awsConfiguration = AWSMobileClient.getInstance().getConfiguration();
114-
115-
assertNotNull(awsConfiguration.optJsonObject("CognitoUserPool"));
116-
try {
117-
assertEquals("us-west-2", awsConfiguration.optJsonObject("CognitoUserPool").getString("Region"));
118-
} catch (JSONException e) {
119-
e.printStackTrace();
120-
fail(e.getMessage());
121-
}
103+
AWSConfiguration awsConfiguration = auth.getConfiguration();
104+
JSONObject userPoolConfig = awsConfiguration.optJsonObject("CognitoUserPool");
105+
assertNotNull(userPoolConfig);
106+
assertEquals(
107+
"us-west-2",
108+
userPoolConfig.getString("Region")
109+
);
122110
}
123111

124-
@Ignore("If network is on on the emulator, this test may get stuck")
125112
@Test
126-
public void testSignInWaitOIDCOffline() throws Exception {
127-
final Queue<UserStateDetails> allChanges = new ConcurrentLinkedQueue<UserStateDetails>();
128-
129-
setTokensDirectly(appContext, AWSMobileClient.getInstance().getLoginKey(), "fakeToken", "someIdentityId");
130-
listener = new UserStateListener() {
131-
@Override
132-
public void onUserStateChanged(UserStateDetails details) {
133-
allChanges.add(details);
134-
}
135-
};
113+
public void testSignInWaitOIDCOffline() {
114+
Queue<UserStateDetails> allChanges = new ConcurrentLinkedQueue<>();
115+
setTokensDirectly(getApplicationContext(), auth.getLoginKey(), "fakeToken", "someIdentityId");
116+
listener = allChanges::add;
136117
auth.addUserStateListener(listener);
137118
assertTrue("User is offline and tokens are invalid", auth.isSignedIn());
138119

@@ -144,5 +125,4 @@ public void onUserStateChanged(UserStateDetails details) {
144125
assertEquals("1 signed-in events should not have been triggered, because tokens swapped underneath", 1, allChanges.size());
145126
assertEquals(UserState.SIGNED_IN, allChanges.remove().getUserState());
146127
}
147-
148128
}

aws-android-sdk-mobile-client/src/androidTest/java/com/amazonaws/mobile/client/AWSMobileClientTestBase.java

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
package com.amazonaws.mobile.client;
1919

2020
import android.content.Context;
21-
import android.net.wifi.WifiManager;
2221
import androidx.test.core.app.ApplicationProvider;
2322
import android.util.Base64;
2423

@@ -48,11 +47,6 @@ public static JSONObject getPackageConfigure() {
4847
return getPackageConfigure(PACKAGE_NAME);
4948
}
5049

51-
public static void setWifi(final Context appContext, final boolean wifiState) {
52-
WifiManager wifiManager = (WifiManager) appContext.getSystemService(Context.WIFI_SERVICE);
53-
wifiManager.setWifiEnabled(wifiState);
54-
}
55-
5650
public static void setTokensDirectly(final Context appContext,
5751
final String providerKey,
5852
final String token,
@@ -110,7 +104,7 @@ public static String getValidJWT(long expiryInSecs){
110104
epoch = epoch + expiryInSecs;
111105
String accessToken_p1_Base64 = "eyJ0eXAiOiAiSldUIiwgImFsZyI6IlJTMjU2In0=";
112106
String accessToken_p3_Base64 = "e0VuY3J5cHRlZF9LZXl9";
113-
String accessToken_p2_Str = "{\"iss\": \"userPoolId\",\"sub\": \"[email protected]\",\"aud\": \"https:aws.cognito.com\",\"exp\": \"" + String.valueOf(epoch) + "\"}";
107+
String accessToken_p2_Str = "{\"iss\": \"userPoolId\",\"sub\": \"[email protected]\",\"aud\": \"https:aws.cognito.com\",\"exp\": \"" + epoch + "\"}";
114108
byte[] accessToken_p2_UTF8 = accessToken_p2_Str.getBytes(StringUtils.UTF8);
115109
String accessToken_p2_Base64 = new String(Base64.encode(accessToken_p2_UTF8, Base64.DEFAULT));
116110
return accessToken_p1_Base64 + "." + accessToken_p2_Base64 + "." + accessToken_p3_Base64;
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
{
2+
"UserAgent": "aws-amplify/cli",
3+
"Version": "0.1.0",
4+
"IdentityManager": {
5+
"Default": {}
6+
},
7+
"CredentialsProvider": {
8+
"CognitoIdentity": {
9+
"Default": {
10+
"__comment": "This was never a real pool. Just a random uuid.",
11+
"PoolId": "us-west-2:d7dd1ff8-908d-4d46-a5e2-a33be23bdade",
12+
"Region": "us-west-2"
13+
}
14+
}
15+
},
16+
"CognitoUserPool": {
17+
"Default": {
18+
"PoolId": "us-west-2_K00lpooL5",
19+
"AppClientId": "app22client44SecretId0",
20+
"AppClientSecret": "appclientsecret5500secretyes",
21+
"Region": "us-west-2"
22+
}
23+
}
24+
}
25+

aws-android-sdk-pinpoint-test/build.gradle

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ android {
55
compileSdkVersion 29
66

77
defaultConfig {
8-
minSdkVersion 14
8+
minSdkVersion 18 // UIAutomator
99
targetSdkVersion 29
1010
versionCode 1
1111
versionName '1.0'
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
/**
1+
/*
22
* Copyright 2019-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License").
@@ -15,11 +15,6 @@
1515

1616
package com.amazonaws.mobileconnectors.pinpoint.analytics;
1717

18-
import android.content.Context;
19-
import android.net.wifi.WifiManager;
20-
21-
import androidx.test.core.app.ApplicationProvider;
22-
2318
import com.amazonaws.auth.CognitoCachingCredentialsProvider;
2419
import com.amazonaws.mobileconnectors.pinpoint.PinpointConfiguration;
2520
import com.amazonaws.mobileconnectors.pinpoint.PinpointManager;
@@ -30,14 +25,15 @@
3025
import com.amazonaws.services.pinpoint.model.ChannelType;
3126
import com.amazonaws.testutils.AWSTestBase;
3227

28+
import org.json.JSONObject;
3329
import org.junit.After;
3430
import org.junit.Before;
3531
import org.junit.Test;
3632

37-
import java.util.Arrays;
3833
import java.util.Collections;
3934

40-
import static junit.framework.TestCase.assertTrue;
35+
import static androidx.test.core.app.ApplicationProvider.getApplicationContext;
36+
import static com.amazonaws.testutils.util.InternetConnectivity.goOnline;
4137
import static org.junit.Assert.assertEquals;
4238
import static org.junit.Assert.assertNotNull;
4339
import static org.junit.Assert.assertNull;
@@ -48,53 +44,31 @@
4844
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
4945
*/
5046
public class EndpointProfileIntegrationTest extends AWSTestBase {
51-
52-
private static Context appContext;
53-
5447
private PinpointManager pinpointManager;
55-
private PinpointConfiguration pinpointConfiguration;
5648
private CognitoCachingCredentialsProvider credentialsProvider;
57-
private WifiManager wifiManager;
58-
59-
private String appId;
60-
private Regions regions;
61-
62-
private static String TAG = EndpointProfileIntegrationTest.class.getSimpleName();
6349

6450
@Before
6551
public void setUp() throws Exception {
66-
final String identityPoolId = getPackageConfigure("pinpoint")
67-
.getString("identity_pool_id");
68-
69-
appId = getPackageConfigure("pinpoint")
70-
.getString("AppId");
71-
regions = Regions.fromName(getPackageConfigure("pinpoint")
72-
.getString("Region"));
73-
74-
appContext = ApplicationProvider.getApplicationContext();
75-
appContext.deleteDatabase("awspinpoint.db");
76-
77-
wifiManager = (WifiManager) ApplicationProvider.getApplicationContext()
78-
.getSystemService(Context.WIFI_SERVICE);
79-
assertTrue(wifiManager.setWifiEnabled(true));
80-
81-
credentialsProvider = new CognitoCachingCredentialsProvider(
82-
appContext,
83-
identityPoolId,
84-
regions);
85-
pinpointConfiguration = new PinpointConfiguration(appContext,
86-
appId,
87-
regions,
88-
ChannelType.GCM,
89-
credentialsProvider);
52+
JSONObject testConfig = getPackageConfigure("pinpoint");
53+
String identityPoolId = testConfig.getString("identity_pool_id");
54+
String appId = testConfig.getString("AppId");
55+
Regions regions = Regions.fromName(testConfig.getString("Region"));
56+
57+
getApplicationContext().deleteDatabase("awspinpoint.db");
58+
goOnline();
59+
60+
credentialsProvider =
61+
new CognitoCachingCredentialsProvider(getApplicationContext(), identityPoolId, regions);
62+
PinpointConfiguration pinpointConfiguration =
63+
new PinpointConfiguration(getApplicationContext(), appId, regions, ChannelType.GCM, credentialsProvider);
9064
pinpointManager = new PinpointManager(pinpointConfiguration);
9165
}
9266

9367
@After
9468
public void tearDown() {
95-
assertTrue(wifiManager.setWifiEnabled(true));
69+
goOnline();
9670
pinpointManager.getAnalyticsClient().closeDB();
97-
appContext.deleteDatabase("awspinpoint.db");
71+
getApplicationContext().deleteDatabase("awspinpoint.db");
9872
}
9973

10074
@Test
@@ -116,18 +90,18 @@ public void testEndpointProfileUpdate() {
11690
targetingClient.updateEndpointProfile();
11791
endpointProfile = targetingClient.currentEndpoint();
11892
assertNotNull(endpointProfile);
119-
assertEquals(credentialsProvider.getIdentityId(),
120-
endpointProfile.getUser().getUserId());
93+
assertEquals(credentialsProvider.getIdentityId(), endpointProfile.getUser().getUserId());
12194
assertNotNull(endpointProfile.getUser().getUserAttributes());
122-
assertEquals(Collections.singletonMap("user-key", Collections.singletonList("user-value")),
123-
endpointProfile.getUser().getUserAttributes());
95+
assertEquals(
96+
Collections.singletonMap("user-key", Collections.singletonList("user-value")),
97+
endpointProfile.getUser().getUserAttributes()
98+
);
12499

125-
endpointProfile.addAttribute("key", Arrays.asList("value"));
100+
endpointProfile.addAttribute("key", Collections.singletonList("value"));
126101
targetingClient.updateEndpointProfile();
127102
endpointProfile = targetingClient.currentEndpoint();
128103
assertNotNull(endpointProfile);
129-
assertEquals(credentialsProvider.getIdentityId(),
130-
endpointProfile.getUser().getUserId());
131-
assertEquals("value", endpointProfile.getAllAttributes().get("key").get(0));
104+
assertEquals(credentialsProvider.getIdentityId(), endpointProfile.getUser().getUserId());
105+
assertEquals(Collections.singletonList("value"), endpointProfile.getAllAttributes().get("key"));
132106
}
133107
}

0 commit comments

Comments
 (0)