summaryrefslogtreecommitdiff
path: root/tests/tests/wifi/src/android/net/wifi/sharedconnectivity/cts/SharedConnectivityTest.java
blob: 2f11f27a124f8e744052c8e299ce669c130af1d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
/*
 * Copyright (C) 2023 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.net.wifi.sharedconnectivity.cts;

import static com.google.common.truth.Truth.assertThat;

import static org.junit.Assert.assertThrows;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.sharedconnectivity.app.HotspotNetwork;
import android.net.wifi.sharedconnectivity.app.HotspotNetworkConnectionStatus;
import android.net.wifi.sharedconnectivity.app.KnownNetwork;
import android.net.wifi.sharedconnectivity.app.KnownNetworkConnectionStatus;
import android.net.wifi.sharedconnectivity.app.NetworkProviderInfo;
import android.net.wifi.sharedconnectivity.app.SharedConnectivityManager;
import android.net.wifi.sharedconnectivity.app.SharedConnectivitySettingsState;
import android.net.wifi.sharedconnectivity.app.cts.TestSharedConnectivityClientCallback;
import android.net.wifi.sharedconnectivity.service.cts.TestSharedConnectivityService;
import android.os.Build;
import android.os.Bundle;

import androidx.test.filters.SdkSuppress;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;

import com.android.compatibility.common.util.NonMainlineTest;

import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * These tests cover both SharedConnectivityService and SharedConnectivityManager.
 * Testing is done on these classes in their bound state.
 */
@RunWith(AndroidJUnit4.class)
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
@NonMainlineTest
public class SharedConnectivityTest {
    private static final String TAG = "SharedConnectivityTest";

    private static final String SERVICE_PACKAGE_NAME = "android.net.wifi.cts";
    private static final String SERVICE_INTENT_ACTION =
            "android.net.wifi.sharedconnectivity.service.cts.TestSharedConnectivityService.BIND";

    // Time between checks for state we expect.
    private static final long CHECK_DELAY_MILLIS = 500;
    // Number of times to check before failing.
    private static final long CHECK_RETRIES = 8;
    // Time to wait for callback's CountDownLatch.
    private static final long LATCH_TIMEOUT_SECS = 10;

    private static final HotspotNetwork TEST_HOTSPOT_NETWORK_1 = new HotspotNetwork.Builder()
            .setDeviceId(1)
            .setNetworkProviderInfo(new NetworkProviderInfo.Builder("Matt's Phone", "Pixel 6a")
                    .setDeviceType(NetworkProviderInfo.DEVICE_TYPE_PHONE)
                    .setBatteryPercentage(80)
                    .setConnectionStrength(3)
                    .build())
            .setHostNetworkType(HotspotNetwork.NETWORK_TYPE_CELLULAR)
            .setNetworkName("Google Fi")
            .setHotspotSsid("Instant Hotspot 12345")
            .setHotspotBssid("01:01:01:01:01:01")
            .addHotspotSecurityType(WifiInfo.SECURITY_TYPE_PSK)
            .build();

    private static final HotspotNetwork TEST_HOTSPOT_NETWORK_2 = new HotspotNetwork.Builder()
            .setDeviceId(2)
            .setNetworkProviderInfo(new NetworkProviderInfo.Builder("Matt's Laptop", "Pixelbook Go")
                    .setDeviceType(NetworkProviderInfo.DEVICE_TYPE_LAPTOP)
                    .setBatteryPercentage(30)
                    .setConnectionStrength(2)
                    .build())
            .setHostNetworkType(HotspotNetwork.NETWORK_TYPE_WIFI)
            .setNetworkName("Hotel Guest")
            .build();

    private static final KnownNetwork TEST_KNOWN_NETWORK_1 = new KnownNetwork.Builder()
            .setNetworkSource(KnownNetwork.NETWORK_SOURCE_NEARBY_SELF)
            .setSsid("Home Network")
            .addSecurityType(WifiInfo.SECURITY_TYPE_WEP)
            .setNetworkProviderInfo(new NetworkProviderInfo.Builder("Isaac's Phone", "Pixel 7")
                    .setDeviceType(NetworkProviderInfo.DEVICE_TYPE_PHONE)
                    .setBatteryPercentage(99)
                    .setConnectionStrength(3)
                    .build())
            .build();

