summaryrefslogtreecommitdiff
path: root/tests/tests/telecom/src/android/telecom/cts/CallRedirectionServiceTest.java
blob: 060afe9e305fc9818d3e128882da6a6682a5f87a (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
/*
 * Copyright (C) 2019 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.telecom.cts;

import static android.telecom.cts.TestUtils.shouldTestTelecom;

import static com.android.compatibility.common.util.SystemUtil.runWithShellPermissionIdentity;

import android.app.role.RoleManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Process;
import android.os.UserHandle;
import android.telecom.Call;
import android.telecom.PhoneAccount;
import android.telecom.TelecomManager;
import android.telecom.cts.redirectiontestapp.CtsCallRedirectionService;
import android.telecom.cts.redirectiontestapp.CtsCallRedirectionServiceController;
import android.telecom.cts.redirectiontestapp.ICtsCallRedirectionServiceController;
import android.text.TextUtils;
import android.util.Log;

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

import junit.framework.AssertionFailedError;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public class CallRedirectionServiceTest extends BaseTelecomTestWithMockServices {
    private static final String TAG = CallRedirectionServiceTest.class.getSimpleName();
    private static final String TEST_APP_NAME = "CTSCRTest";
    private static final String TEST_APP_PACKAGE = "android.telecom.cts.redirectiontestapp";
    private static final String TEST_APP_COMPONENT = TEST_APP_PACKAGE
                    + "/android.telecom.cts.redirectiontestapp.CtsCallRedirectionService";
    private static final String ROLE_CALL_REDIRECTION = "android.app.role.CALL_REDIRECTION";

    private static final Uri SAMPLE_HANDLE = Uri.fromParts(PhoneAccount.SCHEME_TEL, "0001112222",
            null);
    private static final Uri SAMPLE_HANDLE_WITH_POST_DIAL = new Uri.Builder()
            .scheme(PhoneAccount.SCHEME_TEL)
            .encodedOpaquePart("6505551212,1234567890")
            .build();
    private static final Uri SAMPLE_REDIRECT_HANDLE = new Uri.Builder()
            .scheme(PhoneAccount.SCHEME_TEL)
            .encodedOpaquePart("6505551213")
            .build();
    private static final Uri SAMPLE_REDIRECT_HANDLE_WITH_POST_DIAL = new Uri.Builder()
            .scheme(PhoneAccount.SCHEME_TEL)
            .encodedOpaquePart("6505551213,1234567890")
            .build();
    private static final int ASYNC_TIMEOUT = 10000;
    private RoleManager mRoleManager;
    private Handler mHandler;
    private Call mCall;
    private String mPreviousCallRedirectionPackage;
    private ICtsCallRedirectionServiceController mCallRedirectionServiceController;

    private MockInCallService mInCallService;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        if (!mShouldTestTelecom) {
            return;
        }
        NewOutgoingCallBroadcastReceiver.reset();
        mHandler = new Handler(Looper.getMainLooper());
        mRoleManager = (RoleManager) mContext.getSystemService(Context.ROLE_SERVICE);
        setupControlBinder(null, null);
        setupConnectionService(null, FLAG_REGISTER | FLAG_ENABLE);
        rememberPreviousCallRedirectionApp();
        // Ensure CTS app holds the call redirection role.
        addRoleHolder(ROLE_CALL_REDIRECTION,
                CtsCallRedirectionService.class.getPackage().getName());
        setupForEmergencyCalling(TEST_EMERGENCY_NUMBER);
    }

    @Override
    protected void tearDown() throws Exception {
        super.tearDown();
        if (!mShouldTestTelecom) {
            return;
        }
        if (mCallRedirectionServiceController != null) {
            mCallRedirectionServiceController.reset();
        }
        // Remove the test app from the redirection role.
        removeRoleHolder(ROLE_CALL_REDIRECTION,
                CtsCallRedirectionService.class.getPackage().getName());

        if (!TextUtils.isEmpty(mPreviousCallRedirectionPackage)) {
            addRoleHolder(ROLE_CALL_REDIRECTION, mPreviousCallRedirectionPackage);
        }
    }

    public void testRedirectedCallWithRedirectedGateway()
            throws Exception {
        if (!shouldTestTelecom(mContext)) {
            return;
        }
        mCallRedirectionServiceController.setRedirectCall(
                SAMPLE_HANDLE, null, false);
        placeAndVerifyCallByRedirection(false /* cancelledByCallRedirection */);
        mInCallService = mInCallCallbacks.getService();
        assertCallGatewayConstructed(mInCallService.getLastCall(), true);
        mCall = mInCallService.getLastCall();
        assertEquals(SAMPLE_HANDLE, mCall.getDetails().getGatewayInfo().getGatewayAddress());
        assertEquals(getTestNumber(), mCall.getDetails().getGatewayInfo().getOriginalAddress());
        assertEquals(TestUtils.TEST_PHONE_ACCOUNT_HANDLE, mCall.getDetails().getAccountHandle());
        assertTrue(Call.STATE_DISCONNECTED != mCall.getState());
    }

    /**
     * Verifies that post-dial digits will be re-added to a number after redirection.
     * @throws Exception
     */
    public void testRedirectedCallWithPostDialDigits() throws Exception {
        if (!shouldTestTelecom(mContext)) {
            return;
        }
        mCallRedirectionServiceController.setRedirectCall(SAMPLE_REDIRECT_HANDLE, null, false);
        Bundle extras = new Bundle();
        extras.putParcelable(TestUtils.EXTRA_PHONE_NUMBER, SAMPLE_HANDLE_WITH_POST_DIAL);
        placeAndVerifyCallByRedirection(extras, false /* cancelledByCallRedirection */);
        mInCallService = mInCallCallbacks.getService();
        assertCallGatewayConstructed(mInCallService.getLastCall(), true);
        mCall = mInCallService.getLastCall();
        assertEquals(SAMPLE_REDIRECT_HANDLE_WITH_POST_DIAL,
                mCall.getDetails().getGatewayInfo().getGatewayAddress());
        // The , (pause) separators get URI encoded in the call intent; compare decoded scheme to
        // ensure proper equality for what it essentially the same thing.
        assertEquals(Uri.decode(SAMPLE_HANDLE_WITH_POST_DIAL.getSchemeSpecificPart()),
                Uri.decode(mCall.getDetails().getGatewayInfo().getOriginalAddress()
                        .getSchemeSpecificPart()));
        assertEquals(SAMPLE_REDIRECT_HANDLE_WITH_POST_DIAL,
                mCall.getDetails().getHandle());
        assertEquals(TestUtils.TEST_PHONE_ACCOUNT_HANDLE, mCall.getDetails().getAccountHandle());
        assertTrue(Call.STATE_DISCONNECTED != mCall.getState());
    }

    public void testRedirectedCallWithRedirectedPhoneAccount()
            throws Exception {
        if (!shouldTestTelecom(mContext)) {
            return;
        }
        mCallRedirectionServiceController.setRedirectCall(
                SAMPLE_HANDLE, TestUtils.TEST_PHONE_ACCOUNT_HANDLE_2, false);
        placeAndVerifyCallByRedirection(false /* cancelledByCallRedirection */);
        mInCallService = mInCallCallbacks.getService();
        assertCallGatewayConstructed(mInCallService.getLastCall(), true);
        mCall = mInCallService.getLastCall();
        assertEquals(SAMPLE_HANDLE, mCall.getDetails().getGatewayInfo().getGatewayAddress());
        assertEquals(getTestNumber(), mCall.getDetails().getGatewayInfo().getOriginalAddress());
        assertEquals(TestUtils.TEST_PHONE_ACCOUNT_HANDLE_2, mCall.getDetails().getAccountHandle());
        assertTrue(Call.STATE_DISCONNECTED != mCall.getState());
    }

    public void testCancelCall() throws Exception {
        if (!shouldTestTelecom(mContext)) {
            return;
        }
        mCallRedirectionServiceController.setCancelCall();
        placeAndVerifyCallByRedirection(true /* cancelledByCallRedirection */);
        mInCallService = mInCallCallbacks.getService();
        mCall = mInCallService.getLastCall();
        assertCallNotNull(mCall, false);
    }

    public void testPlaceCallUnmodified() throws Exception {
        if (!shouldTestTelecom(mContext)) {
            return;
        }
        mCallRedirectionServiceController.setPlaceCallUnmodified();
        placeAndVerifyCallByRedirection(false /* cancelledByCallRedirection */);
        mInCallService = mInCallCallbacks.getService();
        assertCallDetailsConstructed(mInCallService.getLastCall(), true);
        mCall = mInCallService.getLastCall();
        assertEquals(getTestNumber(), mCall.getDetails().getHandle());
        assertEquals(TestUtils.TEST_PHONE_ACCOUNT_HANDLE, mCall.getDetails().getAccountHandle());
        assertTrue(Call.STATE_DISCONNECTED != mCall.getState());
    }

    public void testNotifyTimeout() throws Exception {
        if (!shouldTestTelecom(mContext)) {
            return;
        }
        mCallRedirectionServiceController.setWaitForTimeout();
        try {
            placeAndVerifyCallByRedirection(false /* cancelledByCallRedirection */);
        } catch (AssertionFailedError e) {
            // Expected since we set the CallRedirectionService wait for timeout
        }
        assertTrue(mCallRedirectionServiceController.waitForTimeoutNotified());
    }

    public void testCantRedirectEmergencyCall() throws Exception {
        if (!shouldTestTelecom(mContext)) {
            return;
        }
        Bundle extras = new Bundle();
        extras.putParcelable(TestUtils.EXTRA_PHONE_NUMBER, TEST_EMERGENCY_URI);
        mCallRedirectionServiceController.setRedirectCall(
                SAMPLE_HANDLE, TestUtils.TEST_PHONE_ACCOUNT_HANDLE_2, false);
        placeAndVerifyCallByRedirection(extras, false /* cancelledByCallRedirection */);
        assertFalse(mCallRedirectionServiceController.waitForOnPlaceCallInvoked());
    }

    public void testServiceUnbindOnNullBinding()
            throws Exception {
        if (!shouldTestTelecom(mContext)) {
            return;
        }
        // Set up control binder using NullBindingCallRedirectionServiceController.
        // This will invoke onNullBinding.
        setupControlBinder(NullBindingCallRedirectionServiceController.CONTROL_INTERFACE_ACTION,
                NullBindingCallRedirectionServiceController.CONTROL_INTERFACE_COMPONENT);
        Bundle extras = new Bundle();
        extras.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE,
                TestUtils.TEST_PHONE_ACCOUNT_HANDLE);
        mTelecomManager.placeCall(createTestNumber(), extras);
        TestUtils.waitOnLocalMainLooper(TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS);
        TestUtils.waitOnAllHandlers(getInstrumentation());
        // Assert bind and unbind latch countdown
        assertTrue(TestUtils.waitForLatchCountDown(
                NullBindingCallRedirectionServiceController.sBindLatch));
        assertTrue(TestUtils.waitForLatchCountDown(
                NullBindingCallRedirectionServiceController.sUnbindLatch));
    }

    /**
     * Sets up a binder used to control the CallRedirectionServiceCtsTestApp.
     * This app is a standalone APK so that it can reside in a package name outside of the one the
     * CTS test itself runs in.
     * @throws InterruptedException
     */
    private void setupControlBinder(String interfaceAction,
            ComponentName interfaceComponentName) throws InterruptedException {
        if (interfaceAction == null) {
            interfaceAction = CtsCallRedirectionServiceController.CONTROL_INTERFACE_ACTION;
        }
        if (interfaceComponentName == null) {
            interfaceComponentName =
                    CtsCallRedirectionServiceController.CONTROL_INTERFACE_COMPONENT;
        }

        Intent bindIntent = new Intent(interfaceAction);
        bindIntent.setComponent(interfaceComponentName);
        final CountDownLatch bindLatch = new CountDownLatch(1);

        boolean success = mContext.bindService(bindIntent, new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                mCallRedirectionServiceController =
                        ICtsCallRedirectionServiceController.Stub.asInterface(service);
                bindLatch.countDown();
            }
            @Override
            public void onServiceDisconnected(ComponentName name) {
                mCallRedirectionServiceController = null;
            }

            @Override
            public void onNullBinding(ComponentName name) {
                // This path will only be hit if NullBindingCallRedirectionServiceController is set
                // as the controller.
                Log.i(TAG, "onNullBinding: null binding received from onBind");
                bindLatch.countDown();
                mContext.unbindService(this);
            }
        }, Context.BIND_AUTO_CREATE);
        if (!success) {
            fail("Failed to get control interface -- bind error");
        }
        bindLatch.await(ASYNC_TIMEOUT, TimeUnit.MILLISECONDS);
    }

    /**
     * Use RoleManager to query the previous call redirection app so we can restore it later.
     */
    @CddTest(requirement ="3.2.3.5/C-2-5")
    private void rememberPreviousCallRedirectionApp() {
        runWithShellPermissionIdentity(() -> {
            List<String> callRedirectionApps = mRoleManager.getRoleHolders(ROLE_CALL_REDIRECTION);
            if (!callRedirectionApps.isEmpty()) {
                mPreviousCallRedirectionPackage = callRedirectionApps.get(0);
            } else {
                mPreviousCallRedirectionPackage = null;
            }
        });
    }

    @CddTest(requirement="3.2.3.5/C-2-4")
    private void addRoleHolder(String roleName, String packageName) throws Exception {
        UserHandle user = Process.myUserHandle();
        Executor executor = mContext.getMainExecutor();
        LinkedBlockingQueue<Boolean> queue = new LinkedBlockingQueue(1);

        runWithShellPermissionIdentity(() -> mRoleManager.addRoleHolderAsUser(roleName,
                packageName, RoleManager.MANAGE_HOLDERS_FLAG_DONT_KILL_APP, user, executor,
                successful -> {
                        try {
                            queue.put(successful);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }));
        boolean result = queue.poll(ASYNC_TIMEOUT, TimeUnit.MILLISECONDS);
        assertTrue(result);
    }

    private void removeRoleHolder(String roleName, String packageName)
            throws Exception {
        UserHandle user = Process.myUserHandle();
        Executor executor = mContext.getMainExecutor();
        LinkedBlockingQueue<Boolean> queue = new LinkedBlockingQueue(1);

        runWithShellPermissionIdentity(() -> mRoleManager.removeRoleHolderAsUser(roleName,
                packageName, RoleManager.MANAGE_HOLDERS_FLAG_DONT_KILL_APP, user, executor,
                successful -> {
                    try {
                        queue.put(successful);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }));
        boolean result = queue.poll(ASYNC_TIMEOUT, TimeUnit.MILLISECONDS);
        assertTrue(result);
    }
}