summaryrefslogtreecommitdiff
path: root/tests/autofillservice/src/android/autofillservice/cts/SessionLifecycleTest.java
blob: 6dd4d1ae033bf5899dabaa24590cd4a6625ca62b (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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
/*
 * Copyright (C) 2017 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.autofillservice.cts;

import static android.autofillservice.cts.activities.OutOfProcessLoginActivity.getDestroyedMarker;
import static android.autofillservice.cts.activities.OutOfProcessLoginActivity.getStartedMarker;
import static android.autofillservice.cts.activities.OutOfProcessLoginActivity.getStoppedMarker;
import static android.autofillservice.cts.testcore.Helper.ID_LOGIN;
import static android.autofillservice.cts.testcore.Helper.ID_PASSWORD;
import static android.autofillservice.cts.testcore.Helper.ID_USERNAME;
import static android.autofillservice.cts.testcore.Helper.assertTextAndValue;
import static android.autofillservice.cts.testcore.Helper.findNodeByResourceId;
import static android.autofillservice.cts.testcore.Helper.getContext;
import static android.autofillservice.cts.testcore.UiBot.LANDSCAPE;
import static android.autofillservice.cts.testcore.UiBot.PORTRAIT;
import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_PASSWORD;
import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_USERNAME;

import static com.android.compatibility.common.util.ShellUtils.runShellCommand;

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

import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue;

import android.app.ActivityManager;
import android.app.PendingIntent;
import android.app.assist.AssistStructure;
import android.autofillservice.cts.activities.EmptyActivity;
import android.autofillservice.cts.activities.LoginActivity;
import android.autofillservice.cts.activities.ManualAuthenticationActivity;
import android.autofillservice.cts.activities.OutOfProcessLoginActivity;
import android.autofillservice.cts.commontests.AutoFillServiceTestCase;
import android.autofillservice.cts.testcore.CannedFillResponse;
import android.autofillservice.cts.testcore.Helper;
import android.autofillservice.cts.testcore.InstrumentedAutoFillService;
import android.autofillservice.cts.testcore.Timeouts;
import android.autofillservice.cts.testcore.UiBot;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.platform.test.annotations.AppModeFull;
import android.support.test.uiautomator.UiObject2;
import android.util.Log;
import android.view.autofill.AutofillValue;
import android.view.View;

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

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.concurrent.Callable;

/**
 * Test the lifecycle of a autofill session
 */
@AppModeFull(reason = "This test requires android.permission.WRITE_EXTERNAL_STORAGE")
public class SessionLifecycleTest extends AutoFillServiceTestCase.ManualActivityLaunch {
    private static final String TAG = "SessionLifecycleTest";

    private static final String ID_BUTTON = "button";
    private static final String ID_CANCEL = "cancel";

    /**
     * Delay for activity start/stop.
     */
    // TODO: figure out a better way to wait without using sleep().
    private static final long WAIT_ACTIVITY_MS = 1000;

    private static final Timeout SESSION_LIFECYCLE_TIMEOUT = new Timeout(
            "SESSION_LIFECYCLE_TIMEOUT", 5000, 2F, 5000);

    /**
     * Runs an {@code assertion}, retrying until {@code timeout} is reached.
     */
    private static void eventually(String description, Callable<Boolean> assertion)
            throws Exception {
        SESSION_LIFECYCLE_TIMEOUT.run(description, assertion);
    }

    public SessionLifecycleTest() {
        super(new UiBot(SESSION_LIFECYCLE_TIMEOUT));
    }

    /**
     * Prevents the screen to rotate by itself
     */
    @Before
    public void disableAutoRotation() throws Exception {
        Helper.disableAutoRotation(mUiBot);
    }

    /**
     * Allows the screen to rotate by itself
     */
    @After
    public void allowAutoRotation() {
        Helper.allowAutoRotation();
    }

    @After
    public void finishLoginActivityOnAnotherProcess() throws Exception {
        runShellCommand(
                "am broadcast --receiver-foreground -n android.autofillservice.cts/.testcore"
                        + ".OutOfProcessLoginActivityFinisherReceiver");
        mUiBot.assertGoneByRelativeId(ID_USERNAME, Timeouts.ACTIVITY_RESURRECTION);

        if (!OutOfProcessLoginActivity.hasInstance()) {
            Log.v(TAG, "@After: Not waiting for oop activity to be destroyed");
            return;
        }
        // Waiting for activity to be destroyed (destroy marker appears)
        eventually("getDestroyedMarker()", () -> {
            return getDestroyedMarker(getContext()).exists();
        });
    }

    private void killOfProcessLoginActivityProcess() throws Exception {
        // Waiting for activity to stop (stop marker appears)
        eventually("getStoppedMarker()", () -> {
            return getStoppedMarker(getContext()).exists();
        });

        // onStop might not be finished, hence wait more
        SystemClock.sleep(WAIT_ACTIVITY_MS);

        // Kill activity that is in the background
        runShellCommand("am broadcast --receiver-foreground "
                + "-n android.autofillservice.cts/.testcore.SelfDestructReceiver");
    }

    private void startAndWaitExternalActivity() throws Exception {
        final Intent outOfProcessAcvitityStartIntent = new Intent(getContext(),
                OutOfProcessLoginActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getStartedMarker(getContext()).delete();
        getContext().startActivity(outOfProcessAcvitityStartIntent);
        eventually("getStartedMarker()", () -> {
            return getStartedMarker(getContext()).exists();
        });
        getStartedMarker(getContext()).delete();
        // Even if we wait the activity started, UiObject still fails. Have to wait a little bit.
        SystemClock.sleep(WAIT_ACTIVITY_MS);

        mUiBot.assertShownByRelativeId(ID_USERNAME);
    }

    @Test
    public void testDatasetAuthResponseWhileAutofilledAppIsLifecycled() throws Exception {
        assumeTrue("Rotation is supported", Helper.isRotationSupported(mContext));
        final ActivityManager activityManager = (ActivityManager) getContext()
                .getSystemService(Context.ACTIVITY_SERVICE);
        assumeFalse(activityManager.isLowRamDevice());

        // Set service.
        enableService();

        try {

            // Start activity that is autofilled in a separate process so it can be killed
            startAndWaitExternalActivity();

            // Set expectations.
            final Bundle extras = new Bundle();
            extras.putString("numbers", "4815162342");

            // Create the authentication intent (launching a full screen activity)
            IntentSender authentication = PendingIntent.getActivity(getContext(), 0,
                    new Intent(getContext(), ManualAuthenticationActivity.class),
                    PendingIntent.FLAG_MUTABLE).getIntentSender();

            // Prepare the authenticated response
            ManualAuthenticationActivity.setResponse(new CannedFillResponse.Builder()
                    .addDataset(new CannedFillResponse.CannedDataset.Builder()
                            .setField(ID_USERNAME, AutofillValue.forText("autofilled username"))
                            .setPresentation(createPresentation("dataset")).build())
                    .setRequiredSavableIds(SAVE_DATA_TYPE_PASSWORD, ID_USERNAME, ID_PASSWORD)
                    .setExtras(extras).build());

            CannedFillResponse response = new CannedFillResponse.Builder()
                    .setAuthentication(authentication, ID_USERNAME, ID_PASSWORD)
                    .setPresentation(createPresentation("authenticate"))
                    .build();
            sReplier.addResponse(response);

            // Trigger autofill on username
            mUiBot.selectByRelativeId(ID_USERNAME);

            // Wait for fill request to be processed
            sReplier.getNextFillRequest();

            // Wait until authentication is shown
            mUiBot.assertDatasets("authenticate");

            // Change orientation which triggers a destroy -> create in the app as the activity
            // cannot deal with such situations
            mUiBot.setScreenOrientation(LANDSCAPE);
            mUiBot.setScreenOrientation(PORTRAIT);

            // Wait context and Views being recreated in rotation
            mUiBot.assertShownByRelativeId(ID_USERNAME);

            // Delete stopped marker
            getStoppedMarker(getContext()).delete();

            // Authenticate
            mUiBot.selectDataset("authenticate");

            // Kill activity that is in the background
            killOfProcessLoginActivityProcess();

            // Change orientation which triggers a destroy -> create in the app as the activity
            // cannot deal with such situations
            mUiBot.setScreenOrientation(PORTRAIT);

            // Approve authentication
            mUiBot.selectByRelativeId(ID_BUTTON);

            // Wait for dataset to be shown
            mUiBot.assertDatasets("dataset");

            // Change orientation which triggers a destroy -> create in the app as the activity
            // cannot deal with such situations
            mUiBot.setScreenOrientation(LANDSCAPE);

            // Select dataset
            mUiBot.selectDataset("dataset");

            // Check the results.
            eventually("getTextById(" + ID_USERNAME + ")", () -> {
                return mUiBot.getTextByRelativeId(ID_USERNAME).equals("autofilled username");
            });

            // Set password
            mUiBot.setTextByRelativeId(ID_PASSWORD, "new password");

            // Login
            mUiBot.selectByRelativeId(ID_LOGIN);

            // Wait for save UI to be shown
            mUiBot.assertSaveShowing(SAVE_DATA_TYPE_PASSWORD);

            // Change orientation to make sure save UI can handle this
            mUiBot.setScreenOrientation(PORTRAIT);

            // Tap "Save".
            mUiBot.saveForAutofill(true, SAVE_DATA_TYPE_PASSWORD);

            // Get save request
            InstrumentedAutoFillService.SaveRequest saveRequest = sReplier.getNextSaveRequest();
            assertWithMessage("onSave() not called").that(saveRequest).isNotNull();

            // Make sure data is correctly saved
            final AssistStructure.ViewNode username = findNodeByResourceId(saveRequest.structure,
                    ID_USERNAME);
            assertTextAndValue(username, "autofilled username");
            final AssistStructure.ViewNode password = findNodeByResourceId(saveRequest.structure,
                    ID_PASSWORD);
            assertTextAndValue(password, "new password");

            // Make sure extras were passed back on onSave()
            assertThat(saveRequest.data).isNotNull();
            final String extraValue = saveRequest.data.getString("numbers");
            assertWithMessage("extras not passed on save").that(extraValue).isEqualTo("4815162342");
        } finally {
            mUiBot.resetScreenResolution();
        }
    }

    @Test
    public void testAuthCanceledWhileAutofilledAppIsLifecycled() throws Exception {
        // Set service.
        enableService();

        // Start activity that is autofilled in a separate process so it can be killed
        startAndWaitExternalActivity();

        // Create the authentication intent (launching a full screen activity)
        IntentSender authentication = PendingIntent.getActivity(getContext(), 0,
                new Intent(getContext(), ManualAuthenticationActivity.class),
                PendingIntent.FLAG_IMMUTABLE).getIntentSender();

        CannedFillResponse response = new CannedFillResponse.Builder()
                .setAuthentication(authentication, ID_USERNAME, ID_PASSWORD)
                .setPresentation(createPresentation("authenticate"))
                .build();
        sReplier.addResponse(response);

        // Trigger autofill on username
        mUiBot.selectByRelativeId(ID_USERNAME);

        // Wait for fill request to be processed
        sReplier.getNextFillRequest();

        // Wait until authentication is shown
        mUiBot.assertDatasets("authenticate");

        // Delete stopped marker
        getStoppedMarker(getContext()).delete();

        // Authenticate
        mUiBot.selectDataset("authenticate");

        // Kill activity that is in the background
        killOfProcessLoginActivityProcess();

        // Set expectations.
        sReplier.addResponse(
                new CannedFillResponse.Builder()
                        .setAuthentication(authentication, ID_USERNAME, ID_PASSWORD)
                        .setPresentation(createPresentation("authenticate2"))
                        .build());

        // Cancel authentication activity
        mUiBot.pressBack();

        // Wait for fill request to be processed
        mUiBot.waitForIdle();
        sReplier.getNextFillRequest();

        // Authentication should still be shown
        mUiBot.assertDatasets("authenticate2");
    }

    @Test
    public void testDatasetVisibleWhileAutofilledAppIsLifecycled() throws Exception {
        // Set service.
        enableService();

        // Start activity that is autofilled in a separate process so it can be killed
        startAndWaitExternalActivity();

        CannedFillResponse response = new CannedFillResponse.Builder()
                .addDataset(new CannedFillResponse.CannedDataset.Builder(
                        createPresentation("dataset"))
                                .setField(ID_USERNAME, "filled").build())
                .build();
        sReplier.addResponse(response);

        // Trigger autofill on username
        mUiBot.selectByRelativeId(ID_USERNAME);

        // Wait for fill request to be processed
        sReplier.getNextFillRequest();

        // Wait until dataset is shown
        mUiBot.assertDatasets("dataset");

        // Delete stopped marker
        getStoppedMarker(getContext()).delete();

        // Start an activity on top of the autofilled activity
        Intent intent = new Intent(getContext(), EmptyActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        getContext().startActivity(intent);

        // Kill activity that is in the background
        killOfProcessLoginActivityProcess();

        // Add response for back to the first activity
        sReplier.addResponse(
                new CannedFillResponse.Builder()
                        .addDataset(new CannedFillResponse.CannedDataset.Builder(
                                createPresentation("dataset2"))
                                        .setField(ID_USERNAME, "filled").build())
                        .build());

        // Cancel activity on top
        mUiBot.pressBack();

        // Wait for fill request to be processed
        mUiBot.waitForIdle();
        sReplier.getNextFillRequest();

        // Dataset should still be shown
        mUiBot.assertDatasets("dataset2");
    }

    @Test
    public void testAutofillNestedActivitiesWhileAutofilledAppIsLifecycled() throws Exception {
        // Set service.
        enableService();

        // Start activity that is autofilled in a separate process so it can be killed
        startAndWaitExternalActivity();

        // Prepare response for first activity
        CannedFillResponse response = new CannedFillResponse.Builder()
                .addDataset(new CannedFillResponse.CannedDataset.Builder(
                        createPresentation("dataset1"))
                                .setField(ID_USERNAME, "filled").build())
                .build();
        sReplier.addResponse(response);

        // Trigger autofill on username
        mUiBot.selectByRelativeId(ID_USERNAME);

        // Wait for fill request to be processed
        sReplier.getNextFillRequest();

        // Wait until dataset1 is shown
        mUiBot.assertDatasets("dataset1");

        // Delete stopped marker
        getStoppedMarker(getContext()).delete();

        // Prepare response for nested activity
        response = new CannedFillResponse.Builder()
                .addDataset(new CannedFillResponse.CannedDataset.Builder(
                        createPresentation("dataset2"))
                                .setField(ID_USERNAME, "filled").build())
                .build();
        sReplier.addResponse(response);

        // Start nested login activity
        Intent intent = new Intent(getContext(), LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getContext().startActivity(intent);

        // Kill activity that is in the background
        killOfProcessLoginActivityProcess();

        // Trigger autofill on username in nested activity
        mUiBot.selectByRelativeId(ID_USERNAME);

        // Wait for fill request to be processed
        sReplier.getNextFillRequest();

        // Wait until dataset in nested activity is shown
        mUiBot.assertDatasets("dataset2");

        // Set expectations for back to the first activity
        sReplier.addResponse(
                new CannedFillResponse.Builder()
                        .addDataset(new CannedFillResponse.CannedDataset.Builder(
                                createPresentation("dataset3"))
                                        .setField(ID_USERNAME, "filled").build())
                        .build());

        boolean isMockImeAvailable = sMockImeSessionRule.getMockImeSession() != null;
        if (!isMockImeAvailable) {
            // If Mock IME cannot be installed,
            // it works fine for portrait but for the platforms that the default orientation
            // is landscape, (e.g. automotive.)
            // the ID_CANCEL button may not be visible depending on the height of the IME.
            LoginActivity loginActivity = LoginActivity.getCurrentActivity();
            loginActivity.onCancel(v -> {
                    v.getParent().requestChildFocus(v, v);
            });
        }

        // Tap "Cancel".
        mUiBot.selectByRelativeId(ID_CANCEL);

        // Wait for fill request to be processed
        mUiBot.waitForIdle();
        sReplier.getNextFillRequest();

        // Dataset should still be shown
        mUiBot.assertDatasets("dataset3");
    }

    @Test
    public void testDatasetGoesAwayWhenAutofilledAppIsKilled() throws Exception {
        // Set service.
        enableService();

        // Start activity that is autofilled in a separate process so it can be killed
        startAndWaitExternalActivity();

        final CannedFillResponse response = new CannedFillResponse.Builder()
                .addDataset(new CannedFillResponse.CannedDataset.Builder(
                        createPresentation("dataset"))
                                .setField(ID_USERNAME, "filled").build())
                .build();
        sReplier.addResponse(response);

        // Trigger autofill on username
        mUiBot.selectByRelativeId(ID_USERNAME);

        // Wait for fill request to be processed
        sReplier.getNextFillRequest();

        // Wait until dataset is shown
        mUiBot.assertDatasets("dataset");

        // Kill activity
        killOfProcessLoginActivityProcess();

        // Make sure dataset is not shown anymore
        mUiBot.assertNoDatasetsEver();

        // Restart activity an make sure the dataset is still not shown
        startAndWaitExternalActivity();
        mUiBot.assertNoDatasets();
    }

    @Test
    public void testSaveRemainsWhenAutofilledAppIsKilled() throws Exception {
        // Set service.
        enableService();

        // Start activity that is autofilled in a separate process so it can be killed
        startAndWaitExternalActivity();

        final CannedFillResponse response = new CannedFillResponse.Builder()
                .setRequiredSavableIds(SAVE_DATA_TYPE_USERNAME, ID_USERNAME)
                .build();
        sReplier.addResponse(response);

        // Trigger autofill on username
        mUiBot.selectByRelativeId(ID_USERNAME);

        // Wait for fill request to be processed
        sReplier.getNextFillRequest();

        // Wait until dataset is shown
        mUiBot.assertNoDatasetsEver();

        // Trigger save
        mUiBot.setTextByRelativeId(ID_USERNAME, "dude");

        // It works fine for portrait but for the platforms that the default orientation
        // is landscape, e.g. automotive. Depending on the height of the IME, the ID_LOGIN
        // button may not be visible.
        // In order to avoid that,
        // generate back key event to hide IME before pressing ID_LOGIN button.
        mUiBot.pressBack();

        mUiBot.selectByRelativeId(ID_LOGIN);
        mUiBot.assertSaveShowing(SAVE_DATA_TYPE_USERNAME);

        // Kill activity
        killOfProcessLoginActivityProcess();

        // Make sure save is still showing
        final UiObject2 saveSnackBar = mUiBot.assertSaveShowing(SAVE_DATA_TYPE_USERNAME);

        mUiBot.saveForAutofill(saveSnackBar, true);

        final InstrumentedAutoFillService.SaveRequest saveRequest = sReplier.getNextSaveRequest();

        // Make sure data is correctly saved
        final AssistStructure.ViewNode username = findNodeByResourceId(saveRequest.structure,
                ID_USERNAME);
        assertTextAndValue(username, "dude");
    }
}