    private static final KnownNetwork TEST_KNOWN_NETWORK_2 = new KnownNetwork.Builder()
            .setNetworkSource(KnownNetwork.NETWORK_SOURCE_NEARBY_SELF)
            .setSsid("Cafe Wifi")
            .addSecurityType(WifiInfo.SECURITY_TYPE_PSK)
            .setNetworkProviderInfo(new NetworkProviderInfo.Builder("Isaac's Work Phone",
                    "Pixel 7 Pro")
                    .setDeviceType(NetworkProviderInfo.DEVICE_TYPE_PHONE)
                    .setBatteryPercentage(15)
                    .setConnectionStrength(1)
                    .build())
            .build();

    private static final HotspotNetworkConnectionStatus TEST_HOTSPOT_NETWORK_CONNECTION_STATUS =
            new HotspotNetworkConnectionStatus.Builder()
                    .setStatus(HotspotNetworkConnectionStatus.CONNECTION_STATUS_ENABLING_HOTSPOT)
                    .setHotspotNetwork(TEST_HOTSPOT_NETWORK_1)
                    .setExtras(Bundle.EMPTY)
                    .build();

    private static final KnownNetworkConnectionStatus TEST_KNOWN_NETWORK_CONNECTION_STATUS =
            new KnownNetworkConnectionStatus.Builder()
                    .setStatus(KnownNetworkConnectionStatus.CONNECTION_STATUS_SAVED)
                    .setKnownNetwork(TEST_KNOWN_NETWORK_1)
                    .setExtras(Bundle.EMPTY)
                    .build();

    @Test
    public void registerCallback_withoutPermission_throwsSecurityException() throws Exception {
        Context context = InstrumentationRegistry.getInstrumentation().getContext();
        grantPermission();
        SharedConnectivityManager manager = getManager(context);
        TestSharedConnectivityClientCallback callback =
                new TestSharedConnectivityClientCallback();
        // Registrations done before the service is connected are cached and executed in the
        // background. Need to wait for the service to be connected to test.
        manager.registerCallback(Runnable::run, callback);
        TestSharedConnectivityService service = getService();
        assertServiceConnected(callback);

        dropPermission();

        TestSharedConnectivityClientCallback callback2 =
                new TestSharedConnectivityClientCallback();
        assertThrows(SecurityException.class,
                () -> manager.registerCallback(Runnable::run, callback2));
    }

    @Test
    public void registerCallback_onServiceConnectedCallbackReceived()
            throws Exception {
        Context context = InstrumentationRegistry.getInstrumentation().getContext();
        grantPermission();
        try {
            SharedConnectivityManager manager = getManager(context);
            TestSharedConnectivityClientCallback callback =
                    new TestSharedConnectivityClientCallback();
            manager.registerCallback(Runnable::run, callback);
            TestSharedConnectivityService service = getService();

            assertServiceConnected(callback);
        } finally {
            dropPermission();
        }
    }

    @Test
    public void unregisterCallback_beforeRegister_unregisterUnsuccessful() throws Exception {
        Context context = InstrumentationRegistry.getInstrumentation().getContext();
        grantPermission();
        try {
            SharedConnectivityManager manager = getManager(context);
            TestSharedConnectivityClientCallback callback =
                    new TestSharedConnectivityClientCallback();

            assertThat(manager.unregisterCallback(callback)).isFalse();
        } finally {
            dropPermission();
        }
    }

    @Test
    public void unregisterCallback_unregisterSuccessful() throws Exception {
        Context context = InstrumentationRegistry.getInstrumentation().getContext();
        grantPermission();
        try {
            SharedConnectivityManager manager = getManager(context);
            CountDownLatch callbackLatch = new CountDownLatch(1);
            TestSharedConnectivityClientCallback callback =
                    new TestSharedConnectivityClientCallback() {
                        @Override
                        public void onSharedConnectivitySettingsChanged(
                                SharedConnectivitySettingsState state) {
                            super.onSharedConnectivitySettingsChanged(state);
                            callbackLatch.countDown();
                        }
                    };
            // Need to successfully register callback before testing unregister method.
            manager.registerCallback(Runnable::run, callback);
            TestSharedConnectivityService service = getService();

            assertThat(manager.unregisterCallback(callback)).isTrue();
            // Try to use callback and validate that manager was not updated.
            service.setSettingsState(buildSettingsState());
            assertThat(callbackLatch.await(LATCH_TIMEOUT_SECS, TimeUnit.SECONDS)).isFalse();
            assertThat(callback.getSharedConnectivitySettingsState()).isNull();
        } finally {
            dropPermission();
        }
    }

