• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.autofillservice.cts.commontests;
18 
19 import static android.autofillservice.cts.testcore.Helper.DEVICE_CONFIG_AUTOFILL_DIALOG_HINTS;
20 import static android.autofillservice.cts.testcore.Helper.getContext;
21 import static android.autofillservice.cts.testcore.InstrumentedAutoFillService.SERVICE_NAME;
22 import static android.autofillservice.cts.testcore.InstrumentedAutoFillService.SERVICE_CLASS;
23 import static android.content.Context.CLIPBOARD_SERVICE;
24 
25 import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
26 
27 import static com.android.compatibility.common.util.ShellUtils.runShellCommand;
28 
29 import static org.junit.Assume.assumeFalse;
30 
31 import android.app.PendingIntent;
32 import android.autofillservice.cts.R;
33 import android.autofillservice.cts.activities.AbstractAutoFillActivity;
34 import android.autofillservice.cts.activities.AugmentedAuthActivity;
35 import android.autofillservice.cts.activities.AuthenticationActivity;
36 import android.autofillservice.cts.activities.LoginActivity;
37 import android.autofillservice.cts.activities.LoginImportantForCredentialManagerActivity;
38 import android.autofillservice.cts.activities.LoginMixedImportantForCredentialManagerActivity;
39 import android.autofillservice.cts.activities.PreSimpleSaveActivity;
40 import android.autofillservice.cts.activities.SimpleSaveActivity;
41 import android.autofillservice.cts.testcore.AutofillActivityTestRule;
42 import android.autofillservice.cts.testcore.AutofillLoggingTestRule;
43 import android.autofillservice.cts.testcore.AutofillTestWatcher;
44 import android.autofillservice.cts.testcore.Helper;
45 import android.autofillservice.cts.testcore.InlineUiBot;
46 import android.autofillservice.cts.testcore.InstrumentedAutoFillService;
47 import android.autofillservice.cts.testcore.InstrumentedAutoFillService.Replier;
48 import android.autofillservice.cts.testcore.RepeatRule;
49 import android.autofillservice.cts.testcore.UiBot;
50 import android.content.ClipboardManager;
51 import android.content.Context;
52 import android.content.Intent;
53 import android.content.pm.PackageManager;
54 import android.platform.test.flag.junit.CheckFlagsRule;
55 import android.platform.test.flag.junit.DeviceFlagsValueProvider;
56 import android.provider.DeviceConfig;
57 import android.provider.Settings;
58 import android.service.autofill.InlinePresentation;
59 import android.util.Log;
60 import android.view.autofill.AutofillFeatureFlags;
61 import android.view.autofill.AutofillManager;
62 import android.widget.RemoteViews;
63 
64 import androidx.annotation.NonNull;
65 import androidx.test.InstrumentationRegistry;
66 import androidx.test.ext.junit.runners.AndroidJUnit4;
67 
68 import com.android.compatibility.common.util.DeviceConfigStateChangerRule;
69 import com.android.compatibility.common.util.DisableAnimationRule;
70 import com.android.compatibility.common.util.RequiredFeatureRule;
71 import com.android.compatibility.common.util.RetryRule;
72 import com.android.compatibility.common.util.SafeCleanerRule;
73 import com.android.compatibility.common.util.SettingsStateKeeperRule;
74 import com.android.compatibility.common.util.TestNameUtils;
75 import com.android.cts.mockime.ImeSettings;
76 import com.android.cts.mockime.MockImeSessionRule;
77 
78 import org.junit.After;
79 import org.junit.AfterClass;
80 import org.junit.Before;
81 import org.junit.BeforeClass;
82 import org.junit.ClassRule;
83 import org.junit.Rule;
84 import org.junit.rules.RuleChain;
85 import org.junit.rules.TestRule;
86 import org.junit.runner.Description;
87 import org.junit.runner.RunWith;
88 import org.junit.runners.model.Statement;
89 
90 /**
91  * Placeholder for the base class for all integration tests:
92  *
93  * <ul>
94  *   <li>{@link AutoActivityLaunch}
95  *   <li>{@link ManualActivityLaunch}
96  * </ul>
97  *
98  * <p>These classes provide the common infrastructure such as:
99  *
100  * <ul>
101  *   <li>Preserving the autofill service settings.
102  *   <li>Cleaning up test state.
103  *   <li>Wrapping the test under autofill-specific test rules.
104  *   <li>Launching the activity used by the test.
105  * </ul>
106  */
107 public final class AutoFillServiceTestCase {
108 
109     /**
110      * Base class for all test cases that use an {@link AutofillActivityTestRule} to
111      * launch the activity.
112      */
113     // Must be public because of @ClassRule
114     public abstract static class AutoActivityLaunch<A extends AbstractAutoFillActivity>
115             extends BaseTestCase {
116 
117         /**
118          * Returns if inline suggestion is enabled.
119          */
isInlineMode()120         protected boolean isInlineMode() {
121             return false;
122         }
123 
getInlineUiBot()124         protected static InlineUiBot getInlineUiBot() {
125             return new InlineUiBot(getContext());
126         }
127 
getDropdownUiBot()128         protected static UiBot getDropdownUiBot() {
129             return sDefaultUiBot;
130         }
131 
132         @ClassRule
133         public static final SettingsStateKeeperRule sPublicServiceSettingsKeeper =
134                 sTheRealServiceSettingsKeeper;
135 
AutoActivityLaunch()136         protected AutoActivityLaunch() {
137             super(sDefaultUiBot);
138         }
AutoActivityLaunch(UiBot uiBot)139         protected AutoActivityLaunch(UiBot uiBot) {
140             super(uiBot);
141         }
142 
143         @Override
getMainTestRule()144         protected TestRule getMainTestRule() {
145             // Tries to set the orientation, noop if nothing happens
146             getDropdownUiBot().maybeSetScreenOrientation(UiBot.PORTRAIT);
147             return getActivityRule();
148         }
149 
150         /**
151          * Gets the rule to launch the main activity for this test.
152          *
153          * <p><b>Note: </b>the rule must be either lazily generated or a static singleton, otherwise
154          * this method could return {@code null} when the rule chain that uses it is constructed.
155          *
156          */
getActivityRule()157         protected abstract @NonNull AutofillActivityTestRule<A> getActivityRule();
158 
launchActivity(@onNull Intent intent)159         protected @NonNull A launchActivity(@NonNull Intent intent) {
160             return getActivityRule().launchActivity(intent);
161         }
162 
getActivity()163         protected @NonNull A getActivity() {
164             return getActivityRule().getActivity();
165         }
166     }
167 
168     /**
169      * Base class for all test cases that don't require an {@link AutofillActivityTestRule}.
170      */
171     // Must be public because of @ClassRule
172     public abstract static class ManualActivityLaunch extends BaseTestCase {
173 
174         @ClassRule
175         public static final SettingsStateKeeperRule sPublicServiceSettingsKeeper =
176                 sTheRealServiceSettingsKeeper;
177 
ManualActivityLaunch()178         protected ManualActivityLaunch() {
179             this(sDefaultUiBot);
180         }
181 
ManualActivityLaunch(@onNull UiBot uiBot)182         protected ManualActivityLaunch(@NonNull UiBot uiBot) {
183             super(uiBot);
184         }
185 
186         @Override
getMainTestRule()187         protected TestRule getMainTestRule() {
188             // TODO: create a NoOpTestRule on common code
189             return new TestRule() {
190 
191                 @Override
192                 public Statement apply(Statement base, Description description) {
193                     // Returns a no-op statements
194                     return new Statement() {
195                         @Override
196                         public void evaluate() throws Throwable {
197                             base.evaluate();
198                         }
199                     };
200                 }
201             };
202         }
203 
204         protected SimpleSaveActivity startSimpleSaveActivity() throws Exception {
205             final Intent intent = new Intent(mContext, SimpleSaveActivity.class)
206                     .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
207             mContext.startActivity(intent);
208             mUiBot.assertShownByRelativeId(SimpleSaveActivity.ID_LABEL);
209             return SimpleSaveActivity.getInstance();
210         }
211 
212         protected PreSimpleSaveActivity startPreSimpleSaveActivity() throws Exception {
213             final Intent intent = new Intent(mContext, PreSimpleSaveActivity.class)
214                     .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
215             mContext.startActivity(intent);
216             mUiBot.assertShownByRelativeId(PreSimpleSaveActivity.ID_PRE_LABEL);
217             return PreSimpleSaveActivity.getInstance();
218         }
219 
220         protected LoginActivity startLoginActivity() throws Exception {
221             final Intent intent = new Intent(mContext, LoginActivity.class)
222                     .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
223             mContext.startActivity(intent);
224             mUiBot.waitForIdleSync();
225             mUiBot.assertShownByRelativeId(Helper.ID_USERNAME_LABEL);
226             return LoginActivity.getCurrentActivity();
227         }
228 
229         protected LoginImportantForCredentialManagerActivity
230                     startLoginImportantForCredentialManagerActivity(boolean useAutofillHint)
231                 throws Exception {
232             final Intent intent =
233                     new Intent(mContext, LoginImportantForCredentialManagerActivity.class)
234                         .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
235                         .putExtra("useAutofillHint", useAutofillHint);
236             mContext.startActivity(intent);
237             mUiBot.assertShownByRelativeId(Helper.ID_USERNAME_LABEL);
238             return LoginImportantForCredentialManagerActivity.getCurrentActivity();
239         }
240 
241         protected LoginMixedImportantForCredentialManagerActivity
242                 startLoginMixedImportantForCredentialManagerActivity(boolean useAutofillHInt)
243                 throws Exception {
244             final Intent intent =
245                     new Intent(mContext, LoginMixedImportantForCredentialManagerActivity.class)
246                         .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
247                         .putExtra("useAutofillHint", useAutofillHInt);
248             mContext.startActivity(intent);
249             mUiBot.assertShownByRelativeId(Helper.ID_USERNAME_LABEL);
250             return LoginMixedImportantForCredentialManagerActivity.getCurrentActivity();
251         }
252     }
253 
254     @RunWith(AndroidJUnit4.class)
255     // Must be public because of @ClassRule
256     public abstract static class BaseTestCase {
257 
258         private static final String TAG = "AutoFillServiceTestCase";
259 
260         protected static final Replier sReplier = InstrumentedAutoFillService.getReplier();
261 
262         protected static final Context sContext = getInstrumentation().getTargetContext();
263 
264         // Hack because JUnit requires that @ClassRule instance belong to a public class.
265         protected static final SettingsStateKeeperRule sTheRealServiceSettingsKeeper =
266                 new SettingsStateKeeperRule(sContext, Settings.Secure.AUTOFILL_SERVICE) {
267             @Override
268             protected void preEvaluate(Description description) {
269                 TestNameUtils.setCurrentTestClass(description.getClassName());
270             }
271 
272             @Override
273             protected void postEvaluate(Description description) {
274                 TestNameUtils.setCurrentTestClass(null);
275             }
276         };
277 
278         public static final MockImeSessionRule sMockImeSessionRule = new MockImeSessionRule(
279                 InstrumentationRegistry.getTargetContext(),
280                 InstrumentationRegistry.getInstrumentation().getUiAutomation(),
281                 new ImeSettings.Builder().setInlineSuggestionsEnabled(true)
282                         .setInlineSuggestionViewContentDesc(InlineUiBot.SUGGESTION_STRIP_DESC));
283 
284         private final AutofillTestWatcher mTestWatcher = new AutofillTestWatcher();
285 
286         private final RetryRule mRetryRule =
287                 new RetryRule(getNumberRetries(), () -> {
288                     // Between testing and retries, clean all launched activities to avoid
289                     // exception:
290                     //     Could not launch intent Intent { ... } within 45 seconds.
291                     mTestWatcher.cleanAllActivities();
292                     cleanAllActivities();
293                 });
294 
295         private final RepeatRule mRepeatRule =
296                 new RepeatRule(
297                         () -> {
298                             // Between testing and retries, clean all launched activities to avoid
299                             // exception:
300                             //     Could not launch intent Intent { ... } within 45 seconds.
301                             mTestWatcher.cleanAllActivities();
302                             cleanAllActivities();
303                         });
304 
305         @Rule
306         public final CheckFlagsRule mCheckFlagsRule =
307                 DeviceFlagsValueProvider.createCheckFlagsRule();
308 
309         private final AutofillLoggingTestRule mLoggingRule = new AutofillLoggingTestRule(TAG);
310 
311         protected final SafeCleanerRule mSafeCleanerRule = new SafeCleanerRule()
312                 .setDumper(mLoggingRule)
313                 .run(() -> sReplier.assertNoUnhandledFillRequests())
314                 .run(() -> sReplier.assertNoUnhandledSaveRequests())
315                 .add(() -> {
316                     return sReplier.getExceptions();
317                 });
318 
319         /**
320          * Disable animation for UiAutomator because animation will cause the UiAutomator
321          * got a wrong position and then tests failed due to click on the wrong position.
322          *
323          * This is annotated as @ClassRule instead of @Rule, to save time of disabling and
324          * re-enabling animation for each test method.
325          */
326         @ClassRule
327         public static DisableAnimationRule sDisableAnimationRule = new DisableAnimationRule();
328 
329         @Rule
330         public final RuleChain mLookAllTheseRules = RuleChain
331                 //
332                 // requiredFeatureRule should be first so the test can be skipped right away
333                 .outerRule(getRequiredFeaturesRule())
334                 //
335                 // mTestWatcher should always be one the first rules, as it defines the name of the
336                 // test being ran and finishes dangling activities at the end
337                 .around(mTestWatcher)
338                 //
339                 // sMockImeSessionRule make sure MockImeSession.create() is used to launch mock IME
340                 .around(sMockImeSessionRule)
341                 //
342                 // mLoggingRule wraps the test but doesn't interfere with it
343                 .around(mLoggingRule)
344                 //
345                 // mSafeCleanerRule will catch errors
346                 .around(mSafeCleanerRule)
347                 //
348                 // mRetryRule should be closest to the main test as possible
349                 .around(mRetryRule)
350                 // mCheckFlagsRule checks for required flags for a test
351                 .around(mCheckFlagsRule)
352 
353                 // mRepeatRule re-runs the test a set number of times
354                 .around(mRepeatRule)
355                 //
356                 // Augmented Autofill should be disabled by default
357                 .around(new DeviceConfigStateChangerRule(sContext, DeviceConfig.NAMESPACE_AUTOFILL,
358                         AutofillFeatureFlags.DEVICE_CONFIG_AUTOFILL_SMART_SUGGESTION_SUPPORTED_MODES,
359                         Integer.toString(getSmartSuggestionMode())))
360                 //
361                 // Fill Dialog should be disabled by default
362                 .around(new DeviceConfigStateChangerRule(sContext, DeviceConfig.NAMESPACE_AUTOFILL,
363                         AutofillFeatureFlags.DEVICE_CONFIG_AUTOFILL_DIALOG_ENABLED,
364                         Boolean.toString(false)))
365                 //
366                 // Hints list of Fill Dialog should be empty by default
367                 .around(new DeviceConfigStateChangerRule(sContext, DeviceConfig.NAMESPACE_AUTOFILL,
368                         DEVICE_CONFIG_AUTOFILL_DIALOG_HINTS,
369                         ""))
370                 //
371                 // Fill Dialog Improvements should be disabled by default
372                 .around(new DeviceConfigStateChangerRule(sContext, DeviceConfig.NAMESPACE_AUTOFILL,
373                         "improve_fill_dialog",
374                         Boolean.toString(false)))
375 
376                 //
377                 // CredentialManager-Autofill integration enabled by default
378                 .around(new DeviceConfigStateChangerRule(sContext, DeviceConfig.NAMESPACE_AUTOFILL,
379                         AutofillFeatureFlags.DEVICE_CONFIG_AUTOFILL_CREDENTIAL_MANAGER_ENABLED,
380                         Boolean.toString(true)))
381                 .around(new DeviceConfigStateChangerRule(sContext, DeviceConfig.NAMESPACE_AUTOFILL,
382                         AutofillFeatureFlags.DEVICE_CONFIG_AUTOFILL_CREDENTIAL_MANAGER_IGNORE_VIEWS,
383                         Boolean.toString(true)))
384 
385                 //
386                 // PCC Detection should be off by default
387                 .around(new DeviceConfigStateChangerRule(sContext, DeviceConfig.NAMESPACE_AUTOFILL,
388                         AutofillFeatureFlags.DEVICE_CONFIG_AUTOFILL_PCC_CLASSIFICATION_ENABLED,
389                         Boolean.toString(false)))
390 
391                 //
392                 // PCC Detection Hints should be empty by default
393                 .around(new DeviceConfigStateChangerRule(sContext, DeviceConfig.NAMESPACE_AUTOFILL,
394                         AutofillFeatureFlags.DEVICE_CONFIG_AUTOFILL_PCC_FEATURE_PROVIDER_HINTS,
395                         ""))
396 
397 
398                 //
399                 // AFAA should be off by default
400                 .around(new DeviceConfigStateChangerRule(sContext, DeviceConfig.NAMESPACE_AUTOFILL,
401                             AutofillFeatureFlags.
402                                 DEVICE_CONFIG_TRIGGER_FILL_REQUEST_ON_UNIMPORTANT_VIEW,
403                             Boolean.toString(false)))
404 
405                 .around(new DeviceConfigStateChangerRule(sContext, DeviceConfig.NAMESPACE_AUTOFILL,
406                             "trigger_fill_request_on_filtered_important_views",
407                             Boolean.toString(false)))
408 
409                 .around(new DeviceConfigStateChangerRule(sContext, DeviceConfig.NAMESPACE_AUTOFILL,
410                             "include_all_autofill_type_not_none_views_in_assist_structure",
411                             Boolean.toString(false)))
412 
413                 //
414                 // Relayout fix should be on by default
415                 .around(new DeviceConfigStateChangerRule(sContext, DeviceConfig.NAMESPACE_AUTOFILL,
416                         "enable_relayout", Boolean.toString(true)))
417 
418 
419                 //
420                 // Max input size to provide autofill suggestion should be 3
421                 .around(new DeviceConfigStateChangerRule(sContext, DeviceConfig.NAMESPACE_AUTOFILL,
422                             "max_input_length_for_autofill",
423                             Integer.toString(3)))
424 
425                 //
426                 // Fill fields from current session only should be on by default
427                 .around(new DeviceConfigStateChangerRule(sContext, DeviceConfig.NAMESPACE_AUTOFILL,
428                         "fill_fields_from_current_session_only", Boolean.toString(true)))
429 
430                 //
431                 // Ignore view state reset to empty should be on by default
432                 .around(new DeviceConfigStateChangerRule(sContext, DeviceConfig.NAMESPACE_AUTOFILL,
433                         "ignore_view_state_reset_to_empty", Boolean.toString(true)))
434 
435                 //
436                 // Include invisible view group in assist structure should be on by default
437                 .around(new DeviceConfigStateChangerRule(sContext, DeviceConfig.NAMESPACE_AUTOFILL,
438                         "include_invisible_view_group_in_assist_structure", Boolean.toString(true)))
439 
440                 //
441                 // Finally, let subclasses add their own rules (like ActivityTestRule)
442                 .around(getMainTestRule());
443 
444 
445         protected final Context mContext = sContext;
446         protected final String mPackageName;
447         protected final UiBot mUiBot;
448 
449         protected static final RuleChain sRequiredFeaturesRule = RuleChain
450                 .outerRule(new RequiredFeatureRule(PackageManager.FEATURE_AUTOFILL))
451                 .around(new RequiredFeatureRule(PackageManager.FEATURE_INPUT_METHODS));
452 
453         public BaseTestCase() {
454             mPackageName = mContext.getPackageName();
455             mUiBot = sDefaultUiBot;
456         }
457 
458         private BaseTestCase(@NonNull UiBot uiBot) {
459             mPackageName = mContext.getPackageName();
460             mUiBot = uiBot;
461             mUiBot.reset();
462         }
463 
464         protected int getSmartSuggestionMode() {
465             return AutofillManager.FLAG_SMART_SUGGESTION_OFF;
466         }
467 
468         /**
469          * Gets how many times a test should be retried.
470          *
471          * @return {@code 1} by default, unless overridden by subclasses or by a global settings
472          * named {@code CLASS_NAME + #getNumberRetries} or
473          * {@code CtsAutoFillServiceTestCases#getNumberRetries} (the former having a higher
474          * priority).
475          */
476         protected int getNumberRetries() {
477             final String localProp = getClass().getName() + "#getNumberRetries";
478             final Integer localValue = getNumberRetries(localProp);
479             if (localValue != null) return localValue.intValue();
480 
481             final String globalProp = "CtsAutoFillServiceTestCases#getNumberRetries";
482             final Integer globalValue = getNumberRetries(globalProp);
483             if (globalValue != null) return globalValue.intValue();
484 
485             return 1;
486         }
487 
488         private Integer getNumberRetries(String prop) {
489             final String value = Settings.Global.getString(sContext.getContentResolver(), prop);
490             if (value != null) {
491                 Log.i(TAG, "getNumberRetries(): overriding to " + value + " because of '" + prop
492                         + "' global setting");
493                 try {
494                     return Integer.parseInt(value);
495                 } catch (Exception e) {
496                     Log.w(TAG, "error parsing property '" + prop + "'='" + value + "'", e);
497                 }
498             }
499             return null;
500         }
501 
502         /**
503          * Gets a rule that defines which features must be present for this test to run.
504          *
505          * <p>By default it returns a rule that requires {@link PackageManager#FEATURE_AUTOFILL},
506          * but subclass can override to be more specific.
507          */
508         @NonNull
509         protected TestRule getRequiredFeaturesRule() {
510             return sRequiredFeaturesRule;
511         }
512 
513         /**
514          * Gets the test-specific {@link Rule @Rule}.
515          *
516          * <p>Sub-class <b>MUST</b> override this method instead of annotation their own rules,
517          * so the order is preserved.
518          *
519          */
520         @NonNull
521         protected abstract TestRule getMainTestRule();
522 
523         @BeforeClass
524         public static void disableDefaultAugmentedService() {
525             Log.v(TAG, "@BeforeClass: disableDefaultAugmentedService()");
526             Helper.setDefaultAugmentedAutofillServiceEnabled(false);
527         }
528 
529         @AfterClass
530         public static void enableDefaultAugmentedService() {
531             Log.v(TAG, "@AfterClass: enableDefaultAugmentedService()");
532             Helper.setDefaultAugmentedAutofillServiceEnabled(true);
533         }
534 
535         @Before
536         public void prepareDevice() throws Exception {
537             Log.v(TAG, "@Before: prepareDevice()");
538 
539             // Unlock screen.
540             runShellCommand("input keyevent KEYCODE_WAKEUP");
541 
542             // Dismiss keyguard, in case it's set as "Swipe to unlock".
543             runShellCommand("wm dismiss-keyguard");
544 
545             // Collapse notifications.
546             runShellCommand("cmd statusbar collapse");
547 
548             assumeFalse("Device is half-folded",
549                     Helper.isDeviceInState(mContext, Helper.DeviceStateEnum.HALF_FOLDED));
550 
551             assumeFalse("Device is TV", Helper.isTv(mContext));
552 
553             // Set orientation as portrait, otherwise some tests might fail due to elements not
554             // fitting in, IME orientation, etc...
555             mUiBot.maybeSetScreenOrientation(UiBot.PORTRAIT);
556 
557             // Clear Clipboard
558             // TODO(b/117768051): remove try/catch once fixed
559             try {
560                 ((ClipboardManager) mContext.getSystemService(CLIPBOARD_SERVICE))
561                     .clearPrimaryClip();
562             } catch (Exception e) {
563                 Log.e(TAG, "Ignoring exception clearing clipboard", e);
564             }
565         }
566 
567         @Before
568         public void preTestCleanup() {
569             Log.v(TAG, "@Before: preTestCleanup()");
570 
571             prepareServicePreTest();
572 
573             AuthenticationActivity.resetStaticState();
574             AugmentedAuthActivity.resetStaticState();
575             sReplier.reset();
576 
577             InstrumentedAutoFillService.startTest();
578         }
579 
580         @After
581         public void postTestCleanup() {
582             Log.v(TAG, "@After: postTestCleanup()");
583 
584             InstrumentedAutoFillService.resetStaticState();
585             mTestWatcher.cleanAllActivities();
586             cleanAllActivities();
587         }
588 
589         /**
590          * Prepares the service before each test - by default, disables it
591          */
592         protected void prepareServicePreTest() {
593             Log.v(TAG, "prepareServicePreTest(): calling disableService()");
594             disableService();
595         }
596 
597         /**
598          * Enables the {@link InstrumentedAutoFillService} for autofill for the current user.
599          */
600         protected void enableService() {
601             Helper.enableAutofillService(SERVICE_NAME);
602             InstrumentedAutoFillService.setAutofillServiceClass(SERVICE_CLASS);
603         }
604 
605         /**
606          * Disables the {@link InstrumentedAutoFillService} for autofill for the current user.
607          */
608         protected void disableService() {
609             Helper.disableAutofillService();
610         }
611 
612         /**
613          * Asserts that the {@link InstrumentedAutoFillService} is enabled for the default user.
614          */
615         protected void assertServiceEnabled() {
616             Helper.assertAutofillServiceStatus(SERVICE_NAME, true);
617         }
618 
619         /**
620          * Asserts that the {@link InstrumentedAutoFillService} is disabled for the default user.
621          */
622         protected void assertServiceDisabled() {
623             Helper.assertAutofillServiceStatus(SERVICE_NAME, false);
624         }
625 
626         protected RemoteViews createPresentation(String message) {
627             return Helper.createPresentation(message);
628         }
629 
630         protected RemoteViews createPresentationWithCancel(String message) {
631             final RemoteViews presentation = new RemoteViews(getContext()
632                     .getPackageName(), R.layout.list_item_cancel);
633             presentation.setTextViewText(R.id.text1, message);
634             return presentation;
635         }
636 
637         protected InlinePresentation createInlinePresentation(String message) {
638             return Helper.createInlinePresentation(message);
639         }
640 
641         protected InlinePresentation createInlinePresentation(String message,
642                                                               PendingIntent attribution) {
643             return Helper.createInlinePresentation(message, attribution);
644         }
645 
646         @NonNull
647         protected AutofillManager getAutofillManager() {
648             return mContext.getSystemService(AutofillManager.class);
649         }
650 
651         /**
652          * Used to clean all activities that started by test case and does not control by the
653          * AutofillTestWatcher.
654          */
655         protected void cleanAllActivities() {}
656     }
657 
658     protected static final UiBot sDefaultUiBot = new UiBot();
659 
660     private AutoFillServiceTestCase() {
661         throw new UnsupportedOperationException("Contain static stuff only");
662     }
663 }
664