summaryrefslogtreecommitdiff
path: root/adservices/apk/tests/src/com/android/adservices/ui/settings/SettingsActivityTest.java
blob: de130957665c910ca538833cfa57466a9fe6684d (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
/*
 * Copyright (C) 2022 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 com.android.adservices.ui.settings;

import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.Espresso.pressBack;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.hasDescendant;
import static androidx.test.espresso.matcher.ViewMatchers.isChecked;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayingAtLeast;
import static androidx.test.espresso.matcher.ViewMatchers.withClassName;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;

import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;

import android.content.Context;
import android.graphics.Rect;
import android.util.Log;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Switch;

import androidx.core.widget.NestedScrollView;
import androidx.lifecycle.ViewModelProvider;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.espresso.PerformException;
import androidx.test.espresso.UiController;
import androidx.test.espresso.ViewAction;
import androidx.test.espresso.action.ViewActions;
import androidx.test.espresso.matcher.ViewMatchers;
import androidx.test.espresso.util.HumanReadables;
import androidx.test.ext.junit.rules.ActivityScenarioRule;

import com.android.adservices.api.R;
import com.android.adservices.data.topics.Topic;
import com.android.adservices.service.common.BackgroundJobsManager;
import com.android.adservices.service.consent.App;
import com.android.adservices.service.consent.ConsentManager;
import com.android.adservices.ui.settings.fragments.AdServicesSettingsMainFragment;
import com.android.adservices.ui.settings.viewmodels.AppsViewModel;
import com.android.adservices.ui.settings.viewmodels.MainViewModel;
import com.android.adservices.ui.settings.viewmodels.TopicsViewModel;
import com.android.dx.mockito.inline.extended.ExtendedMockito;

import com.google.common.collect.ImmutableList;

import junit.framework.AssertionFailedError;

import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.MockitoSession;
import org.mockito.quality.Strictness;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/** Tests for {@link AdServicesSettingsActivity}. */
public class SettingsActivityTest {
    static ViewModelProvider sViewModelProvider = Mockito.mock(ViewModelProvider.class);
    static ConsentManager sConsentManager;
    private MockitoSession mStaticMockSession;

    private static final class NestedScrollToAction implements ViewAction {
        private static final String TAG =
                androidx.test.espresso.action.ScrollToAction.class.getSimpleName();

        @Override
        public Matcher<View> getConstraints() {
            return Matchers.allOf(
                    ViewMatchers.withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE),
                    ViewMatchers.isDescendantOfA(
                            Matchers.anyOf(
                                    ViewMatchers.isAssignableFrom(NestedScrollView.class),
                                    ViewMatchers.isAssignableFrom(ScrollView.class),
                                    ViewMatchers.isAssignableFrom(HorizontalScrollView.class),
                                    ViewMatchers.isAssignableFrom(ListView.class))));
        }

        @Override
        public void perform(UiController uiController, View view) {
            if (isDisplayingAtLeast(90).matches(view)) {
                Log.i(TAG, "View is already displayed. Returning.");
                return;
            }
            Rect rect = new Rect();
            view.getDrawingRect(rect);
            if (!view.requestRectangleOnScreen(rect, true /* immediate */)) {
                Log.w(TAG, "Scrolling to view was requested, but none of the parents scrolled.");
            }
            uiController.loopMainThreadUntilIdle();
            if (!isDisplayingAtLeast(90).matches(view)) {
                throw new PerformException.Builder()
                        .withActionDescription(this.getDescription())
                        .withViewDescription(HumanReadables.describe(view))
                        .withCause(
                                new RuntimeException(
                                        "Scrolling to view was attempted, but the view is not "
                                                + "displayed"))
                        .build();
            }
        }

        @Override
        public String getDescription() {
            return "scroll to";
        }
    }

    private static ViewAction nestedScrollTo() {
        return ViewActions.actionWithAssertions(new NestedScrollToAction());
    }

    /**
     * {@link ActivityScenarioRule} is a JUnit {@link Rule @Rule} to launch your activity under
     * test.
     *
     * <p>Rules are interceptors which are executed for each test method and are important building
     * blocks of Junit tests.
     */
    @Rule
    public ActivityScenarioRule mRule =
            new ActivityScenarioRule<>(AdServicesSettingsActivityWrapper.class);

    /**
     * This is used by {@link AdServicesSettingsActivityWrapper}. Provides a mocked {@link
     * ViewModelProvider} that serves mocked view models, which use a mocked {@link ConsentManager},
     * which gives mocked data.
     *
     * @return the mocked {@link ViewModelProvider}
     */
    public ViewModelProvider generateMockedViewModelProvider() {
        sConsentManager =
                spy(ConsentManager.getInstance(ApplicationProvider.getApplicationContext()));
        List<Topic> tempList = new ArrayList<>();
        tempList.add(Topic.create(10001, 1, 1));
        tempList.add(Topic.create(10002, 1, 1));
        tempList.add(Topic.create(10003, 1, 1));
        ImmutableList<Topic> topicsList = ImmutableList.copyOf(tempList);
        doReturn(topicsList).when(sConsentManager).getKnownTopicsWithConsent();

        tempList = new ArrayList<>();
        tempList.add(Topic.create(10004, 1, 1));
        tempList.add(Topic.create(10005, 1, 1));
        ImmutableList<Topic> blockedTopicsList = ImmutableList.copyOf(tempList);
        doReturn(blockedTopicsList).when(sConsentManager).getTopicsWithRevokedConsent();

        List<App> appTempList = new ArrayList<>();
        appTempList.add(App.create("app1"));
        appTempList.add(App.create("app2"));
        ImmutableList<App> appsList = ImmutableList.copyOf(appTempList);
        doReturn(appsList).when(sConsentManager).getKnownAppsWithConsent();

        appTempList = new ArrayList<>();
        appTempList.add(App.create("app3"));
        ImmutableList<App> blockedAppsList = ImmutableList.copyOf(appTempList);
        doReturn(blockedAppsList).when(sConsentManager).getAppsWithRevokedConsent();

        doNothing().when(sConsentManager).resetTopicsAndBlockedTopics();
        try {
            doNothing().when(sConsentManager).resetAppsAndBlockedApps();
        } catch (IOException e) {
            e.printStackTrace();
        }
        doNothing().when(sConsentManager).resetMeasurement();

        TopicsViewModel topicsViewModel =
                new TopicsViewModel(ApplicationProvider.getApplicationContext(), sConsentManager);
        AppsViewModel appsViewModel =
                new AppsViewModel(ApplicationProvider.getApplicationContext(), sConsentManager);
        MainViewModel mainViewModel =
                new MainViewModel(ApplicationProvider.getApplicationContext(), sConsentManager);
        doReturn(topicsViewModel).when(sViewModelProvider).get(TopicsViewModel.class);
        doReturn(mainViewModel).when(sViewModelProvider).get(MainViewModel.class);
        doReturn(appsViewModel).when(sViewModelProvider).get(AppsViewModel.class);
        return sViewModelProvider;
    }

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        mStaticMockSession =
                ExtendedMockito.mockitoSession()
                        .spyStatic(BackgroundJobsManager.class)
                        .strictness(Strictness.WARN)
                        .initMocks(this)
                        .startMocking();
        ExtendedMockito.doNothing()
                .when(() -> BackgroundJobsManager.scheduleAllBackgroundJobs(any(Context.class)));
    }

    @After
    public void teardown() {
        if (mStaticMockSession != null) {
            mStaticMockSession.finishMocking();
        }
    }

    /**
     * Test if {@link AdServicesSettingsMainFragment} is displayed in {@link
     * AdServicesSettingsActivity}.
     */
    @Test
    public void test_FragmentContainer_isDisplayed() {
        giveConsentIfNeeded();
        onView(withId(R.id.fragment_container_view)).check(matches(isDisplayed()));
    }

    /**
     * Test if the strings (settingsUI_topics_title, settingsUI_apps_title,
     * settingsUI_main_view_title) are displayed in {@link AdServicesSettingsMainFragment}.
     */
    @Test
    public void test_MainFragmentView_isDisplayed() {
        giveConsentIfNeeded();
        onView(withText(R.string.settingsUI_privacy_sandbox_beta_switch_title))
                .perform(nestedScrollTo())
                .check(matches(isDisplayed()));
        onView(withText(R.string.settingsUI_topics_title))
                .perform(nestedScrollTo())
                .check(matches(isDisplayed()));
        onView(withText(R.string.settingsUI_apps_title))
                .perform(nestedScrollTo())
                .check(matches(isDisplayed()));
    }

    /** Test if {@link MainViewModel} works if Activity is recreated (simulates rotate phone). */
    @Test
    public void test_MainViewModel_getConsent() {
        giveConsentIfNeeded();
        onView(withId(R.id.main_fragment))
                .check(
                        matches(
                                hasDescendant(
                                        Matchers.allOf(
                                                withClassName(Matchers.is(Switch.class.getName())),
                                                isChecked()))));
        onView(withText(R.string.settingsUI_privacy_sandbox_beta_switch_title))
                .perform(nestedScrollTo(), click());

        mRule.getScenario().recreate();
        onView(withId(R.id.main_fragment))
                .check(
                        matches(
                                hasDescendant(
                                        Matchers.allOf(
                                                withClassName(Matchers.is(Switch.class.getName())),
                                                Matchers.not(isChecked())))));

        // Give consent back
        onView(withText(R.string.settingsUI_privacy_sandbox_beta_switch_title))
                .perform(nestedScrollTo(), click());
        onView(withId(R.id.main_fragment))
                .check(
                        matches(
                                hasDescendant(
                                        Matchers.allOf(
                                                withClassName(Matchers.is(Switch.class.getName())),
                                                isChecked()))));
    }

    /**
     * Test if the Topics button in the main fragment opens the topics fragment, and the back button
     * returns to the main fragment.
     */
    @Test
    public void test_TopicsView() {
        giveConsentIfNeeded();

        assertMainFragmentDisplayed();

        onView(withText(R.string.settingsUI_topics_title)).perform(nestedScrollTo(), click());

        assertTopicsFragmentDisplayed();

        pressBack();

        assertMainFragmentDisplayed();
    }

    /**
     * Test if the Topics button in the main fragment opens the topics fragment, and the back button
     * returns to the main fragment.
     */
    @Test
    public void test_BlockedTopicsView() {
        giveConsentIfNeeded();

        assertMainFragmentDisplayed();

        onView(withText(R.string.settingsUI_topics_title)).perform(nestedScrollTo(), click());

        assertTopicsFragmentDisplayed();

        onView(withId(R.id.blocked_topics_button)).perform(nestedScrollTo(), click());

        assertBlockedTopicsFragmentDisplayed();

        pressBack();

        assertTopicsFragmentDisplayed();

        pressBack();

        assertMainFragmentDisplayed();
    }

    /**
     * Test if the Topics button in the main fragment opens the topics fragment, and the back button
     * returns to the main fragment.
     */
    @Test
    public void test_AppsView() {
        giveConsentIfNeeded();

        assertMainFragmentDisplayed();

        onView(withText(R.string.settingsUI_apps_title)).perform(nestedScrollTo(), click());

        assertAppsFragmentDisplayed();

        pressBack();

        assertMainFragmentDisplayed();
    }

    /**
     * Test if the Topics button in the main fragment opens the topics fragment, and the back button
     * returns to the main fragment.
     */
    @Test
    public void test_BlockedAppsView() {
        giveConsentIfNeeded();

        assertMainFragmentDisplayed();

        onView(withText(R.string.settingsUI_apps_title)).perform(nestedScrollTo(), click());

        assertAppsFragmentDisplayed();

        onView(withId(R.id.blocked_apps_button)).perform(nestedScrollTo(), click());

        assertBlockedAppsFragmentDisplayed();

        pressBack();

        assertAppsFragmentDisplayed();

        pressBack();

        assertMainFragmentDisplayed();
    }

    private void assertMainFragmentDisplayed() {
        onView(withText(R.string.settingsUI_main_view_subtitle))
                .perform(nestedScrollTo())
                .check(matches(isDisplayed()));
    }

    private void assertTopicsFragmentDisplayed() {
        onView(withText(R.string.settingsUI_topics_view_subtitle))
                .perform(nestedScrollTo())
                .check(matches(isDisplayed()));
    }

    private void assertAppsFragmentDisplayed() {
        onView(withText(R.string.settingsUI_apps_view_subtitle))
                .perform(nestedScrollTo())
                .check(matches(isDisplayed()));
    }

    private void assertBlockedTopicsFragmentDisplayed() {
        onView(withId(R.id.blocked_topics_list)).check(matches(isDisplayed()));
    }

    private void assertBlockedAppsFragmentDisplayed() {
        onView(withId(R.id.blocked_apps_list)).check(matches(isDisplayed()));
    }

    private void giveConsentIfNeeded() {
        try {
            onView(withId(R.id.main_fragment))
                    .check(
                            matches(
                                    hasDescendant(
                                            Matchers.allOf(
                                                    withClassName(
                                                            Matchers.is(Switch.class.getName())),
                                                    isChecked()))));
        } catch (AssertionFailedError e) {
            // Give consent
            onView(withText(R.string.settingsUI_privacy_sandbox_beta_switch_title))
                    .perform(nestedScrollTo(), click());
        }
    }
}