    @Test
    public void setHotspotNetworks_managerCallbackReceivedWithCorrectData() throws Exception {
        Context context = InstrumentationRegistry.getInstrumentation().getContext();
        grantPermission();
        try {
            SharedConnectivityManager manager = getManager(context);
            CountDownLatch callbackLatch = new CountDownLatch(1);
            TestSharedConnectivityClientCallback callback =
                    new TestSharedConnectivityClientCallback() {
                        @Override
                        public void onHotspotNetworksUpdated(List<HotspotNetwork> networks) {
                            super.onHotspotNetworksUpdated(networks);
                            callbackLatch.countDown();
                        }
                    };
            manager.registerCallback(Runnable::run, callback);
            TestSharedConnectivityService service = getService();
            assertServiceConnected(callback);

            List<HotspotNetwork> networks = Arrays.asList(TEST_HOTSPOT_NETWORK_1,
                    TEST_HOTSPOT_NETWORK_2);
            service.setHotspotNetworks(networks);

            assertThat(callbackLatch.await(LATCH_TIMEOUT_SECS, TimeUnit.SECONDS)).isTrue();
            assertThat(callback.getHotspotNetworksList()).containsExactlyElementsIn(networks);
        } finally {
            dropPermission();
        }
    }

    @Test
    public void setKnownNetworks_managerCallbackReceivedWithCorrectData() throws Exception {
        Context context = InstrumentationRegistry.getInstrumentation().getContext();
        grantPermission();
        try {
            SharedConnectivityManager manager = getManager(context);
            CountDownLatch callbackLatch = new CountDownLatch(1);
            TestSharedConnectivityClientCallback callback =
                    new TestSharedConnectivityClientCallback() {
                        @Override
                        public void onKnownNetworksUpdated(List<KnownNetwork> networks) {
                            super.onKnownNetworksUpdated(networks);
                            callbackLatch.countDown();
                        }
                    };
            manager.registerCallback(Runnable::run, callback);
            TestSharedConnectivityService service = getService();
            assertServiceConnected(callback);

            List<KnownNetwork> networks = Arrays.asList(TEST_KNOWN_NETWORK_1, TEST_KNOWN_NETWORK_2);
            service.setKnownNetworks(networks);

            assertThat(callbackLatch.await(LATCH_TIMEOUT_SECS, TimeUnit.SECONDS)).isTrue();
            assertThat(callback.getKnownNetworksList()).containsExactlyElementsIn(networks);
        } finally {
            dropPermission();
        }
    }

    @Test
    public void setSettingsState_managerCallbackReceivedWithCorrectData() throws Exception {
        Context context = InstrumentationRegistry.getInstrumentation().getContext();
        grantPermission();
        try {
            SharedConnectivityManager manager = getManager(context);
            CountDownLatch callbackLatch = new CountDownLatch(1);
            TestSharedConnectivityClientCallback callback =
                    new TestSharedConnectivityClientCallback() {
                        @Override
                        public void onSharedConnectivitySettingsChanged(
                                SharedConnectivitySettingsState state) {
                            super.onSharedConnectivitySettingsChanged(state);
                            callbackLatch.countDown();
                        }
                    };
            manager.registerCallback(Runnable::run, callback);
            TestSharedConnectivityService service = getService();
            assertServiceConnected(callback);

            service.setSettingsState(buildSettingsState());

            assertThat(callbackLatch.await(LATCH_TIMEOUT_SECS, TimeUnit.SECONDS)).isTrue();
            assertThat(callback.getSharedConnectivitySettingsState()).isEqualTo(
                    buildSettingsState());
        } finally {
            dropPermission();
        }
    }

    @Test
    public void updateHotspotNetworkConnectionStatus_managerCallbackReceivedWithCorrectData()
            throws Exception {
        Context context = InstrumentationRegistry.getInstrumentation().getContext();
        grantPermission();
        try {
            SharedConnectivityManager manager = getManager(context);
            CountDownLatch callbackLatch = new CountDownLatch(1);
            TestSharedConnectivityClientCallback callback =
                    new TestSharedConnectivityClientCallback() {
                        @Override
                        public void onHotspotNetworkConnectionStatusChanged(
                                HotspotNetworkConnectionStatus status) {
                            super.onHotspotNetworkConnectionStatusChanged(status);
                            callbackLatch.countDown();
                        }
                    };
            manager.registerCallback(Runnable::run, callback);
            TestSharedConnectivityService service = getService();
            assertServiceConnected(callback);

            service.updateHotspotNetworkConnectionStatus(TEST_HOTSPOT_NETWORK_CONNECTION_STATUS);

            assertThat(callbackLatch.await(LATCH_TIMEOUT_SECS, TimeUnit.SECONDS)).isTrue();
            assertThat(callback.getHotspotNetworkConnectionStatus()).isEqualTo(
                    TEST_HOTSPOT_NETWORK_CONNECTION_STATUS);
        } finally {
            dropPermission();
        }
    }

    @Test
    public void updateKnownNetworkConnectionStatus_managerCallbackReceivedWithCorrectData()
            throws Exception {
        Context context = InstrumentationRegistry.getInstrumentation().getContext();
        grantPermission();
        try {
            SharedConnectivityManager manager = getManager(context);
            CountDownLatch callbackLatch = new CountDownLatch(1);
            TestSharedConnectivityClientCallback callback =
                    new TestSharedConnectivityClientCallback() {
                        @Override
                        public void onKnownNetworkConnectionStatusChanged(
                                KnownNetworkConnectionStatus status) {
                            super.onKnownNetworkConnectionStatusChanged(status);
                            callbackLatch.countDown();
                        }
                    };
            manager.registerCallback(Runnable::run, callback);
            TestSharedConnectivityService service = getService();
            assertServiceConnected(callback);

            service.updateKnownNetworkConnectionStatus(TEST_KNOWN_NETWORK_CONNECTION_STATUS);

            assertThat(callbackLatch.await(LATCH_TIMEOUT_SECS, TimeUnit.SECONDS)).isTrue();
            assertThat(callback.getKnownNetworkConnectionStatus()).isEqualTo(
                    TEST_KNOWN_NETWORK_CONNECTION_STATUS);
        } finally {
            dropPermission();
        }
    }

    @Test
    public void connectHotspotNetwork_serviceCallbackReceivedWithCorrectData() throws Exception {
        Context context = InstrumentationRegistry.getInstrumentation().getContext();
        grantPermission();
        try {
            SharedConnectivityManager manager = getManager(context);
            TestSharedConnectivityClientCallback callback =
                    new TestSharedConnectivityClientCallback();
            manager.registerCallback(Runnable::run, callback);
            TestSharedConnectivityService service = getService();
            assertServiceConnected(callback);

            assertThat(manager.connectHotspotNetwork(TEST_HOTSPOT_NETWORK_1)).isTrue();

            for (int i = 0; service.getConnectHotspotNetwork() == null && i < CHECK_RETRIES; i++) {
                Thread.sleep(CHECK_DELAY_MILLIS);
            }
            assertThat(service.getConnectHotspotNetwork()).isNotNull();
            assertThat(service.getConnectHotspotNetwork()).isEqualTo(TEST_HOTSPOT_NETWORK_1);
        } finally {
            dropPermission();
        }
    }

    @Test
    public void disconnectHotspotNetwork_serviceCallbackReceivedWithCorrectData() throws Exception {
        Context context = InstrumentationRegistry.getInstrumentation().getContext();
        grantPermission();
        try {
            SharedConnectivityManager manager = getManager(context);
            TestSharedConnectivityClientCallback callback =
                    new TestSharedConnectivityClientCallback();
            manager.registerCallback(Runnable::run, callback);
            TestSharedConnectivityService service = getService();
            assertServiceConnected(callback);

            manager.disconnectHotspotNetwork(TEST_HOTSPOT_NETWORK_1);

            for (int i = 0; service.getDisconnectHotspotNetwork() == null && i < CHECK_RETRIES;
                    i++) {
                Thread.sleep(CHECK_DELAY_MILLIS);
            }
            assertThat(service.getDisconnectHotspotNetwork()).isNotNull();
            assertThat(service.getDisconnectHotspotNetwork()).isEqualTo(TEST_HOTSPOT_NETWORK_1);
        } finally {
            dropPermission();
        }
    }

    @Test
    public void connectKnownNetwork_serviceCallbackReceivedWithCorrectData() throws Exception {
        Context context = InstrumentationRegistry.getInstrumentation().getContext();
        grantPermission();
        try {
            SharedConnectivityManager manager = getManager(context);
            TestSharedConnectivityClientCallback callback =
                    new TestSharedConnectivityClientCallback();
            manager.registerCallback(Runnable::run, callback);
            TestSharedConnectivityService service = getService();
            assertServiceConnected(callback);

            manager.connectKnownNetwork(TEST_KNOWN_NETWORK_1);

            for (int i = 0; service.getConnectKnownNetwork() == null && i < CHECK_RETRIES; i++) {
                Thread.sleep(CHECK_DELAY_MILLIS);
            }
            assertThat(service.getConnectKnownNetwork()).isNotNull();
            assertThat(service.getConnectKnownNetwork()).isEqualTo(TEST_KNOWN_NETWORK_1);
        } finally {
            dropPermission();
        }
    }

    @Test
    public void forgetKnownNetwork_serviceCallbackReceivedWithCorrectData() throws Exception {
        Context context = InstrumentationRegistry.getInstrumentation().getContext();
        grantPermission();
        try {
            SharedConnectivityManager manager = getManager(context);
            TestSharedConnectivityClientCallback callback =
                    new TestSharedConnectivityClientCallback();
            manager.registerCallback(Runnable::run, callback);
            TestSharedConnectivityService service = getService();
            assertServiceConnected(callback);

            manager.forgetKnownNetwork(TEST_KNOWN_NETWORK_1);

            for (int i = 0; service.getForgetKnownNetwork() == null && i < CHECK_RETRIES; i++) {
                Thread.sleep(CHECK_DELAY_MILLIS);
            }
            assertThat(service.getForgetKnownNetwork()).isNotNull();
            assertThat(service.getForgetKnownNetwork()).isEqualTo(TEST_KNOWN_NETWORK_1);
        } finally {
            dropPermission();
        }
    }

    private SharedConnectivityManager getManager(Context context) {
        return SharedConnectivityManager.create(context, SERVICE_PACKAGE_NAME,
                SERVICE_INTENT_ACTION);
    }

    private TestSharedConnectivityService getService() throws InterruptedException {
        TestSharedConnectivityService service = TestSharedConnectivityService.getInstance();
        for (int i = 0; service == null && i < CHECK_RETRIES; i++) {
            Thread.sleep(CHECK_DELAY_MILLIS);
            service = TestSharedConnectivityService.getInstance();
        }
        assertThat(service).isNotNull();
        return service;
    }

    private void grantPermission() {
        InstrumentationRegistry.getInstrumentation().getUiAutomation()
                .adoptShellPermissionIdentity(android.Manifest.permission.NETWORK_SETTINGS);
    }

    private void dropPermission() {
        InstrumentationRegistry.getInstrumentation().getUiAutomation()
                .dropShellPermissionIdentity();
    }

    private void assertServiceConnected(TestSharedConnectivityClientCallback callback)
            throws InterruptedException {
        assertThat(callback.getServiceConnectedLatch().await(LATCH_TIMEOUT_SECS,
                TimeUnit.SECONDS)).isTrue();
    }

    private SharedConnectivitySettingsState buildSettingsState() {
        Context context = InstrumentationRegistry.getInstrumentation().getContext();
        return new SharedConnectivitySettingsState.Builder()
                        .setInstantTetherEnabled(true)
                        .setInstantTetherSettingsPendingIntent(
                                PendingIntent.getActivity(context, 0, new Intent(),
                                        PendingIntent.FLAG_IMMUTABLE))
                        .setExtras(Bundle.EMPTY)
                        .build();
    }
}