blob: 4bb6ed48d7400078f9dac3799dae79d0afdddb03 [file] [log] [blame]
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -05001/*
2 * Copyright (C) 2016 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
17package com.android.server.notification;
18
Beverly58b24532018-10-02 09:08:23 -040019import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
20import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_GONE;
Mady Mellorbe797962019-04-01 16:04:24 -070021import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
22import static android.app.Notification.CATEGORY_CALL;
Mady Mellor22f2f072019-04-18 13:26:18 -070023import static android.app.Notification.FLAG_AUTO_CANCEL;
Mady Mellor49b1bf12019-03-29 12:00:02 -070024import static android.app.Notification.FLAG_BUBBLE;
Julia Reynoldse5c60452018-04-30 14:41:36 -040025import static android.app.Notification.FLAG_FOREGROUND_SERVICE;
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -050026import static android.app.NotificationManager.EXTRA_BLOCKED_STATE;
Julia Reynolds27c0a962018-12-10 12:37:28 -050027import static android.app.NotificationManager.IMPORTANCE_DEFAULT;
Julia Reynolds8617e4e2017-09-18 16:52:37 -040028import static android.app.NotificationManager.IMPORTANCE_HIGH;
Julia Reynolds73ed76b2017-04-04 17:04:38 -040029import static android.app.NotificationManager.IMPORTANCE_LOW;
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -050030import static android.app.NotificationManager.IMPORTANCE_MAX;
Julia Reynolds4da79702017-06-01 11:06:10 -040031import static android.app.NotificationManager.IMPORTANCE_NONE;
Julia Reynolds8617e4e2017-09-18 16:52:37 -040032import static android.app.NotificationManager.IMPORTANCE_UNSPECIFIED;
Julia Reynoldsccc6ae62018-03-01 16:24:49 -050033import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_AMBIENT;
34import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_BADGE;
35import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_FULL_SCREEN_INTENT;
36import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_LIGHTS;
37import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_NOTIFICATION_LIST;
38import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_PEEK;
39import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_SCREEN_OFF;
40import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_SCREEN_ON;
41import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_STATUS_BAR;
Julia Reynoldse1816412017-10-24 10:39:11 -040042import static android.content.pm.PackageManager.FEATURE_WATCH;
Julia Reynolds4db59552017-06-30 13:34:01 -040043import static android.content.pm.PackageManager.PERMISSION_DENIED;
Julia Reynolds7a6d07a2019-03-18 11:31:56 -040044import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Julia Reynoldsccc6ae62018-03-01 16:24:49 -050045import static android.os.Build.VERSION_CODES.O_MR1;
46import static android.os.Build.VERSION_CODES.P;
Julia Reynoldsc7dcdc22019-03-25 10:26:14 -040047import static android.service.notification.Adjustment.KEY_IMPORTANCE;
48import static android.service.notification.Adjustment.KEY_USER_SENTIMENT;
Tony Makeda84a72018-11-19 17:01:32 +000049import static android.service.notification.NotificationListenerService.Ranking.USER_SENTIMENT_NEGATIVE;
50import static android.service.notification.NotificationListenerService.Ranking.USER_SENTIMENT_NEUTRAL;
Julia Reynolds73ed76b2017-04-04 17:04:38 -040051
Geoffrey Pitsch03533712017-01-05 10:30:07 -050052import static junit.framework.Assert.assertEquals;
Julia Reynolds727a7282017-04-13 10:54:01 -040053import static junit.framework.Assert.assertFalse;
Julia Reynolds92febc32017-10-26 11:30:31 -040054import static junit.framework.Assert.assertNotNull;
Julia Reynolds8617e4e2017-09-18 16:52:37 -040055import static junit.framework.Assert.assertNull;
Julia Reynoldsbaff4002016-12-15 11:34:26 -050056import static junit.framework.Assert.assertTrue;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -050057import static junit.framework.Assert.fail;
Julia Reynoldsbaff4002016-12-15 11:34:26 -050058
Julia Reynolds5f20e9f2017-01-30 08:54:53 -050059import static org.mockito.Matchers.anyBoolean;
Julia Reynoldsa78cdff2017-04-26 10:19:25 -040060import static org.mockito.Matchers.anyLong;
Julia Reynoldsbaff4002016-12-15 11:34:26 -050061import static org.mockito.Matchers.anyString;
62import static org.mockito.Matchers.eq;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -050063import static org.mockito.Mockito.any;
64import static org.mockito.Mockito.anyInt;
Julia Reynoldseb3dca72017-07-11 10:39:58 -040065import static org.mockito.Mockito.doAnswer;
Julia Reynolds4afe2642019-05-01 08:42:24 -040066import static org.mockito.Mockito.doNothing;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -050067import static org.mockito.Mockito.mock;
Julia Reynolds73ed76b2017-04-04 17:04:38 -040068import static org.mockito.Mockito.never;
69import static org.mockito.Mockito.reset;
Julia Reynolds503ed942017-10-04 16:04:56 -040070import static org.mockito.Mockito.spy;
71import static org.mockito.Mockito.timeout;
Julia Reynoldsbaff4002016-12-15 11:34:26 -050072import static org.mockito.Mockito.times;
73import static org.mockito.Mockito.verify;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -050074import static org.mockito.Mockito.when;
75
Julia Reynolds68263d12017-06-21 14:21:19 -040076import android.app.ActivityManager;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -040077import android.app.AppOpsManager;
Julia Reynoldsa94365d2019-04-09 10:48:43 -040078import android.app.AutomaticZenRule;
Julia Reynoldse0d711f2017-09-01 08:50:47 -040079import android.app.IActivityManager;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -050080import android.app.INotificationManager;
Julia Reynolds268647a2018-10-25 16:54:27 -040081import android.app.ITransientNotification;
82import android.app.IUriGrantsManager;
Julia Reynoldsbaff4002016-12-15 11:34:26 -050083import android.app.Notification;
Julia Reynoldse0d711f2017-09-01 08:50:47 -040084import android.app.Notification.MessagingStyle.Message;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -050085import android.app.NotificationChannel;
Julia Reynolds73ed76b2017-04-04 17:04:38 -040086import android.app.NotificationChannelGroup;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -050087import android.app.NotificationManager;
Mady Mellor7eb18ef2019-03-27 14:03:46 -070088import android.app.PendingIntent;
Mady Mellorbe797962019-04-01 16:04:24 -070089import android.app.Person;
Mady Mellora10448e2019-04-26 13:50:58 -070090import android.app.RemoteInput;
Jason Parks50322ff2018-03-27 10:23:33 -050091import android.app.admin.DevicePolicyManagerInternal;
Julia Reynolds7217dc92018-03-07 12:12:09 -050092import android.app.usage.UsageStatsManagerInternal;
Julia Reynolds73ed76b2017-04-04 17:04:38 -040093import android.companion.ICompanionDeviceManager;
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -050094import android.content.ComponentName;
Jeff Sharkey6a97cc32018-04-17 12:16:20 -060095import android.content.ContentUris;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -050096import android.content.Context;
Beverlyd4f96492017-08-02 13:36:11 -040097import android.content.Intent;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -050098import android.content.pm.ApplicationInfo;
99import android.content.pm.IPackageManager;
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500100import android.content.pm.PackageManager;
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500101import android.content.pm.ParceledListSlice;
Julia Reynolds4afe2642019-05-01 08:42:24 -0400102import android.content.pm.UserInfo;
Kristian Monsen05f34792018-04-09 10:27:16 +0200103import android.content.res.Resources;
Julia Reynolds73ed76b2017-04-04 17:04:38 -0400104import android.graphics.Color;
Mady Mellor7eb18ef2019-03-27 14:03:46 -0700105import android.graphics.drawable.Icon;
Julia Reynolds76c096d2017-06-19 08:16:04 -0400106import android.media.AudioManager;
Julia Reynoldse0d711f2017-09-01 08:50:47 -0400107import android.net.Uri;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500108import android.os.Binder;
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400109import android.os.Build;
Julia Reynolds503ed942017-10-04 16:04:56 -0400110import android.os.Bundle;
Julia Reynoldse0d711f2017-09-01 08:50:47 -0400111import android.os.IBinder;
Julia Reynoldsf27d6b22017-04-13 15:48:16 -0400112import android.os.Process;
Julia Reynoldsb3c68ff2018-05-22 14:58:39 -0400113import android.os.RemoteException;
Mady Mellorbe797962019-04-01 16:04:24 -0700114import android.os.SystemClock;
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500115import android.os.UserHandle;
Julia Reynolds0c245002019-03-27 16:10:11 -0400116import android.os.UserManager;
Tony Mak9a3c1f12019-03-04 16:04:42 +0000117import android.provider.DeviceConfig;
Jeff Sharkey6a97cc32018-04-17 12:16:20 -0600118import android.provider.MediaStore;
Tony Mak9a3c1f12019-03-04 16:04:42 +0000119import android.provider.Settings;
Julia Reynolds503ed942017-10-04 16:04:56 -0400120import android.service.notification.Adjustment;
Julia Reynolds73ed76b2017-04-04 17:04:38 -0400121import android.service.notification.NotificationListenerService;
Julia Reynolds503ed942017-10-04 16:04:56 -0400122import android.service.notification.NotificationStats;
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500123import android.service.notification.StatusBarNotification;
Julia Reynoldsa94365d2019-04-09 10:48:43 -0400124import android.service.notification.ZenPolicy;
Geoffrey Pitsch8185d382017-05-19 18:41:32 -0400125import android.test.suitebuilder.annotation.SmallTest;
Jason Monk745d0a82017-04-17 11:34:22 -0400126import android.testing.AndroidTestingRunner;
Julia Reynolds92febc32017-10-26 11:30:31 -0400127import android.testing.TestableContext;
Geoffrey Pitsch415e4542017-04-10 13:12:58 -0400128import android.testing.TestableLooper;
Jason Monk745d0a82017-04-17 11:34:22 -0400129import android.testing.TestableLooper.RunWithLooper;
Julia Reynolds7a6d07a2019-03-18 11:31:56 -0400130import android.testing.TestablePermissions;
Dan Sandler7d67bd42018-05-15 14:06:38 -0400131import android.text.Html;
Julia Reynoldseb3dca72017-07-11 10:39:58 -0400132import android.util.ArrayMap;
Tony Mak9a3c1f12019-03-04 16:04:42 +0000133import android.util.ArraySet;
Julia Reynoldsb852e562017-06-06 16:14:18 -0400134import android.util.AtomicFile;
Julia Reynoldseb3dca72017-07-11 10:39:58 -0400135
Mady Mellor49b1bf12019-03-29 12:00:02 -0700136import androidx.annotation.Nullable;
137import androidx.test.InstrumentationRegistry;
138
Kristian Monsen05f34792018-04-09 10:27:16 +0200139import com.android.internal.R;
Tony Mak9a3c1f12019-03-04 16:04:42 +0000140import com.android.internal.config.sysui.SystemUiDeviceConfigFlags;
Julia Reynolds503ed942017-10-04 16:04:56 -0400141import com.android.internal.statusbar.NotificationVisibility;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700142import com.android.server.LocalServices;
Beverly58b24532018-10-02 09:08:23 -0400143import com.android.server.SystemService;
Jason Monk74f5e362017-12-06 08:56:33 -0500144import com.android.server.UiServiceTestCase;
Julia Reynoldseb3dca72017-07-11 10:39:58 -0400145import com.android.server.lights.Light;
146import com.android.server.lights.LightsManager;
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -0400147import com.android.server.notification.NotificationManagerService.NotificationAssistants;
148import com.android.server.notification.NotificationManagerService.NotificationListeners;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700149import com.android.server.uri.UriGrantsManagerInternal;
Beverly58b24532018-10-02 09:08:23 -0400150import com.android.server.wm.WindowManagerInternal;
Julia Reynoldseb3dca72017-07-11 10:39:58 -0400151
152import org.junit.After;
153import org.junit.Before;
154import org.junit.Test;
155import org.junit.runner.RunWith;
Julia Reynolds40f00d72017-12-12 10:47:32 -0500156import org.mockito.ArgumentCaptor;
157import org.mockito.Mock;
158import org.mockito.MockitoAnnotations;
Julia Reynoldseb3dca72017-07-11 10:39:58 -0400159import org.mockito.stubbing.Answer;
Julia Reynolds5f20e9f2017-01-30 08:54:53 -0500160
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -0400161import java.io.BufferedInputStream;
162import java.io.ByteArrayInputStream;
Julia Reynoldsb852e562017-06-06 16:14:18 -0400163import java.io.File;
Julia Reynoldsb852e562017-06-06 16:14:18 -0400164import java.io.FileOutputStream;
Julia Reynolds73ed76b2017-04-04 17:04:38 -0400165import java.util.ArrayList;
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500166import java.util.Arrays;
Tony Mak9a3c1f12019-03-04 16:04:42 +0000167import java.util.Collections;
Julia Reynolds73ed76b2017-04-04 17:04:38 -0400168import java.util.List;
Julia Reynoldseb3dca72017-07-11 10:39:58 -0400169import java.util.Map;
Robin Leed107af62018-04-27 13:55:56 +0200170import java.util.function.Consumer;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500171
Geoffrey Pitsch8185d382017-05-19 18:41:32 -0400172@SmallTest
Jason Monk745d0a82017-04-17 11:34:22 -0400173@RunWith(AndroidTestingRunner.class)
174@RunWithLooper
Jason Monk74f5e362017-12-06 08:56:33 -0500175public class NotificationManagerServiceTest extends UiServiceTestCase {
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -0500176 private static final String TEST_CHANNEL_ID = "NotificationManagerServiceTestChannelId";
Tony Mak9a3c1f12019-03-04 16:04:42 +0000177 private static final String CLEAR_DEVICE_CONFIG_KEY_CMD =
178 "device_config delete " + DeviceConfig.NAMESPACE_SYSTEMUI + " "
179 + SystemUiDeviceConfigFlags.NAS_DEFAULT_SERVICE;
180 private static final String SET_DEFAULT_ASSISTANT_DEVICE_CONFIG_CMD =
181 "device_config put " + DeviceConfig.NAMESPACE_SYSTEMUI + " "
182 + SystemUiDeviceConfigFlags.NAS_DEFAULT_SERVICE;
183
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400184 private final int mUid = Binder.getCallingUid();
Julia Reynoldsd78263d2018-01-30 10:40:41 -0500185 private TestableNotificationManagerService mService;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500186 private INotificationManager mBinderService;
Geoffrey Pitsch415e4542017-04-10 13:12:58 -0400187 private NotificationManagerInternal mInternalService;
Julia Reynoldsda781472017-04-12 09:41:16 -0400188 @Mock
189 private IPackageManager mPackageManager;
190 @Mock
191 private PackageManager mPackageManagerClient;
Beverly58b24532018-10-02 09:08:23 -0400192 @Mock
193 private WindowManagerInternal mWindowManagerInternal;
Julia Reynolds92febc32017-10-26 11:30:31 -0400194 private TestableContext mContext = spy(getContext());
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -0500195 private final String PKG = mContext.getPackageName();
Geoffrey Pitsch415e4542017-04-10 13:12:58 -0400196 private TestableLooper mTestableLooper;
Julia Reynoldsda781472017-04-12 09:41:16 -0400197 @Mock
198 private RankingHelper mRankingHelper;
Aaron Heuckrothe5bec152018-07-09 16:26:09 -0400199 @Mock private PreferencesHelper mPreferencesHelper;
Julia Reynoldsb852e562017-06-06 16:14:18 -0400200 AtomicFile mPolicyFile;
201 File mFile;
202 @Mock
Geoffrey Pitschd5bcf212017-06-01 15:45:35 -0400203 private NotificationUsageStats mUsageStats;
Julia Reynolds76c096d2017-06-19 08:16:04 -0400204 @Mock
Julia Reynoldsb3c68ff2018-05-22 14:58:39 -0400205 private UsageStatsManagerInternal mAppUsageStats;
206 @Mock
Julia Reynolds76c096d2017-06-19 08:16:04 -0400207 private AudioManager mAudioManager;
Julia Reynolds68263d12017-06-21 14:21:19 -0400208 @Mock
209 ActivityManager mActivityManager;
Julia Reynoldseb3dca72017-07-11 10:39:58 -0400210 NotificationManagerService.WorkerHandler mHandler;
Kristian Monsen05f34792018-04-09 10:27:16 +0200211 @Mock
212 Resources mResources;
Julia Reynolds3ff26d22017-06-19 08:16:04 -0400213
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -0500214 private NotificationChannel mTestNotificationChannel = new NotificationChannel(
Julia Reynolds27c0a962018-12-10 12:37:28 -0500215 TEST_CHANNEL_ID, TEST_CHANNEL_ID, IMPORTANCE_DEFAULT);
Gustav Senntona8e38aa2019-01-22 14:55:39 +0000216
217 private static final int NOTIFICATION_LOCATION_UNKNOWN = 0;
218
Julia Reynoldsda781472017-04-12 09:41:16 -0400219 @Mock
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -0400220 private NotificationListeners mListeners;
221 @Mock private NotificationAssistants mAssistants;
Julia Reynoldsb852e562017-06-06 16:14:18 -0400222 @Mock private ConditionProviders mConditionProviders;
Julia Reynoldsda781472017-04-12 09:41:16 -0400223 private ManagedServices.ManagedServiceInfo mListener;
224 @Mock private ICompanionDeviceManager mCompanionMgr;
Julia Reynoldsa78cdff2017-04-26 10:19:25 -0400225 @Mock SnoozeHelper mSnoozeHelper;
Julia Reynolds8aebf352017-06-26 11:35:33 -0400226 @Mock GroupHelper mGroupHelper;
Julia Reynoldse0d711f2017-09-01 08:50:47 -0400227 @Mock
228 IBinder mPermOwner;
229 @Mock
230 IActivityManager mAm;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700231 @Mock
232 IUriGrantsManager mUgm;
233 @Mock
234 UriGrantsManagerInternal mUgmInternal;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -0400235 @Mock
236 AppOpsManager mAppOpsManager;
Annie Meng8b646fd2019-02-01 18:46:42 +0000237 @Mock
Tony Mak9a3c1f12019-03-04 16:04:42 +0000238 private TestableNotificationManagerService.NotificationAssistantAccessGrantedCallback
239 mNotificationAssistantAccessGrantedCallback;
Julia Reynolds0c245002019-03-27 16:10:11 -0400240 @Mock
241 UserManager mUm;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500242
Geoffrey Pitsch415e4542017-04-10 13:12:58 -0400243 // Use a Testable subclass so we can simulate calls from the system without failing.
244 private static class TestableNotificationManagerService extends NotificationManagerService {
Julia Reynoldsd78263d2018-01-30 10:40:41 -0500245 int countSystemChecks = 0;
Brad Stenning8c991ea2018-07-31 13:33:01 -0700246 boolean isSystemUid = true;
Gustav Sennton44dc5882018-12-13 14:38:50 +0000247 int countLogSmartSuggestionsVisible = 0;
Tony Mak9a3c1f12019-03-04 16:04:42 +0000248 @Nullable
249 NotificationAssistantAccessGrantedCallback mNotificationAssistantAccessGrantedCallback;
Julia Reynoldsd78263d2018-01-30 10:40:41 -0500250
Julia Reynolds0c245002019-03-27 16:10:11 -0400251 TestableNotificationManagerService(Context context) {
Amith Yamasani803eab692017-11-09 17:47:04 -0800252 super(context);
253 }
Geoffrey Pitsch415e4542017-04-10 13:12:58 -0400254
255 @Override
Geoffrey Pitsch27684152017-05-02 11:41:31 -0400256 protected boolean isCallingUidSystem() {
Julia Reynoldsd78263d2018-01-30 10:40:41 -0500257 countSystemChecks++;
Brad Stenning8c991ea2018-07-31 13:33:01 -0700258 return isSystemUid;
Geoffrey Pitsch27684152017-05-02 11:41:31 -0400259 }
260
261 @Override
262 protected boolean isCallerSystemOrPhone() {
Julia Reynoldsd78263d2018-01-30 10:40:41 -0500263 countSystemChecks++;
Brad Stenning8c991ea2018-07-31 13:33:01 -0700264 return isSystemUid;
Julia Reynolds73ed76b2017-04-04 17:04:38 -0400265 }
Julia Reynolds727a7282017-04-13 10:54:01 -0400266
267 @Override
268 protected ICompanionDeviceManager getCompanionManager() {
269 return null;
270 }
Amith Yamasani803eab692017-11-09 17:47:04 -0800271
272 @Override
Amith Yamasani7ec89412018-02-07 08:48:49 -0800273 protected void reportUserInteraction(NotificationRecord r) {
274 return;
275 }
Julia Reynoldsb62dad42018-11-26 16:33:02 -0500276
277 @Override
278 protected void handleSavePolicyFile() {
279 return;
280 }
Gustav Sennton44dc5882018-12-13 14:38:50 +0000281
282 @Override
Gustav Senntonc7d0d322019-01-07 15:36:41 +0000283 void logSmartSuggestionsVisible(NotificationRecord r, int notificationLocation) {
284 super.logSmartSuggestionsVisible(r, notificationLocation);
Gustav Sennton44dc5882018-12-13 14:38:50 +0000285 countLogSmartSuggestionsVisible++;
286 }
287
Annie Meng8b646fd2019-02-01 18:46:42 +0000288 @Override
Tony Mak9a3c1f12019-03-04 16:04:42 +0000289 protected void setNotificationAssistantAccessGrantedForUserInternal(
290 ComponentName assistant, int userId, boolean granted) {
291 if (mNotificationAssistantAccessGrantedCallback != null) {
292 mNotificationAssistantAccessGrantedCallback.onGranted(assistant, userId, granted);
293 return;
294 }
295 super.setNotificationAssistantAccessGrantedForUserInternal(assistant, userId, granted);
296 }
297
298 private void setNotificationAssistantAccessGrantedCallback(
299 @Nullable NotificationAssistantAccessGrantedCallback callback) {
300 this.mNotificationAssistantAccessGrantedCallback = callback;
301 }
302
303 interface NotificationAssistantAccessGrantedCallback {
304 void onGranted(ComponentName assistant, int userId, boolean granted);
305 }
306
Mady Mellorca0c24c2019-05-16 16:14:32 -0700307 @Override
308 protected boolean canLaunchInActivityView(Context context, PendingIntent pendingIntent,
309 String packageName) {
310 // Tests for this not being true are in CTS NotificationManagerTest
311 return true;
312 }
Geoffrey Pitsch415e4542017-04-10 13:12:58 -0400313 }
314
Beverly58b24532018-10-02 09:08:23 -0400315 private class TestableToastCallback extends ITransientNotification.Stub {
316 @Override
317 public void show(IBinder windowToken) {
318 }
319
320 @Override
321 public void hide() {
322 }
323 }
324
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500325 @Before
326 public void setUp() throws Exception {
Stanislav Zholnin872afd42019-03-12 15:57:25 +0000327 InstrumentationRegistry.getInstrumentation().getUiAutomation().adoptShellPermissionIdentity(
328 "android.permission.WRITE_DEVICE_CONFIG", "android.permission.READ_DEVICE_CONFIG");
329
Julia Reynoldsda781472017-04-12 09:41:16 -0400330 MockitoAnnotations.initMocks(this);
Chris Wren89aa2262017-05-05 18:05:56 -0400331
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700332 LocalServices.removeServiceForTest(UriGrantsManagerInternal.class);
333 LocalServices.addService(UriGrantsManagerInternal.class, mUgmInternal);
Beverly58b24532018-10-02 09:08:23 -0400334 LocalServices.removeServiceForTest(WindowManagerInternal.class);
335 LocalServices.addService(WindowManagerInternal.class, mWindowManagerInternal);
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700336
Julia Reynolds4afe2642019-05-01 08:42:24 -0400337 doNothing().when(mContext).sendBroadcastAsUser(any(), any(), any());
338
Julia Reynolds0c245002019-03-27 16:10:11 -0400339 mService = new TestableNotificationManagerService(mContext);
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500340
Julia Reynoldseb3dca72017-07-11 10:39:58 -0400341 // Use this testable looper.
342 mTestableLooper = TestableLooper.get(this);
Julia Reynolds503ed942017-10-04 16:04:56 -0400343 mHandler = mService.new WorkerHandler(mTestableLooper.getLooper());
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500344 // MockPackageManager - default returns ApplicationInfo with matching calling UID
Julia Reynolds92febc32017-10-26 11:30:31 -0400345 mContext.setMockPackageManager(mPackageManagerClient);
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500346 final ApplicationInfo applicationInfo = new ApplicationInfo();
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400347 applicationInfo.uid = mUid;
Julia Reynolds73ed76b2017-04-04 17:04:38 -0400348 when(mPackageManager.getApplicationInfo(anyString(), anyInt(), anyInt()))
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500349 .thenReturn(applicationInfo);
Julia Reynolds5f20e9f2017-01-30 08:54:53 -0500350 when(mPackageManagerClient.getApplicationInfoAsUser(anyString(), anyInt(), anyInt()))
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500351 .thenReturn(applicationInfo);
Julia Reynolds92febc32017-10-26 11:30:31 -0400352 when(mPackageManagerClient.getPackageUidAsUser(any(), anyInt())).thenReturn(mUid);
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500353 final LightsManager mockLightsManager = mock(LightsManager.class);
354 when(mockLightsManager.getLight(anyInt())).thenReturn(mock(Light.class));
Julia Reynolds76c096d2017-06-19 08:16:04 -0400355 when(mAudioManager.getRingerModeInternal()).thenReturn(AudioManager.RINGER_MODE_NORMAL);
Julia Reynoldse1816412017-10-24 10:39:11 -0400356 when(mPackageManagerClient.hasSystemFeature(FEATURE_WATCH)).thenReturn(false);
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700357 when(mUgmInternal.newUriPermissionOwner(anyString())).thenReturn(mPermOwner);
Julia Reynolds268647a2018-10-25 16:54:27 -0400358 when(mPackageManager.getPackagesForUid(mUid)).thenReturn(new String[]{PKG});
Julia Reynolds4214da92019-04-10 15:04:06 -0400359 when(mPackageManagerClient.getPackagesForUid(anyInt())).thenReturn(new String[]{PKG});
Julia Reynoldse99db5a2019-04-16 12:50:04 -0400360 mContext.addMockSystemService(AppOpsManager.class, mock(AppOpsManager.class));
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500361
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -0400362 // write to a test file; the system file isn't readable from tests
Julia Reynoldsb852e562017-06-06 16:14:18 -0400363 mFile = new File(mContext.getCacheDir(), "test.xml");
364 mFile.createNewFile();
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -0400365 final String preupgradeXml = "<notification-policy></notification-policy>";
366 mPolicyFile = new AtomicFile(mFile);
367 FileOutputStream fos = mPolicyFile.startWrite();
368 fos.write(preupgradeXml.getBytes());
369 mPolicyFile.finishWrite(fos);
Julia Reynoldsb852e562017-06-06 16:14:18 -0400370
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -0400371 // Setup managed services
372 mListener = mListeners.new ManagedServiceInfo(
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400373 null, new ComponentName(PKG, "test_class"), mUid, true, null, 0);
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -0400374 when(mListeners.checkServiceTokenLocked(any())).thenReturn(mListener);
375 ManagedServices.Config listenerConfig = new ManagedServices.Config();
376 listenerConfig.xmlTag = NotificationListeners.TAG_ENABLED_NOTIFICATION_LISTENERS;
377 when(mListeners.getConfig()).thenReturn(listenerConfig);
378 ManagedServices.Config assistantConfig = new ManagedServices.Config();
379 assistantConfig.xmlTag = NotificationAssistants.TAG_ENABLED_NOTIFICATION_ASSISTANTS;
380 when(mAssistants.getConfig()).thenReturn(assistantConfig);
381 ManagedServices.Config dndConfig = new ManagedServices.Config();
382 dndConfig.xmlTag = ConditionProviders.TAG_ENABLED_DND_APPS;
383 when(mConditionProviders.getConfig()).thenReturn(dndConfig);
384
Julia Reynolds418a8ff2019-03-21 10:45:10 -0400385 when(mAssistants.isAdjustmentAllowed(anyString())).thenReturn(true);
386
Julia Reynolds4afe2642019-05-01 08:42:24 -0400387
388 mService.init(mTestableLooper.getLooper(),
389 mPackageManager, mPackageManagerClient, mockLightsManager,
390 mListeners, mAssistants, mConditionProviders,
391 mCompanionMgr, mSnoozeHelper, mUsageStats, mPolicyFile, mActivityManager,
392 mGroupHelper, mAm, mAppUsageStats,
393 mock(DevicePolicyManagerInternal.class), mUgm, mUgmInternal,
394 mAppOpsManager, mUm);
395 mService.onBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
396
Julia Reynolds503ed942017-10-04 16:04:56 -0400397 mService.setAudioManager(mAudioManager);
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500398
399 // Tests call directly into the Binder.
Julia Reynolds503ed942017-10-04 16:04:56 -0400400 mBinderService = mService.getBinderService();
401 mInternalService = mService.getInternalService();
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -0500402
403 mBinderService.createNotificationChannels(
404 PKG, new ParceledListSlice(Arrays.asList(mTestNotificationChannel)));
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -0400405 assertNotNull(mBinderService.getNotificationChannel(
406 PKG, mContext.getUserId(), PKG, TEST_CHANNEL_ID));
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500407 }
408
Julia Reynoldsb852e562017-06-06 16:14:18 -0400409 @After
410 public void tearDown() throws Exception {
411 mFile.delete();
Tony Mak9a3c1f12019-03-04 16:04:42 +0000412 clearDeviceConfig();
Stanislav Zholnin872afd42019-03-12 15:57:25 +0000413 InstrumentationRegistry.getInstrumentation()
414 .getUiAutomation().dropShellPermissionIdentity();
Julia Reynoldsb852e562017-06-06 16:14:18 -0400415 }
416
Julia Reynolds7bcb57b2018-01-22 10:37:58 -0500417 public void waitForIdle() {
Geoffrey Pitsch415e4542017-04-10 13:12:58 -0400418 mTestableLooper.processAllMessages();
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500419 }
420
Mady Mellorc6820342019-05-20 12:04:36 -0700421 private void setUpPrefsForBubbles(boolean globalEnabled, boolean pkgEnabled,
422 boolean channelEnabled) {
423 mService.setPreferencesHelper(mPreferencesHelper);
Lyn Han4463f842019-07-09 15:27:28 -0700424 when(mPreferencesHelper.bubblesEnabled()).thenReturn(globalEnabled);
Mady Mellorc6820342019-05-20 12:04:36 -0700425 when(mPreferencesHelper.areBubblesAllowed(anyString(), anyInt())).thenReturn(pkgEnabled);
426 when(mPreferencesHelper.getNotificationChannel(
427 anyString(), anyInt(), anyString(), anyBoolean())).thenReturn(
428 mTestNotificationChannel);
429 when(mPreferencesHelper.getImportance(anyString(), anyInt())).thenReturn(
430 mTestNotificationChannel.getImportance());
431 mTestNotificationChannel.setAllowBubbles(channelEnabled);
432 }
433
Julia Reynolds7bcb57b2018-01-22 10:37:58 -0500434 private StatusBarNotification generateSbn(String pkg, int uid, long postTime, int userId) {
435 Notification.Builder nb = new Notification.Builder(mContext, "a")
436 .setContentTitle("foo")
437 .setSmallIcon(android.R.drawable.sym_def_app_icon);
438 StatusBarNotification sbn = new StatusBarNotification(pkg, pkg, uid, "tag", uid, 0,
439 nb.build(), new UserHandle(userId), null, postTime);
440 return sbn;
441 }
442
Mady Mellor22f2f072019-04-18 13:26:18 -0700443
Julia Reynoldsa78cdff2017-04-26 10:19:25 -0400444 private NotificationRecord generateNotificationRecord(NotificationChannel channel, int id,
445 String groupKey, boolean isSummary) {
Mady Mellor22f2f072019-04-18 13:26:18 -0700446 return generateNotificationRecord(channel, id, groupKey, isSummary, false /* isBubble */);
447 }
448
449 private NotificationRecord generateNotificationRecord(NotificationChannel channel, int id,
450 String groupKey, boolean isSummary, boolean isBubble) {
Julia Reynoldsa78cdff2017-04-26 10:19:25 -0400451 Notification.Builder nb = new Notification.Builder(mContext, channel.getId())
452 .setContentTitle("foo")
453 .setSmallIcon(android.R.drawable.sym_def_app_icon)
454 .setGroup(groupKey)
455 .setGroupSummary(isSummary);
Mady Mellor22f2f072019-04-18 13:26:18 -0700456 if (isBubble) {
457 nb.setBubbleMetadata(getBasicBubbleMetadataBuilder().build());
458 }
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400459 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, id, "tag", mUid, 0,
460 nb.build(), new UserHandle(mUid), null, 0);
Geoffrey Pitscha22f6442017-05-05 16:47:38 +0000461 return new NotificationRecord(mContext, sbn, channel);
Julia Reynoldsa78cdff2017-04-26 10:19:25 -0400462 }
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400463
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500464 private NotificationRecord generateNotificationRecord(NotificationChannel channel) {
Julia Reynolds5f20e9f2017-01-30 08:54:53 -0500465 return generateNotificationRecord(channel, null);
466 }
467
468 private NotificationRecord generateNotificationRecord(NotificationChannel channel,
469 Notification.TvExtender extender) {
Mady Mellorbe797962019-04-01 16:04:24 -0700470 return generateNotificationRecord(channel, extender, false /* isBubble */);
471 }
472
473 private NotificationRecord generateNotificationRecord(NotificationChannel channel,
474 Notification.TvExtender extender, boolean isBubble) {
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500475 if (channel == null) {
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -0500476 channel = mTestNotificationChannel;
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500477 }
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500478 Notification.Builder nb = new Notification.Builder(mContext, channel.getId())
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500479 .setContentTitle("foo")
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500480 .setSmallIcon(android.R.drawable.sym_def_app_icon);
Julia Reynolds5f20e9f2017-01-30 08:54:53 -0500481 if (extender != null) {
482 nb.extend(extender);
483 }
Mady Mellorbe797962019-04-01 16:04:24 -0700484 if (isBubble) {
485 nb.setBubbleMetadata(getBasicBubbleMetadataBuilder().build());
486 }
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400487 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, "tag", mUid, 0,
488 nb.build(), new UserHandle(mUid), null, 0);
Geoffrey Pitscha22f6442017-05-05 16:47:38 +0000489 return new NotificationRecord(mContext, sbn, channel);
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500490 }
491
Julia Reynoldseb3dca72017-07-11 10:39:58 -0400492 private Map<String, Answer> getSignalExtractorSideEffects() {
493 Map<String, Answer> answers = new ArrayMap<>();
494
495 answers.put("override group key", invocationOnMock -> {
496 ((NotificationRecord) invocationOnMock.getArguments()[0])
497 .setOverrideGroupKey("bananas");
498 return null;
499 });
500 answers.put("override people", invocationOnMock -> {
501 ((NotificationRecord) invocationOnMock.getArguments()[0])
502 .setPeopleOverride(new ArrayList<>());
503 return null;
504 });
505 answers.put("snooze criteria", invocationOnMock -> {
506 ((NotificationRecord) invocationOnMock.getArguments()[0])
507 .setSnoozeCriteria(new ArrayList<>());
508 return null;
509 });
510 answers.put("notification channel", invocationOnMock -> {
511 ((NotificationRecord) invocationOnMock.getArguments()[0])
512 .updateNotificationChannel(new NotificationChannel("a", "", IMPORTANCE_LOW));
513 return null;
514 });
515 answers.put("badging", invocationOnMock -> {
516 NotificationRecord r = (NotificationRecord) invocationOnMock.getArguments()[0];
517 r.setShowBadge(!r.canShowBadge());
518 return null;
519 });
Julia Reynolds4509ce72019-01-31 13:12:43 -0500520 answers.put("bubbles", invocationOnMock -> {
521 NotificationRecord r = (NotificationRecord) invocationOnMock.getArguments()[0];
522 r.setAllowBubble(!r.canBubble());
523 return null;
524 });
Julia Reynoldseb3dca72017-07-11 10:39:58 -0400525 answers.put("package visibility", invocationOnMock -> {
526 ((NotificationRecord) invocationOnMock.getArguments()[0]).setPackageVisibilityOverride(
527 Notification.VISIBILITY_SECRET);
528 return null;
529 });
530
531 return answers;
532 }
533
Julia Reynoldsc7dcdc22019-03-25 10:26:14 -0400534 private void clearDeviceConfig() {
535 DeviceConfig.resetToDefaults(
536 Settings.RESET_MODE_PACKAGE_DEFAULTS, DeviceConfig.NAMESPACE_SYSTEMUI);
537 }
538
539 private void setDefaultAssistantInDeviceConfig(String componentName) {
540 DeviceConfig.setProperty(
541 DeviceConfig.NAMESPACE_SYSTEMUI,
542 SystemUiDeviceConfigFlags.NAS_DEFAULT_SERVICE,
543 componentName,
544 false);
545 }
546
Mady Mellor7eb18ef2019-03-27 14:03:46 -0700547 private Notification.BubbleMetadata.Builder getBasicBubbleMetadataBuilder() {
548 PendingIntent pi = PendingIntent.getActivity(mContext, 0, new Intent(), 0);
549 return new Notification.BubbleMetadata.Builder()
550 .setIntent(pi)
551 .setIcon(Icon.createWithResource(mContext, android.R.drawable.sym_def_app_icon));
552 }
553
Mady Mellor22f2f072019-04-18 13:26:18 -0700554 private NotificationRecord addGroupWithBubblesAndValidateAdded(boolean summaryAutoCancel)
555 throws RemoteException {
556
557 // Notification that has bubble metadata
558 NotificationRecord nrBubble = generateNotificationRecord(mTestNotificationChannel, 1,
559 "BUBBLE_GROUP", false /* isSummary */, true /* isBubble */);
560
561 // Make the package foreground so that we're allowed to be a bubble
562 when(mActivityManager.getPackageImportance(nrBubble.sbn.getPackageName())).thenReturn(
563 IMPORTANCE_FOREGROUND);
564
565 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
566 nrBubble.sbn.getId(), nrBubble.sbn.getNotification(), nrBubble.sbn.getUserId());
567 waitForIdle();
568
569 // Make sure we are a bubble
570 StatusBarNotification[] notifsAfter = mBinderService.getActiveNotifications(PKG);
571 assertEquals(1, notifsAfter.length);
572 assertTrue((notifsAfter[0].getNotification().flags & FLAG_BUBBLE) != 0);
573
574 // Plain notification without bubble metadata
575 NotificationRecord nrPlain = generateNotificationRecord(mTestNotificationChannel, 2,
576 "BUBBLE_GROUP", false /* isSummary */, false /* isBubble */);
577 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
578 nrPlain.sbn.getId(), nrPlain.sbn.getNotification(), nrPlain.sbn.getUserId());
579 waitForIdle();
580
581 notifsAfter = mBinderService.getActiveNotifications(PKG);
582 assertEquals(2, notifsAfter.length);
583
584 // Summary notification for both of those
585 NotificationRecord nrSummary = generateNotificationRecord(mTestNotificationChannel, 3,
586 "BUBBLE_GROUP", true /* isSummary */, false /* isBubble */);
587 if (summaryAutoCancel) {
588 nrSummary.getNotification().flags |= FLAG_AUTO_CANCEL;
589 }
590 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
591 nrSummary.sbn.getId(), nrSummary.sbn.getNotification(), nrSummary.sbn.getUserId());
592 waitForIdle();
593
594 notifsAfter = mBinderService.getActiveNotifications(PKG);
595 assertEquals(3, notifsAfter.length);
596
597 return nrSummary;
598 }
599
Geoffrey Pitsch16594462017-01-26 14:42:30 -0500600 @Test
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500601 public void testCreateNotificationChannels_SingleChannel() throws Exception {
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500602 final NotificationChannel channel =
Julia Reynolds27c0a962018-12-10 12:37:28 -0500603 new NotificationChannel("id", "name", IMPORTANCE_DEFAULT);
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400604 mBinderService.createNotificationChannels(PKG,
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500605 new ParceledListSlice(Arrays.asList(channel)));
606 final NotificationChannel createdChannel =
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -0400607 mBinderService.getNotificationChannel(PKG, mContext.getUserId(), PKG, "id");
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500608 assertTrue(createdChannel != null);
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500609 }
610
Geoffrey Pitsch16594462017-01-26 14:42:30 -0500611 @Test
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500612 public void testCreateNotificationChannels_NullChannelThrowsException() throws Exception {
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500613 try {
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400614 mBinderService.createNotificationChannels(PKG,
Kristian Monsen05f34792018-04-09 10:27:16 +0200615 new ParceledListSlice(Arrays.asList((Object[])null)));
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500616 fail("Exception should be thrown immediately.");
617 } catch (NullPointerException e) {
618 // pass
619 }
620 }
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500621
Geoffrey Pitsch16594462017-01-26 14:42:30 -0500622 @Test
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500623 public void testCreateNotificationChannels_TwoChannels() throws Exception {
624 final NotificationChannel channel1 =
Julia Reynolds27c0a962018-12-10 12:37:28 -0500625 new NotificationChannel("id1", "name", IMPORTANCE_DEFAULT);
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500626 final NotificationChannel channel2 =
Julia Reynolds27c0a962018-12-10 12:37:28 -0500627 new NotificationChannel("id2", "name", IMPORTANCE_DEFAULT);
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400628 mBinderService.createNotificationChannels(PKG,
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500629 new ParceledListSlice(Arrays.asList(channel1, channel2)));
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -0400630 assertTrue(mBinderService.getNotificationChannel(
631 PKG, mContext.getUserId(), PKG, "id1") != null);
632 assertTrue(mBinderService.getNotificationChannel(
633 PKG, mContext.getUserId(), PKG, "id2") != null);
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500634 }
635
Geoffrey Pitsch16594462017-01-26 14:42:30 -0500636 @Test
Geoffrey Pitsch76a3aa02017-07-26 15:07:34 -0400637 public void testCreateNotificationChannels_SecondCreateDoesNotChangeImportance()
638 throws Exception {
639 final NotificationChannel channel =
Julia Reynolds27c0a962018-12-10 12:37:28 -0500640 new NotificationChannel("id", "name", IMPORTANCE_DEFAULT);
Geoffrey Pitsch76a3aa02017-07-26 15:07:34 -0400641 mBinderService.createNotificationChannels(PKG,
642 new ParceledListSlice(Arrays.asList(channel)));
643
644 // Recreating the channel doesn't throw, but ignores importance.
645 final NotificationChannel dupeChannel =
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400646 new NotificationChannel("id", "name", IMPORTANCE_HIGH);
Geoffrey Pitsch76a3aa02017-07-26 15:07:34 -0400647 mBinderService.createNotificationChannels(PKG,
648 new ParceledListSlice(Arrays.asList(dupeChannel)));
649 final NotificationChannel createdChannel =
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -0400650 mBinderService.getNotificationChannel(PKG, mContext.getUserId(), PKG, "id");
Julia Reynolds27c0a962018-12-10 12:37:28 -0500651 assertEquals(IMPORTANCE_DEFAULT, createdChannel.getImportance());
Geoffrey Pitsch76a3aa02017-07-26 15:07:34 -0400652 }
653
654 @Test
655 public void testCreateNotificationChannels_SecondCreateAllowedToDowngradeImportance()
656 throws Exception {
657 final NotificationChannel channel =
Julia Reynolds27c0a962018-12-10 12:37:28 -0500658 new NotificationChannel("id", "name", IMPORTANCE_DEFAULT);
Geoffrey Pitsch76a3aa02017-07-26 15:07:34 -0400659 mBinderService.createNotificationChannels(PKG,
660 new ParceledListSlice(Arrays.asList(channel)));
661
662 // Recreating with a lower importance is allowed to modify the channel.
663 final NotificationChannel dupeChannel =
664 new NotificationChannel("id", "name", NotificationManager.IMPORTANCE_LOW);
665 mBinderService.createNotificationChannels(PKG,
666 new ParceledListSlice(Arrays.asList(dupeChannel)));
667 final NotificationChannel createdChannel =
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -0400668 mBinderService.getNotificationChannel(PKG, mContext.getUserId(), PKG, "id");
Geoffrey Pitsch76a3aa02017-07-26 15:07:34 -0400669 assertEquals(NotificationManager.IMPORTANCE_LOW, createdChannel.getImportance());
670 }
671
672 @Test
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400673 public void testCreateNotificationChannels_CannotDowngradeImportanceIfAlreadyUpdated()
674 throws Exception {
675 final NotificationChannel channel =
Julia Reynolds27c0a962018-12-10 12:37:28 -0500676 new NotificationChannel("id", "name", IMPORTANCE_DEFAULT);
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400677 mBinderService.createNotificationChannels(PKG,
678 new ParceledListSlice(Arrays.asList(channel)));
679
680 // The user modifies importance directly, can no longer be changed by the app.
681 final NotificationChannel updatedChannel =
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400682 new NotificationChannel("id", "name", IMPORTANCE_HIGH);
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400683 mBinderService.updateNotificationChannelForPackage(PKG, mUid, updatedChannel);
684
685 // Recreating with a lower importance leaves channel unchanged.
686 final NotificationChannel dupeChannel =
687 new NotificationChannel("id", "name", NotificationManager.IMPORTANCE_LOW);
688 mBinderService.createNotificationChannels(PKG,
689 new ParceledListSlice(Arrays.asList(dupeChannel)));
690 final NotificationChannel createdChannel =
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -0400691 mBinderService.getNotificationChannel(PKG, mContext.getUserId(), PKG, "id");
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400692 assertEquals(IMPORTANCE_HIGH, createdChannel.getImportance());
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400693 }
694
695 @Test
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500696 public void testCreateNotificationChannels_IdenticalChannelsInListIgnoresSecond()
697 throws Exception {
698 final NotificationChannel channel1 =
Julia Reynolds27c0a962018-12-10 12:37:28 -0500699 new NotificationChannel("id", "name", IMPORTANCE_DEFAULT);
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500700 final NotificationChannel channel2 =
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400701 new NotificationChannel("id", "name", IMPORTANCE_HIGH);
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400702 mBinderService.createNotificationChannels(PKG,
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500703 new ParceledListSlice(Arrays.asList(channel1, channel2)));
704 final NotificationChannel createdChannel =
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -0400705 mBinderService.getNotificationChannel(PKG, mContext.getUserId(), PKG, "id");
Julia Reynolds27c0a962018-12-10 12:37:28 -0500706 assertEquals(IMPORTANCE_DEFAULT, createdChannel.getImportance());
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500707 }
708
Geoffrey Pitsch16594462017-01-26 14:42:30 -0500709 @Test
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500710 public void testBlockedNotifications_suspended() throws Exception {
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500711 when(mPackageManager.isPackageSuspendedForUser(anyString(), anyInt())).thenReturn(true);
712
713 NotificationChannel channel = new NotificationChannel("id", "name",
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400714 IMPORTANCE_HIGH);
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500715 NotificationRecord r = generateNotificationRecord(channel);
Beverly3c707b42018-09-14 09:49:07 -0400716
717 // isBlocked is only used for user blocking, not app suspension
718 assertFalse(mService.isBlocked(r, mUsageStats));
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500719 }
720
Geoffrey Pitsch16594462017-01-26 14:42:30 -0500721 @Test
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500722 public void testBlockedNotifications_blockedChannel() throws Exception {
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500723 when(mPackageManager.isPackageSuspendedForUser(anyString(), anyInt())).thenReturn(false);
724
725 NotificationChannel channel = new NotificationChannel("id", "name",
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400726 NotificationManager.IMPORTANCE_NONE);
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500727 NotificationRecord r = generateNotificationRecord(channel);
Julia Reynolds503ed942017-10-04 16:04:56 -0400728 assertTrue(mService.isBlocked(r, mUsageStats));
Geoffrey Pitschd5bcf212017-06-01 15:45:35 -0400729 verify(mUsageStats, times(1)).registerBlocked(eq(r));
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400730
731 mBinderService.createNotificationChannels(
732 PKG, new ParceledListSlice(Arrays.asList(channel)));
733 final StatusBarNotification sbn = generateNotificationRecord(channel).sbn;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -0400734 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400735 sbn.getId(), sbn.getNotification(), sbn.getUserId());
736 waitForIdle();
737 assertEquals(0, mBinderService.getActiveNotifications(sbn.getPackageName()).length);
738 }
739
740 @Test
741 public void testEnqueuedBlockedNotifications_appBlockedChannelForegroundService()
742 throws Exception {
743 when(mPackageManager.isPackageSuspendedForUser(anyString(), anyInt())).thenReturn(false);
744
745 NotificationChannel channel = new NotificationChannel("blocked", "name",
746 NotificationManager.IMPORTANCE_NONE);
747 mBinderService.createNotificationChannels(
748 PKG, new ParceledListSlice(Arrays.asList(channel)));
749
750 final StatusBarNotification sbn = generateNotificationRecord(channel).sbn;
Julia Reynoldse5c60452018-04-30 14:41:36 -0400751 sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -0400752 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400753 sbn.getId(), sbn.getNotification(), sbn.getUserId());
754 waitForIdle();
755 assertEquals(1, mBinderService.getActiveNotifications(sbn.getPackageName()).length);
756 assertEquals(IMPORTANCE_LOW,
Julia Reynolds503ed942017-10-04 16:04:56 -0400757 mService.getNotificationRecord(sbn.getKey()).getImportance());
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -0400758 assertEquals(IMPORTANCE_LOW, mBinderService.getNotificationChannel(
759 PKG, mContext.getUserId(), PKG, channel.getId()).getImportance());
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400760 }
761
762 @Test
763 public void testEnqueuedBlockedNotifications_userBlockedChannelForegroundService()
764 throws Exception {
765 when(mPackageManager.isPackageSuspendedForUser(anyString(), anyInt())).thenReturn(false);
766
767 NotificationChannel channel =
768 new NotificationChannel("blockedbyuser", "name", IMPORTANCE_HIGH);
769 mBinderService.createNotificationChannels(
770 PKG, new ParceledListSlice(Arrays.asList(channel)));
771
772 NotificationChannel update =
773 new NotificationChannel("blockedbyuser", "name", IMPORTANCE_NONE);
774 mBinderService.updateNotificationChannelForPackage(PKG, mUid, update);
775 waitForIdle();
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -0400776 assertEquals(IMPORTANCE_NONE, mBinderService.getNotificationChannel(
777 PKG, mContext.getUserId(), PKG, channel.getId()).getImportance());
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400778
Dianne Hackborn025d4a52018-04-30 16:23:26 -0700779 StatusBarNotification sbn = generateNotificationRecord(channel).sbn;
Julia Reynoldse5c60452018-04-30 14:41:36 -0400780 sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -0400781 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400782 sbn.getId(), sbn.getNotification(), sbn.getUserId());
783 waitForIdle();
Dianne Hackborn025d4a52018-04-30 16:23:26 -0700784 // The first time a foreground service notification is shown, we allow the channel
785 // to be updated to allow it to be seen.
786 assertEquals(1, mBinderService.getActiveNotifications(sbn.getPackageName()).length);
787 assertEquals(IMPORTANCE_LOW,
788 mService.getNotificationRecord(sbn.getKey()).getImportance());
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -0400789 assertEquals(IMPORTANCE_LOW, mBinderService.getNotificationChannel(
790 PKG, mContext.getUserId(), PKG, channel.getId()).getImportance());
Dianne Hackborn025d4a52018-04-30 16:23:26 -0700791 mBinderService.cancelNotificationWithTag(PKG, "tag", sbn.getId(), sbn.getUserId());
792 waitForIdle();
793
794 update = new NotificationChannel("blockedbyuser", "name", IMPORTANCE_NONE);
795 update.setFgServiceShown(true);
796 mBinderService.updateNotificationChannelForPackage(PKG, mUid, update);
797 waitForIdle();
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -0400798 assertEquals(IMPORTANCE_NONE, mBinderService.getNotificationChannel(
799 PKG, mContext.getUserId(), PKG, channel.getId()).getImportance());
Dianne Hackborn025d4a52018-04-30 16:23:26 -0700800
801 sbn = generateNotificationRecord(channel).sbn;
802 sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -0400803 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Dianne Hackborn025d4a52018-04-30 16:23:26 -0700804 sbn.getId(), sbn.getNotification(), sbn.getUserId());
805 waitForIdle();
806 // The second time it is shown, we keep the user's preference.
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400807 assertEquals(0, mBinderService.getActiveNotifications(sbn.getPackageName()).length);
Julia Reynolds503ed942017-10-04 16:04:56 -0400808 assertNull(mService.getNotificationRecord(sbn.getKey()));
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -0400809 assertEquals(IMPORTANCE_NONE, mBinderService.getNotificationChannel(
810 PKG, mContext.getUserId(), PKG, channel.getId()).getImportance());
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500811 }
812
Geoffrey Pitsch16594462017-01-26 14:42:30 -0500813 @Test
Julia Reynolds005c8b92017-08-24 10:35:53 -0400814 public void testBlockedNotifications_blockedChannelGroup() throws Exception {
815 when(mPackageManager.isPackageSuspendedForUser(anyString(), anyInt())).thenReturn(false);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -0400816 mService.setPreferencesHelper(mPreferencesHelper);
817 when(mPreferencesHelper.isGroupBlocked(anyString(), anyInt(), anyString())).thenReturn(true);
Julia Reynolds005c8b92017-08-24 10:35:53 -0400818
819 NotificationChannel channel = new NotificationChannel("id", "name",
820 NotificationManager.IMPORTANCE_HIGH);
821 channel.setGroup("something");
822 NotificationRecord r = generateNotificationRecord(channel);
Julia Reynolds503ed942017-10-04 16:04:56 -0400823 assertTrue(mService.isBlocked(r, mUsageStats));
Julia Reynolds005c8b92017-08-24 10:35:53 -0400824 verify(mUsageStats, times(1)).registerBlocked(eq(r));
825 }
826
827 @Test
Julia Reynolds4da79702017-06-01 11:06:10 -0400828 public void testEnqueuedBlockedNotifications_blockedApp() throws Exception {
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500829 when(mPackageManager.isPackageSuspendedForUser(anyString(), anyInt())).thenReturn(false);
830
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400831 mBinderService.setNotificationsEnabledForPackage(PKG, mUid, false);
Julia Reynolds4da79702017-06-01 11:06:10 -0400832
833 final StatusBarNotification sbn = generateNotificationRecord(null).sbn;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -0400834 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Julia Reynolds4da79702017-06-01 11:06:10 -0400835 sbn.getId(), sbn.getNotification(), sbn.getUserId());
836 waitForIdle();
837 assertEquals(0, mBinderService.getActiveNotifications(sbn.getPackageName()).length);
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500838 }
839
Geoffrey Pitsch16594462017-01-26 14:42:30 -0500840 @Test
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400841 public void testEnqueuedBlockedNotifications_blockedAppForegroundService() throws Exception {
842 when(mPackageManager.isPackageSuspendedForUser(anyString(), anyInt())).thenReturn(false);
843
844 mBinderService.setNotificationsEnabledForPackage(PKG, mUid, false);
845
846 final StatusBarNotification sbn = generateNotificationRecord(null).sbn;
Julia Reynoldse5c60452018-04-30 14:41:36 -0400847 sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -0400848 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400849 sbn.getId(), sbn.getNotification(), sbn.getUserId());
850 waitForIdle();
851 assertEquals(0, mBinderService.getActiveNotifications(sbn.getPackageName()).length);
Julia Reynolds503ed942017-10-04 16:04:56 -0400852 assertNull(mService.getNotificationRecord(sbn.getKey()));
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400853 }
854
Brad Stenning8c991ea2018-07-31 13:33:01 -0700855 /**
856 * Confirm the system user on automotive devices can use car categories
857 */
858 @Test
859 public void testEnqueuedRestrictedNotifications_asSystem() throws Exception {
860 when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE, 0))
861 .thenReturn(true);
862 List<String> categories = Arrays.asList(Notification.CATEGORY_CAR_EMERGENCY,
863 Notification.CATEGORY_CAR_WARNING,
864 Notification.CATEGORY_CAR_INFORMATION);
865 int id = 0;
866 for (String category: categories) {
867 final StatusBarNotification sbn =
868 generateNotificationRecord(mTestNotificationChannel, ++id, "", false).sbn;
869 sbn.getNotification().category = category;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -0400870 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Brad Stenning8c991ea2018-07-31 13:33:01 -0700871 sbn.getId(), sbn.getNotification(), sbn.getUserId());
872 }
873 waitForIdle();
874 assertEquals(categories.size(), mBinderService.getActiveNotifications(PKG).length);
875 }
876
877
878 /**
879 * Confirm restricted notification categories only apply to automotive.
880 */
881 @Test
882 public void testEnqueuedRestrictedNotifications_notAutomotive() throws Exception {
883 mService.isSystemUid = false;
884 when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE, 0))
885 .thenReturn(false);
886 List<String> categories = Arrays.asList(Notification.CATEGORY_CAR_EMERGENCY,
887 Notification.CATEGORY_CAR_WARNING,
888 Notification.CATEGORY_CAR_INFORMATION);
889 int id = 0;
890 for (String category: categories) {
891 final StatusBarNotification sbn =
892 generateNotificationRecord(mTestNotificationChannel, ++id, "", false).sbn;
893 sbn.getNotification().category = category;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -0400894 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Brad Stenning8c991ea2018-07-31 13:33:01 -0700895 sbn.getId(), sbn.getNotification(), sbn.getUserId());
896 }
897 waitForIdle();
898 assertEquals(categories.size(), mBinderService.getActiveNotifications(PKG).length);
899 }
900
901 /**
902 * Confirm if a non-system user tries to use the car categories on a automotive device that
903 * they will get a security exception
904 */
905 @Test
906 public void testEnqueuedRestrictedNotifications_badUser() throws Exception {
907 mService.isSystemUid = false;
908 when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE, 0))
909 .thenReturn(true);
910 List<String> categories = Arrays.asList(Notification.CATEGORY_CAR_EMERGENCY,
911 Notification.CATEGORY_CAR_WARNING,
912 Notification.CATEGORY_CAR_INFORMATION);
913 for (String category: categories) {
914 final StatusBarNotification sbn = generateNotificationRecord(null).sbn;
915 sbn.getNotification().category = category;
916 try {
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -0400917 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Brad Stenning8c991ea2018-07-31 13:33:01 -0700918 sbn.getId(), sbn.getNotification(), sbn.getUserId());
919 fail("Calls from non system apps should not allow use of restricted categories");
920 } catch (SecurityException e) {
921 // pass
922 }
923 }
924 waitForIdle();
925 assertEquals(0, mBinderService.getActiveNotifications(PKG).length);
926 }
927
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400928 @Test
Julia Reynoldsefcdff42018-08-09 09:42:56 -0400929 public void testBlockedNotifications_blockedByAssistant() throws Exception {
930 when(mPackageManager.isPackageSuspendedForUser(anyString(), anyInt())).thenReturn(false);
Julia Reynolds27c0a962018-12-10 12:37:28 -0500931 when(mAssistants.isSameUser(any(), anyInt())).thenReturn(true);
Julia Reynoldsefcdff42018-08-09 09:42:56 -0400932
933 NotificationChannel channel = new NotificationChannel("id", "name",
934 NotificationManager.IMPORTANCE_HIGH);
935 NotificationRecord r = generateNotificationRecord(channel);
936 mService.addEnqueuedNotification(r);
937
Julia Reynolds27c0a962018-12-10 12:37:28 -0500938 Bundle bundle = new Bundle();
Julia Reynoldsc7dcdc22019-03-25 10:26:14 -0400939 bundle.putInt(KEY_IMPORTANCE, IMPORTANCE_NONE);
Julia Reynolds27c0a962018-12-10 12:37:28 -0500940 Adjustment adjustment = new Adjustment(
941 r.sbn.getPackageName(), r.getKey(), bundle, "", r.getUser().getIdentifier());
942 mBinderService.applyEnqueuedAdjustmentFromAssistant(null, adjustment);
Julia Reynoldsefcdff42018-08-09 09:42:56 -0400943
944 NotificationManagerService.PostNotificationRunnable runnable =
945 mService.new PostNotificationRunnable(r.getKey());
946 runnable.run();
947 waitForIdle();
948
949 verify(mUsageStats, never()).registerPostedByApp(any());
950 }
951
952 @Test
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500953 public void testEnqueueNotificationWithTag_PopulatesGetActiveNotifications() throws Exception {
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -0400954 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag", 0,
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -0400955 generateNotificationRecord(null).getNotification(), 0);
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500956 waitForIdle();
Julia Reynolds080361e2017-07-13 11:23:12 -0400957 StatusBarNotification[] notifs = mBinderService.getActiveNotifications(PKG);
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500958 assertEquals(1, notifs.length);
Julia Reynolds503ed942017-10-04 16:04:56 -0400959 assertEquals(1, mService.getNotificationRecordCount());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500960 }
961
Geoffrey Pitsch16594462017-01-26 14:42:30 -0500962 @Test
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500963 public void testCancelNotificationImmediatelyAfterEnqueue() throws Exception {
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -0400964 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag", 0,
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -0400965 generateNotificationRecord(null).getNotification(), 0);
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -0500966 mBinderService.cancelNotificationWithTag(PKG, "tag", 0, 0);
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500967 waitForIdle();
968 StatusBarNotification[] notifs =
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -0500969 mBinderService.getActiveNotifications(PKG);
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500970 assertEquals(0, notifs.length);
Julia Reynolds503ed942017-10-04 16:04:56 -0400971 assertEquals(0, mService.getNotificationRecordCount());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500972 }
973
Geoffrey Pitsch16594462017-01-26 14:42:30 -0500974 @Test
Geoffrey Pitschccc0b972017-02-15 10:52:26 -0500975 public void testCancelNotificationWhilePostedAndEnqueued() throws Exception {
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -0400976 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag", 0,
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -0400977 generateNotificationRecord(null).getNotification(), 0);
Geoffrey Pitschccc0b972017-02-15 10:52:26 -0500978 waitForIdle();
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -0400979 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag", 0,
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -0400980 generateNotificationRecord(null).getNotification(), 0);
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -0500981 mBinderService.cancelNotificationWithTag(PKG, "tag", 0, 0);
Geoffrey Pitschccc0b972017-02-15 10:52:26 -0500982 waitForIdle();
983 StatusBarNotification[] notifs =
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -0500984 mBinderService.getActiveNotifications(PKG);
Geoffrey Pitschccc0b972017-02-15 10:52:26 -0500985 assertEquals(0, notifs.length);
Julia Reynolds503ed942017-10-04 16:04:56 -0400986 assertEquals(0, mService.getNotificationRecordCount());
987 ArgumentCaptor<NotificationStats> captor = ArgumentCaptor.forClass(NotificationStats.class);
988 verify(mListeners, times(1)).notifyRemovedLocked(any(), anyInt(), captor.capture());
989 assertEquals(NotificationStats.DISMISSAL_OTHER, captor.getValue().getDismissalSurface());
Geoffrey Pitschccc0b972017-02-15 10:52:26 -0500990 }
991
992 @Test
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500993 public void testCancelNotificationsFromListenerImmediatelyAfterEnqueue() throws Exception {
Julia Reynolds503ed942017-10-04 16:04:56 -0400994 NotificationRecord r = generateNotificationRecord(null);
995 final StatusBarNotification sbn = r.sbn;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -0400996 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -0400997 sbn.getId(), sbn.getNotification(), sbn.getUserId());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500998 mBinderService.cancelNotificationsFromListener(null, null);
999 waitForIdle();
1000 StatusBarNotification[] notifs =
1001 mBinderService.getActiveNotifications(sbn.getPackageName());
1002 assertEquals(0, notifs.length);
Julia Reynolds503ed942017-10-04 16:04:56 -04001003 assertEquals(0, mService.getNotificationRecordCount());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001004 }
1005
Geoffrey Pitsch16594462017-01-26 14:42:30 -05001006 @Test
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001007 public void testCancelAllNotificationsImmediatelyAfterEnqueue() throws Exception {
1008 final StatusBarNotification sbn = generateNotificationRecord(null).sbn;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001009 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001010 sbn.getId(), sbn.getNotification(), sbn.getUserId());
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -05001011 mBinderService.cancelAllNotifications(PKG, sbn.getUserId());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001012 waitForIdle();
1013 StatusBarNotification[] notifs =
1014 mBinderService.getActiveNotifications(sbn.getPackageName());
1015 assertEquals(0, notifs.length);
Julia Reynolds503ed942017-10-04 16:04:56 -04001016 assertEquals(0, mService.getNotificationRecordCount());
Julia Reynolds080361e2017-07-13 11:23:12 -04001017 }
1018
1019 @Test
1020 public void testUserInitiatedClearAll_noLeak() throws Exception {
1021 final NotificationRecord n = generateNotificationRecord(
1022 mTestNotificationChannel, 1, "group", true);
1023
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001024 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Julia Reynolds080361e2017-07-13 11:23:12 -04001025 n.sbn.getId(), n.sbn.getNotification(), n.sbn.getUserId());
1026 waitForIdle();
1027
Julia Reynolds503ed942017-10-04 16:04:56 -04001028 mService.mNotificationDelegate.onClearAll(mUid, Binder.getCallingPid(),
Julia Reynolds080361e2017-07-13 11:23:12 -04001029 n.getUserId());
1030 waitForIdle();
1031 StatusBarNotification[] notifs =
1032 mBinderService.getActiveNotifications(n.sbn.getPackageName());
1033 assertEquals(0, notifs.length);
Julia Reynolds503ed942017-10-04 16:04:56 -04001034 assertEquals(0, mService.getNotificationRecordCount());
1035 ArgumentCaptor<NotificationStats> captor = ArgumentCaptor.forClass(NotificationStats.class);
1036 verify(mListeners, times(1)).notifyRemovedLocked(any(), anyInt(), captor.capture());
1037 assertEquals(NotificationStats.DISMISSAL_OTHER, captor.getValue().getDismissalSurface());
Julia Reynolds080361e2017-07-13 11:23:12 -04001038 }
1039
1040 @Test
1041 public void testCancelAllNotificationsCancelsChildren() throws Exception {
1042 final NotificationRecord parent = generateNotificationRecord(
1043 mTestNotificationChannel, 1, "group1", true);
1044 final NotificationRecord child = generateNotificationRecord(
1045 mTestNotificationChannel, 2, "group1", false);
1046
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001047 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Julia Reynolds080361e2017-07-13 11:23:12 -04001048 parent.sbn.getId(), parent.sbn.getNotification(), parent.sbn.getUserId());
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001049 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Julia Reynolds080361e2017-07-13 11:23:12 -04001050 child.sbn.getId(), child.sbn.getNotification(), child.sbn.getUserId());
1051 waitForIdle();
1052
1053 mBinderService.cancelAllNotifications(PKG, parent.sbn.getUserId());
1054 waitForIdle();
Julia Reynolds503ed942017-10-04 16:04:56 -04001055 assertEquals(0, mService.getNotificationRecordCount());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001056 }
1057
Geoffrey Pitsch16594462017-01-26 14:42:30 -05001058 @Test
Julia Reynolds0839c022017-06-15 15:24:01 -04001059 public void testCancelAllNotificationsMultipleEnqueuedDoesNotCrash() throws Exception {
1060 final StatusBarNotification sbn = generateNotificationRecord(null).sbn;
1061 for (int i = 0; i < 10; i++) {
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001062 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Julia Reynolds0839c022017-06-15 15:24:01 -04001063 sbn.getId(), sbn.getNotification(), sbn.getUserId());
1064 }
1065 mBinderService.cancelAllNotifications(PKG, sbn.getUserId());
1066 waitForIdle();
Julia Reynolds080361e2017-07-13 11:23:12 -04001067
Julia Reynolds503ed942017-10-04 16:04:56 -04001068 assertEquals(0, mService.getNotificationRecordCount());
Julia Reynolds0839c022017-06-15 15:24:01 -04001069 }
1070
1071 @Test
1072 public void testCancelGroupSummaryMultipleEnqueuedChildrenDoesNotCrash() throws Exception {
1073 final NotificationRecord parent = generateNotificationRecord(
1074 mTestNotificationChannel, 1, "group1", true);
1075 final NotificationRecord parentAsChild = generateNotificationRecord(
1076 mTestNotificationChannel, 1, "group1", false);
1077 final NotificationRecord child = generateNotificationRecord(
1078 mTestNotificationChannel, 2, "group1", false);
1079
1080 // fully post parent notification
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001081 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Julia Reynolds0839c022017-06-15 15:24:01 -04001082 parent.sbn.getId(), parent.sbn.getNotification(), parent.sbn.getUserId());
1083 waitForIdle();
1084
1085 // enqueue the child several times
1086 for (int i = 0; i < 10; i++) {
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001087 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Julia Reynolds0839c022017-06-15 15:24:01 -04001088 child.sbn.getId(), child.sbn.getNotification(), child.sbn.getUserId());
1089 }
1090 // make the parent a child, which will cancel the child notification
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001091 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Julia Reynolds0839c022017-06-15 15:24:01 -04001092 parentAsChild.sbn.getId(), parentAsChild.sbn.getNotification(),
1093 parentAsChild.sbn.getUserId());
1094 waitForIdle();
Julia Reynolds080361e2017-07-13 11:23:12 -04001095
Julia Reynolds503ed942017-10-04 16:04:56 -04001096 assertEquals(0, mService.getNotificationRecordCount());
Julia Reynolds0839c022017-06-15 15:24:01 -04001097 }
1098
1099 @Test
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001100 public void testCancelAllNotifications_IgnoreForegroundService() throws Exception {
1101 final StatusBarNotification sbn = generateNotificationRecord(null).sbn;
Julia Reynoldse5c60452018-04-30 14:41:36 -04001102 sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001103 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001104 sbn.getId(), sbn.getNotification(), sbn.getUserId());
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -05001105 mBinderService.cancelAllNotifications(PKG, sbn.getUserId());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001106 waitForIdle();
1107 StatusBarNotification[] notifs =
1108 mBinderService.getActiveNotifications(sbn.getPackageName());
1109 assertEquals(1, notifs.length);
Julia Reynolds503ed942017-10-04 16:04:56 -04001110 assertEquals(1, mService.getNotificationRecordCount());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001111 }
1112
Geoffrey Pitsch16594462017-01-26 14:42:30 -05001113 @Test
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001114 public void testCancelAllNotifications_IgnoreOtherPackages() throws Exception {
1115 final StatusBarNotification sbn = generateNotificationRecord(null).sbn;
Julia Reynoldse5c60452018-04-30 14:41:36 -04001116 sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001117 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001118 sbn.getId(), sbn.getNotification(), sbn.getUserId());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001119 mBinderService.cancelAllNotifications("other_pkg_name", sbn.getUserId());
1120 waitForIdle();
1121 StatusBarNotification[] notifs =
1122 mBinderService.getActiveNotifications(sbn.getPackageName());
1123 assertEquals(1, notifs.length);
Julia Reynolds503ed942017-10-04 16:04:56 -04001124 assertEquals(1, mService.getNotificationRecordCount());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001125 }
1126
Geoffrey Pitsch16594462017-01-26 14:42:30 -05001127 @Test
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001128 public void testCancelAllNotifications_NullPkgRemovesAll() throws Exception {
1129 final StatusBarNotification sbn = generateNotificationRecord(null).sbn;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001130 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001131 sbn.getId(), sbn.getNotification(), sbn.getUserId());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001132 mBinderService.cancelAllNotifications(null, sbn.getUserId());
1133 waitForIdle();
1134 StatusBarNotification[] notifs =
1135 mBinderService.getActiveNotifications(sbn.getPackageName());
1136 assertEquals(0, notifs.length);
Julia Reynolds503ed942017-10-04 16:04:56 -04001137 assertEquals(0, mService.getNotificationRecordCount());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001138 }
1139
Geoffrey Pitsch16594462017-01-26 14:42:30 -05001140 @Test
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001141 public void testCancelAllNotifications_NullPkgIgnoresUserAllNotifications() throws Exception {
1142 final StatusBarNotification sbn = generateNotificationRecord(null).sbn;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001143 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001144 sbn.getId(), sbn.getNotification(), UserHandle.USER_ALL);
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001145 // Null pkg is how we signal a user switch.
1146 mBinderService.cancelAllNotifications(null, sbn.getUserId());
1147 waitForIdle();
1148 StatusBarNotification[] notifs =
1149 mBinderService.getActiveNotifications(sbn.getPackageName());
1150 assertEquals(1, notifs.length);
Julia Reynolds503ed942017-10-04 16:04:56 -04001151 assertEquals(1, mService.getNotificationRecordCount());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001152 }
Julia Reynolds5f20e9f2017-01-30 08:54:53 -05001153
1154 @Test
Beverly40239d92017-07-07 10:20:41 -04001155 public void testAppInitiatedCancelAllNotifications_CancelsNoClearFlag() throws Exception {
1156 final StatusBarNotification sbn = generateNotificationRecord(null).sbn;
1157 sbn.getNotification().flags |= Notification.FLAG_NO_CLEAR;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001158 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Beverly40239d92017-07-07 10:20:41 -04001159 sbn.getId(), sbn.getNotification(), sbn.getUserId());
1160 mBinderService.cancelAllNotifications(PKG, sbn.getUserId());
1161 waitForIdle();
1162 StatusBarNotification[] notifs =
1163 mBinderService.getActiveNotifications(sbn.getPackageName());
1164 assertEquals(0, notifs.length);
1165 }
1166
1167 @Test
1168 public void testCancelAllNotifications_CancelsNoClearFlag() throws Exception {
1169 final NotificationRecord notif = generateNotificationRecord(
1170 mTestNotificationChannel, 1, "group", true);
1171 notif.getNotification().flags |= Notification.FLAG_NO_CLEAR;
Julia Reynolds503ed942017-10-04 16:04:56 -04001172 mService.addNotification(notif);
1173 mService.cancelAllNotificationsInt(mUid, 0, PKG, null, 0, 0, true,
Beverly40239d92017-07-07 10:20:41 -04001174 notif.getUserId(), 0, null);
1175 waitForIdle();
1176 StatusBarNotification[] notifs =
1177 mBinderService.getActiveNotifications(notif.sbn.getPackageName());
1178 assertEquals(0, notifs.length);
1179 }
1180
1181 @Test
1182 public void testUserInitiatedCancelAllOnClearAll_NoClearFlag() throws Exception {
1183 final NotificationRecord notif = generateNotificationRecord(
1184 mTestNotificationChannel, 1, "group", true);
1185 notif.getNotification().flags |= Notification.FLAG_NO_CLEAR;
Julia Reynolds503ed942017-10-04 16:04:56 -04001186 mService.addNotification(notif);
Beverly40239d92017-07-07 10:20:41 -04001187
Julia Reynolds503ed942017-10-04 16:04:56 -04001188 mService.mNotificationDelegate.onClearAll(mUid, Binder.getCallingPid(),
Beverly40239d92017-07-07 10:20:41 -04001189 notif.getUserId());
1190 waitForIdle();
1191 StatusBarNotification[] notifs =
1192 mBinderService.getActiveNotifications(notif.sbn.getPackageName());
1193 assertEquals(1, notifs.length);
1194 }
1195
1196 @Test
1197 public void testCancelAllCancelNotificationsFromListener_NoClearFlag() throws Exception {
1198 final NotificationRecord parent = generateNotificationRecord(
1199 mTestNotificationChannel, 1, "group", true);
1200 final NotificationRecord child = generateNotificationRecord(
1201 mTestNotificationChannel, 2, "group", false);
1202 final NotificationRecord child2 = generateNotificationRecord(
1203 mTestNotificationChannel, 3, "group", false);
1204 child2.getNotification().flags |= Notification.FLAG_NO_CLEAR;
1205 final NotificationRecord newGroup = generateNotificationRecord(
1206 mTestNotificationChannel, 4, "group2", false);
Julia Reynolds503ed942017-10-04 16:04:56 -04001207 mService.addNotification(parent);
1208 mService.addNotification(child);
1209 mService.addNotification(child2);
1210 mService.addNotification(newGroup);
1211 mService.getBinderService().cancelNotificationsFromListener(null, null);
Beverly40239d92017-07-07 10:20:41 -04001212 waitForIdle();
1213 StatusBarNotification[] notifs =
1214 mBinderService.getActiveNotifications(parent.sbn.getPackageName());
1215 assertEquals(1, notifs.length);
1216 }
1217
1218 @Test
1219 public void testUserInitiatedCancelAllWithGroup_NoClearFlag() throws Exception {
1220 final NotificationRecord parent = generateNotificationRecord(
1221 mTestNotificationChannel, 1, "group", true);
1222 final NotificationRecord child = generateNotificationRecord(
1223 mTestNotificationChannel, 2, "group", false);
1224 final NotificationRecord child2 = generateNotificationRecord(
1225 mTestNotificationChannel, 3, "group", false);
1226 child2.getNotification().flags |= Notification.FLAG_NO_CLEAR;
1227 final NotificationRecord newGroup = generateNotificationRecord(
1228 mTestNotificationChannel, 4, "group2", false);
Julia Reynolds503ed942017-10-04 16:04:56 -04001229 mService.addNotification(parent);
1230 mService.addNotification(child);
1231 mService.addNotification(child2);
1232 mService.addNotification(newGroup);
1233 mService.mNotificationDelegate.onClearAll(mUid, Binder.getCallingPid(),
Beverly40239d92017-07-07 10:20:41 -04001234 parent.getUserId());
1235 waitForIdle();
1236 StatusBarNotification[] notifs =
1237 mBinderService.getActiveNotifications(parent.sbn.getPackageName());
1238 assertEquals(1, notifs.length);
1239 }
1240
1241 @Test
Geoffrey Pitsch415e4542017-04-10 13:12:58 -04001242 public void testRemoveForegroundServiceFlag_ImmediatelyAfterEnqueue() throws Exception {
1243 final StatusBarNotification sbn = generateNotificationRecord(null).sbn;
Julia Reynoldse5c60452018-04-30 14:41:36 -04001244 sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001245 mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001246 sbn.getId(), sbn.getNotification(), sbn.getUserId());
Geoffrey Pitsch415e4542017-04-10 13:12:58 -04001247 mInternalService.removeForegroundServiceFlagFromNotification(PKG, sbn.getId(),
1248 sbn.getUserId());
1249 waitForIdle();
1250 StatusBarNotification[] notifs =
1251 mBinderService.getActiveNotifications(sbn.getPackageName());
Julia Reynoldse5c60452018-04-30 14:41:36 -04001252 assertEquals(0, notifs[0].getNotification().flags & FLAG_FOREGROUND_SERVICE);
Geoffrey Pitsch415e4542017-04-10 13:12:58 -04001253 }
1254
1255 @Test
Geoffrey Pitsch27684152017-05-02 11:41:31 -04001256 public void testCancelAfterSecondEnqueueDoesNotSpecifyForegroundFlag() throws Exception {
1257 final StatusBarNotification sbn = generateNotificationRecord(null).sbn;
1258 sbn.getNotification().flags =
Julia Reynoldse5c60452018-04-30 14:41:36 -04001259 Notification.FLAG_ONGOING_EVENT | FLAG_FOREGROUND_SERVICE;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001260 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Geoffrey Pitsch27684152017-05-02 11:41:31 -04001261 sbn.getId(), sbn.getNotification(), sbn.getUserId());
1262 sbn.getNotification().flags = Notification.FLAG_ONGOING_EVENT;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001263 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Geoffrey Pitsch27684152017-05-02 11:41:31 -04001264 sbn.getId(), sbn.getNotification(), sbn.getUserId());
1265 mBinderService.cancelNotificationWithTag(PKG, "tag", sbn.getId(), sbn.getUserId());
1266 waitForIdle();
1267 assertEquals(0, mBinderService.getActiveNotifications(sbn.getPackageName()).length);
Julia Reynolds503ed942017-10-04 16:04:56 -04001268 assertEquals(0, mService.getNotificationRecordCount());
Geoffrey Pitsch27684152017-05-02 11:41:31 -04001269 }
1270
1271 @Test
Julia Reynolds40f00d72017-12-12 10:47:32 -05001272 public void testCancelAllCancelNotificationsFromListener_ForegroundServiceFlag()
1273 throws Exception {
1274 final NotificationRecord parent = generateNotificationRecord(
1275 mTestNotificationChannel, 1, "group", true);
1276 final NotificationRecord child = generateNotificationRecord(
1277 mTestNotificationChannel, 2, "group", false);
1278 final NotificationRecord child2 = generateNotificationRecord(
1279 mTestNotificationChannel, 3, "group", false);
Julia Reynoldse5c60452018-04-30 14:41:36 -04001280 child2.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
Julia Reynolds40f00d72017-12-12 10:47:32 -05001281 final NotificationRecord newGroup = generateNotificationRecord(
1282 mTestNotificationChannel, 4, "group2", false);
1283 mService.addNotification(parent);
1284 mService.addNotification(child);
1285 mService.addNotification(child2);
1286 mService.addNotification(newGroup);
1287 mService.getBinderService().cancelNotificationsFromListener(null, null);
1288 waitForIdle();
1289 StatusBarNotification[] notifs =
1290 mBinderService.getActiveNotifications(parent.sbn.getPackageName());
1291 assertEquals(0, notifs.length);
1292 }
1293
1294 @Test
1295 public void testCancelAllCancelNotificationsFromListener_ForegroundServiceFlagWithParameter()
1296 throws Exception {
1297 final NotificationRecord parent = generateNotificationRecord(
1298 mTestNotificationChannel, 1, "group", true);
1299 final NotificationRecord child = generateNotificationRecord(
1300 mTestNotificationChannel, 2, "group", false);
1301 final NotificationRecord child2 = generateNotificationRecord(
1302 mTestNotificationChannel, 3, "group", false);
Julia Reynoldse5c60452018-04-30 14:41:36 -04001303 child2.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
Julia Reynolds40f00d72017-12-12 10:47:32 -05001304 final NotificationRecord newGroup = generateNotificationRecord(
1305 mTestNotificationChannel, 4, "group2", false);
1306 mService.addNotification(parent);
1307 mService.addNotification(child);
1308 mService.addNotification(child2);
1309 mService.addNotification(newGroup);
1310 String[] keys = {parent.sbn.getKey(), child.sbn.getKey(),
1311 child2.sbn.getKey(), newGroup.sbn.getKey()};
1312 mService.getBinderService().cancelNotificationsFromListener(null, keys);
1313 waitForIdle();
1314 StatusBarNotification[] notifs =
1315 mBinderService.getActiveNotifications(parent.sbn.getPackageName());
1316 assertEquals(1, notifs.length);
1317 }
1318
1319 @Test
1320 public void testUserInitiatedCancelAllWithGroup_ForegroundServiceFlag() throws Exception {
1321 final NotificationRecord parent = generateNotificationRecord(
1322 mTestNotificationChannel, 1, "group", true);
1323 final NotificationRecord child = generateNotificationRecord(
1324 mTestNotificationChannel, 2, "group", false);
1325 final NotificationRecord child2 = generateNotificationRecord(
1326 mTestNotificationChannel, 3, "group", false);
Julia Reynoldse5c60452018-04-30 14:41:36 -04001327 child2.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
Julia Reynolds40f00d72017-12-12 10:47:32 -05001328 final NotificationRecord newGroup = generateNotificationRecord(
1329 mTestNotificationChannel, 4, "group2", false);
1330 mService.addNotification(parent);
1331 mService.addNotification(child);
1332 mService.addNotification(child2);
1333 mService.addNotification(newGroup);
1334 mService.mNotificationDelegate.onClearAll(mUid, Binder.getCallingPid(),
1335 parent.getUserId());
1336 waitForIdle();
1337 StatusBarNotification[] notifs =
1338 mBinderService.getActiveNotifications(parent.sbn.getPackageName());
1339 assertEquals(0, notifs.length);
1340 }
1341
1342 @Test
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04001343 public void testFindGroupNotificationsLocked() throws Exception {
1344 // make sure the same notification can be found in both lists and returned
1345 final NotificationRecord group1 = generateNotificationRecord(
1346 mTestNotificationChannel, 1, "group1", true);
Julia Reynolds503ed942017-10-04 16:04:56 -04001347 mService.addEnqueuedNotification(group1);
1348 mService.addNotification(group1);
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04001349
1350 // should not be returned
1351 final NotificationRecord group2 = generateNotificationRecord(
1352 mTestNotificationChannel, 2, "group2", true);
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001353 mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04001354 group2.sbn.getId(), group2.sbn.getNotification(), group2.sbn.getUserId());
1355 waitForIdle();
1356
1357 // should not be returned
1358 final NotificationRecord nonGroup = generateNotificationRecord(
1359 mTestNotificationChannel, 3, null, false);
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001360 mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04001361 nonGroup.sbn.getId(), nonGroup.sbn.getNotification(), nonGroup.sbn.getUserId());
1362 waitForIdle();
1363
1364 // same group, child, should be returned
1365 final NotificationRecord group1Child = generateNotificationRecord(
1366 mTestNotificationChannel, 4, "group1", false);
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001367 mBinderService.enqueueNotificationWithTag(PKG, PKG, null, group1Child.sbn.getId(),
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04001368 group1Child.sbn.getNotification(), group1Child.sbn.getUserId());
1369 waitForIdle();
1370
1371 List<NotificationRecord> inGroup1 =
Julia Reynolds503ed942017-10-04 16:04:56 -04001372 mService.findGroupNotificationsLocked(PKG, group1.getGroupKey(),
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04001373 group1.sbn.getUserId());
1374 assertEquals(3, inGroup1.size());
1375 for (NotificationRecord record : inGroup1) {
1376 assertTrue(record.getGroupKey().equals(group1.getGroupKey()));
1377 assertTrue(record.sbn.getId() == 1 || record.sbn.getId() == 4);
1378 }
1379 }
1380
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04001381 @Test
Julia Reynolds40f00d72017-12-12 10:47:32 -05001382 public void testCancelAllNotifications_CancelsNoClearFlagOnGoing() throws Exception {
1383 final NotificationRecord notif = generateNotificationRecord(
1384 mTestNotificationChannel, 1, "group", true);
1385 notif.getNotification().flags |= Notification.FLAG_NO_CLEAR;
1386 mService.addNotification(notif);
1387 mService.cancelAllNotificationsInt(mUid, 0, PKG, null, 0,
1388 Notification.FLAG_ONGOING_EVENT, true, notif.getUserId(), 0, null);
1389 waitForIdle();
1390 StatusBarNotification[] notifs =
1391 mBinderService.getActiveNotifications(notif.sbn.getPackageName());
1392 assertEquals(0, notifs.length);
1393 }
1394
1395 @Test
1396 public void testCancelAllCancelNotificationsFromListener_NoClearFlagWithParameter()
1397 throws Exception {
1398 final NotificationRecord parent = generateNotificationRecord(
1399 mTestNotificationChannel, 1, "group", true);
1400 final NotificationRecord child = generateNotificationRecord(
1401 mTestNotificationChannel, 2, "group", false);
1402 final NotificationRecord child2 = generateNotificationRecord(
1403 mTestNotificationChannel, 3, "group", false);
1404 child2.getNotification().flags |= Notification.FLAG_NO_CLEAR;
1405 final NotificationRecord newGroup = generateNotificationRecord(
1406 mTestNotificationChannel, 4, "group2", false);
1407 mService.addNotification(parent);
1408 mService.addNotification(child);
1409 mService.addNotification(child2);
1410 mService.addNotification(newGroup);
1411 String[] keys = {parent.sbn.getKey(), child.sbn.getKey(),
1412 child2.sbn.getKey(), newGroup.sbn.getKey()};
1413 mService.getBinderService().cancelNotificationsFromListener(null, keys);
1414 waitForIdle();
1415 StatusBarNotification[] notifs =
1416 mBinderService.getActiveNotifications(parent.sbn.getPackageName());
1417 assertEquals(0, notifs.length);
1418 }
1419
1420 @Test
1421 public void testAppInitiatedCancelAllNotifications_CancelsOnGoingFlag() throws Exception {
1422 final StatusBarNotification sbn = generateNotificationRecord(null).sbn;
1423 sbn.getNotification().flags |= Notification.FLAG_ONGOING_EVENT;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001424 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Julia Reynolds40f00d72017-12-12 10:47:32 -05001425 sbn.getId(), sbn.getNotification(), sbn.getUserId());
1426 mBinderService.cancelAllNotifications(PKG, sbn.getUserId());
1427 waitForIdle();
1428 StatusBarNotification[] notifs =
1429 mBinderService.getActiveNotifications(sbn.getPackageName());
1430 assertEquals(0, notifs.length);
1431 }
1432
1433 @Test
1434 public void testCancelAllNotifications_CancelsOnGoingFlag() throws Exception {
1435 final NotificationRecord notif = generateNotificationRecord(
1436 mTestNotificationChannel, 1, "group", true);
1437 notif.getNotification().flags |= Notification.FLAG_ONGOING_EVENT;
1438 mService.addNotification(notif);
1439 mService.cancelAllNotificationsInt(mUid, 0, PKG, null, 0, 0, true,
1440 notif.getUserId(), 0, null);
1441 waitForIdle();
1442 StatusBarNotification[] notifs =
1443 mBinderService.getActiveNotifications(notif.sbn.getPackageName());
1444 assertEquals(0, notifs.length);
1445 }
1446
1447 @Test
1448 public void testUserInitiatedCancelAllOnClearAll_OnGoingFlag() throws Exception {
1449 final NotificationRecord notif = generateNotificationRecord(
1450 mTestNotificationChannel, 1, "group", true);
1451 notif.getNotification().flags |= Notification.FLAG_ONGOING_EVENT;
1452 mService.addNotification(notif);
1453
1454 mService.mNotificationDelegate.onClearAll(mUid, Binder.getCallingPid(),
1455 notif.getUserId());
1456 waitForIdle();
1457 StatusBarNotification[] notifs =
1458 mBinderService.getActiveNotifications(notif.sbn.getPackageName());
1459 assertEquals(1, notifs.length);
1460 }
1461
1462 @Test
1463 public void testCancelAllCancelNotificationsFromListener_OnGoingFlag() throws Exception {
1464 final NotificationRecord parent = generateNotificationRecord(
1465 mTestNotificationChannel, 1, "group", true);
1466 final NotificationRecord child = generateNotificationRecord(
1467 mTestNotificationChannel, 2, "group", false);
1468 final NotificationRecord child2 = generateNotificationRecord(
1469 mTestNotificationChannel, 3, "group", false);
1470 child2.getNotification().flags |= Notification.FLAG_ONGOING_EVENT;
1471 final NotificationRecord newGroup = generateNotificationRecord(
1472 mTestNotificationChannel, 4, "group2", false);
1473 mService.addNotification(parent);
1474 mService.addNotification(child);
1475 mService.addNotification(child2);
1476 mService.addNotification(newGroup);
1477 mService.getBinderService().cancelNotificationsFromListener(null, null);
1478 waitForIdle();
1479 StatusBarNotification[] notifs =
1480 mBinderService.getActiveNotifications(parent.sbn.getPackageName());
1481 assertEquals(1, notifs.length);
1482 }
1483
1484 @Test
1485 public void testCancelAllCancelNotificationsFromListener_OnGoingFlagWithParameter()
1486 throws Exception {
1487 final NotificationRecord parent = generateNotificationRecord(
1488 mTestNotificationChannel, 1, "group", true);
1489 final NotificationRecord child = generateNotificationRecord(
1490 mTestNotificationChannel, 2, "group", false);
1491 final NotificationRecord child2 = generateNotificationRecord(
1492 mTestNotificationChannel, 3, "group", false);
1493 child2.getNotification().flags |= Notification.FLAG_ONGOING_EVENT;
1494 final NotificationRecord newGroup = generateNotificationRecord(
1495 mTestNotificationChannel, 4, "group2", false);
1496 mService.addNotification(parent);
1497 mService.addNotification(child);
1498 mService.addNotification(child2);
1499 mService.addNotification(newGroup);
1500 String[] keys = {parent.sbn.getKey(), child.sbn.getKey(),
1501 child2.sbn.getKey(), newGroup.sbn.getKey()};
1502 mService.getBinderService().cancelNotificationsFromListener(null, keys);
1503 waitForIdle();
1504 StatusBarNotification[] notifs =
1505 mBinderService.getActiveNotifications(parent.sbn.getPackageName());
1506 assertEquals(0, notifs.length);
1507 }
1508
1509 @Test
1510 public void testUserInitiatedCancelAllWithGroup_OnGoingFlag() throws Exception {
1511 final NotificationRecord parent = generateNotificationRecord(
1512 mTestNotificationChannel, 1, "group", true);
1513 final NotificationRecord child = generateNotificationRecord(
1514 mTestNotificationChannel, 2, "group", false);
1515 final NotificationRecord child2 = generateNotificationRecord(
1516 mTestNotificationChannel, 3, "group", false);
1517 child2.getNotification().flags |= Notification.FLAG_ONGOING_EVENT;
1518 final NotificationRecord newGroup = generateNotificationRecord(
1519 mTestNotificationChannel, 4, "group2", false);
1520 mService.addNotification(parent);
1521 mService.addNotification(child);
1522 mService.addNotification(child2);
1523 mService.addNotification(newGroup);
1524 mService.mNotificationDelegate.onClearAll(mUid, Binder.getCallingPid(),
1525 parent.getUserId());
1526 waitForIdle();
1527 StatusBarNotification[] notifs =
1528 mBinderService.getActiveNotifications(parent.sbn.getPackageName());
1529 assertEquals(1, notifs.length);
1530 }
1531
1532 @Test
Julia Reynolds5f20e9f2017-01-30 08:54:53 -05001533 public void testTvExtenderChannelOverride_onTv() throws Exception {
Julia Reynolds503ed942017-10-04 16:04:56 -04001534 mService.setIsTelevision(true);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001535 mService.setPreferencesHelper(mPreferencesHelper);
1536 when(mPreferencesHelper.getNotificationChannel(
Julia Reynolds5f20e9f2017-01-30 08:54:53 -05001537 anyString(), anyInt(), eq("foo"), anyBoolean())).thenReturn(
Julia Reynolds8617e4e2017-09-18 16:52:37 -04001538 new NotificationChannel("foo", "foo", IMPORTANCE_HIGH));
Julia Reynolds5f20e9f2017-01-30 08:54:53 -05001539
Julia Reynoldsbad42972017-04-25 13:52:49 -04001540 Notification.TvExtender tv = new Notification.TvExtender().setChannelId("foo");
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001541 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag", 0,
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001542 generateNotificationRecord(null, tv).getNotification(), 0);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001543 verify(mPreferencesHelper, times(1)).getNotificationChannel(
Julia Reynolds5f20e9f2017-01-30 08:54:53 -05001544 anyString(), anyInt(), eq("foo"), anyBoolean());
1545 }
1546
1547 @Test
Julia Reynolds5f20e9f2017-01-30 08:54:53 -05001548 public void testTvExtenderChannelOverride_notOnTv() throws Exception {
Julia Reynolds503ed942017-10-04 16:04:56 -04001549 mService.setIsTelevision(false);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001550 mService.setPreferencesHelper(mPreferencesHelper);
1551 when(mPreferencesHelper.getNotificationChannel(
Julia Reynolds5f20e9f2017-01-30 08:54:53 -05001552 anyString(), anyInt(), anyString(), anyBoolean())).thenReturn(
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -05001553 mTestNotificationChannel);
Julia Reynolds5f20e9f2017-01-30 08:54:53 -05001554
Julia Reynoldsbad42972017-04-25 13:52:49 -04001555 Notification.TvExtender tv = new Notification.TvExtender().setChannelId("foo");
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001556 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag", 0,
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001557 generateNotificationRecord(null, tv).getNotification(), 0);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001558 verify(mPreferencesHelper, times(1)).getNotificationChannel(
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -05001559 anyString(), anyInt(), eq(mTestNotificationChannel.getId()), anyBoolean());
Julia Reynolds5f20e9f2017-01-30 08:54:53 -05001560 }
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001561
1562 @Test
Julia Reynoldsfc9767b2018-01-22 17:45:16 -05001563 public void testUpdateAppNotifyCreatorBlock() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001564 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynoldsfc9767b2018-01-22 17:45:16 -05001565
1566 mBinderService.setNotificationsEnabledForPackage(PKG, 0, false);
1567 ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
1568 verify(mContext, times(1)).sendBroadcastAsUser(captor.capture(), any(), eq(null));
1569
1570 assertEquals(NotificationManager.ACTION_APP_BLOCK_STATE_CHANGED,
1571 captor.getValue().getAction());
1572 assertEquals(PKG, captor.getValue().getPackage());
1573 assertTrue(captor.getValue().getBooleanExtra(EXTRA_BLOCKED_STATE, false));
1574 }
1575
1576 @Test
1577 public void testUpdateAppNotifyCreatorUnblock() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001578 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynoldsfc9767b2018-01-22 17:45:16 -05001579
1580 mBinderService.setNotificationsEnabledForPackage(PKG, 0, true);
1581 ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
1582 verify(mContext, times(1)).sendBroadcastAsUser(captor.capture(), any(), eq(null));
1583
1584 assertEquals(NotificationManager.ACTION_APP_BLOCK_STATE_CHANGED,
1585 captor.getValue().getAction());
1586 assertEquals(PKG, captor.getValue().getPackage());
1587 assertFalse(captor.getValue().getBooleanExtra(EXTRA_BLOCKED_STATE, true));
1588 }
1589
1590 @Test
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05001591 public void testUpdateChannelNotifyCreatorBlock() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001592 mService.setPreferencesHelper(mPreferencesHelper);
1593 when(mPreferencesHelper.getNotificationChannel(eq(PKG), anyInt(),
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05001594 eq(mTestNotificationChannel.getId()), anyBoolean()))
1595 .thenReturn(mTestNotificationChannel);
1596
1597 NotificationChannel updatedChannel =
1598 new NotificationChannel(mTestNotificationChannel.getId(),
1599 mTestNotificationChannel.getName(), IMPORTANCE_NONE);
1600
1601 mBinderService.updateNotificationChannelForPackage(PKG, 0, updatedChannel);
1602 ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
1603 verify(mContext, times(1)).sendBroadcastAsUser(captor.capture(), any(), eq(null));
1604
1605 assertEquals(NotificationManager.ACTION_NOTIFICATION_CHANNEL_BLOCK_STATE_CHANGED,
1606 captor.getValue().getAction());
1607 assertEquals(PKG, captor.getValue().getPackage());
1608 assertEquals(mTestNotificationChannel.getId(), captor.getValue().getStringExtra(
Julia Reynolds44ff7c92018-02-05 10:02:30 -05001609 NotificationManager.EXTRA_NOTIFICATION_CHANNEL_ID));
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05001610 assertTrue(captor.getValue().getBooleanExtra(EXTRA_BLOCKED_STATE, false));
1611 }
1612
1613 @Test
1614 public void testUpdateChannelNotifyCreatorUnblock() throws Exception {
1615 NotificationChannel existingChannel =
1616 new NotificationChannel(mTestNotificationChannel.getId(),
1617 mTestNotificationChannel.getName(), IMPORTANCE_NONE);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001618 mService.setPreferencesHelper(mPreferencesHelper);
1619 when(mPreferencesHelper.getNotificationChannel(eq(PKG), anyInt(),
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05001620 eq(mTestNotificationChannel.getId()), anyBoolean()))
1621 .thenReturn(existingChannel);
1622
1623 mBinderService.updateNotificationChannelForPackage(PKG, 0, mTestNotificationChannel);
1624 ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
1625 verify(mContext, times(1)).sendBroadcastAsUser(captor.capture(), any(), eq(null));
1626
1627 assertEquals(NotificationManager.ACTION_NOTIFICATION_CHANNEL_BLOCK_STATE_CHANGED,
1628 captor.getValue().getAction());
1629 assertEquals(PKG, captor.getValue().getPackage());
1630 assertEquals(mTestNotificationChannel.getId(), captor.getValue().getStringExtra(
Julia Reynolds44ff7c92018-02-05 10:02:30 -05001631 NotificationManager.EXTRA_NOTIFICATION_CHANNEL_ID));
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05001632 assertFalse(captor.getValue().getBooleanExtra(EXTRA_BLOCKED_STATE, false));
1633 }
1634
1635 @Test
1636 public void testUpdateChannelNoNotifyCreatorOtherChanges() throws Exception {
1637 NotificationChannel existingChannel =
1638 new NotificationChannel(mTestNotificationChannel.getId(),
1639 mTestNotificationChannel.getName(), IMPORTANCE_MAX);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001640 mService.setPreferencesHelper(mPreferencesHelper);
1641 when(mPreferencesHelper.getNotificationChannel(eq(PKG), anyInt(),
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05001642 eq(mTestNotificationChannel.getId()), anyBoolean()))
1643 .thenReturn(existingChannel);
1644
1645 mBinderService.updateNotificationChannelForPackage(PKG, 0, mTestNotificationChannel);
1646 verify(mContext, never()).sendBroadcastAsUser(any(), any(), eq(null));
1647 }
1648
1649 @Test
1650 public void testUpdateGroupNotifyCreatorBlock() throws Exception {
1651 NotificationChannelGroup existing = new NotificationChannelGroup("id", "name");
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001652 mService.setPreferencesHelper(mPreferencesHelper);
1653 when(mPreferencesHelper.getNotificationChannelGroup(eq(existing.getId()), eq(PKG), anyInt()))
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05001654 .thenReturn(existing);
1655
1656 NotificationChannelGroup updated = new NotificationChannelGroup("id", "name");
1657 updated.setBlocked(true);
1658
1659 mBinderService.updateNotificationChannelGroupForPackage(PKG, 0, updated);
1660 ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
1661 verify(mContext, times(1)).sendBroadcastAsUser(captor.capture(), any(), eq(null));
1662
1663 assertEquals(NotificationManager.ACTION_NOTIFICATION_CHANNEL_GROUP_BLOCK_STATE_CHANGED,
1664 captor.getValue().getAction());
1665 assertEquals(PKG, captor.getValue().getPackage());
1666 assertEquals(existing.getId(), captor.getValue().getStringExtra(
Julia Reynolds44ff7c92018-02-05 10:02:30 -05001667 NotificationManager.EXTRA_NOTIFICATION_CHANNEL_GROUP_ID));
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05001668 assertTrue(captor.getValue().getBooleanExtra(EXTRA_BLOCKED_STATE, false));
1669 }
1670
1671 @Test
1672 public void testUpdateGroupNotifyCreatorUnblock() throws Exception {
1673 NotificationChannelGroup existing = new NotificationChannelGroup("id", "name");
1674 existing.setBlocked(true);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001675 mService.setPreferencesHelper(mPreferencesHelper);
1676 when(mPreferencesHelper.getNotificationChannelGroup(eq(existing.getId()), eq(PKG), anyInt()))
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05001677 .thenReturn(existing);
1678
1679 mBinderService.updateNotificationChannelGroupForPackage(
1680 PKG, 0, new NotificationChannelGroup("id", "name"));
1681 ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
1682 verify(mContext, times(1)).sendBroadcastAsUser(captor.capture(), any(), eq(null));
1683
1684 assertEquals(NotificationManager.ACTION_NOTIFICATION_CHANNEL_GROUP_BLOCK_STATE_CHANGED,
1685 captor.getValue().getAction());
1686 assertEquals(PKG, captor.getValue().getPackage());
1687 assertEquals(existing.getId(), captor.getValue().getStringExtra(
Julia Reynolds44ff7c92018-02-05 10:02:30 -05001688 NotificationManager.EXTRA_NOTIFICATION_CHANNEL_GROUP_ID));
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05001689 assertFalse(captor.getValue().getBooleanExtra(EXTRA_BLOCKED_STATE, false));
1690 }
1691
1692 @Test
1693 public void testUpdateGroupNoNotifyCreatorOtherChanges() throws Exception {
1694 NotificationChannelGroup existing = new NotificationChannelGroup("id", "name");
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001695 mService.setPreferencesHelper(mPreferencesHelper);
1696 when(mPreferencesHelper.getNotificationChannelGroup(eq(existing.getId()), eq(PKG), anyInt()))
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05001697 .thenReturn(existing);
1698
1699 mBinderService.updateNotificationChannelGroupForPackage(
1700 PKG, 0, new NotificationChannelGroup("id", "new name"));
1701 verify(mContext, never()).sendBroadcastAsUser(any(), any(), eq(null));
1702 }
1703
1704 @Test
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001705 public void testCreateChannelNotifyListener() throws Exception {
1706 List<String> associations = new ArrayList<>();
1707 associations.add("a");
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04001708 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001709 mService.setPreferencesHelper(mPreferencesHelper);
1710 when(mPreferencesHelper.getNotificationChannel(eq(PKG), anyInt(),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001711 eq(mTestNotificationChannel.getId()), anyBoolean()))
1712 .thenReturn(mTestNotificationChannel);
1713 NotificationChannel channel2 = new NotificationChannel("a", "b", IMPORTANCE_LOW);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001714 when(mPreferencesHelper.getNotificationChannel(eq(PKG), anyInt(),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001715 eq(channel2.getId()), anyBoolean()))
1716 .thenReturn(channel2);
Julia Reynoldsdafd3a42019-05-24 13:33:28 -04001717 when(mPreferencesHelper.createNotificationChannel(eq(PKG), anyInt(),
1718 eq(channel2), anyBoolean(), anyBoolean()))
1719 .thenReturn(true);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001720
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04001721 reset(mListeners);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001722 mBinderService.createNotificationChannels(PKG,
1723 new ParceledListSlice(Arrays.asList(mTestNotificationChannel, channel2)));
Julia Reynoldsdafd3a42019-05-24 13:33:28 -04001724 verify(mListeners, never()).notifyNotificationChannelChanged(eq(PKG),
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001725 eq(Process.myUserHandle()), eq(mTestNotificationChannel),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001726 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_ADDED));
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04001727 verify(mListeners, times(1)).notifyNotificationChannelChanged(eq(PKG),
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001728 eq(Process.myUserHandle()), eq(channel2),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001729 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_ADDED));
1730 }
1731
1732 @Test
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001733 public void testCreateChannelGroupNotifyListener() throws Exception {
1734 List<String> associations = new ArrayList<>();
1735 associations.add("a");
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04001736 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001737 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001738 NotificationChannelGroup group1 = new NotificationChannelGroup("a", "b");
1739 NotificationChannelGroup group2 = new NotificationChannelGroup("n", "m");
1740
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04001741 reset(mListeners);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001742 mBinderService.createNotificationChannelGroups(PKG,
1743 new ParceledListSlice(Arrays.asList(group1, group2)));
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04001744 verify(mListeners, times(1)).notifyNotificationChannelGroupChanged(eq(PKG),
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001745 eq(Process.myUserHandle()), eq(group1),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001746 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_ADDED));
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04001747 verify(mListeners, times(1)).notifyNotificationChannelGroupChanged(eq(PKG),
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001748 eq(Process.myUserHandle()), eq(group2),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001749 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_ADDED));
1750 }
1751
1752 @Test
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001753 public void testUpdateChannelNotifyListener() throws Exception {
1754 List<String> associations = new ArrayList<>();
1755 associations.add("a");
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04001756 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001757 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001758 mTestNotificationChannel.setLightColor(Color.CYAN);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001759 when(mPreferencesHelper.getNotificationChannel(eq(PKG), anyInt(),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001760 eq(mTestNotificationChannel.getId()), anyBoolean()))
1761 .thenReturn(mTestNotificationChannel);
1762
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04001763 reset(mListeners);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001764 mBinderService.updateNotificationChannelForPackage(PKG, 0, mTestNotificationChannel);
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04001765 verify(mListeners, times(1)).notifyNotificationChannelChanged(eq(PKG),
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001766 eq(Process.myUserHandle()), eq(mTestNotificationChannel),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001767 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_UPDATED));
1768 }
1769
1770 @Test
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001771 public void testDeleteChannelNotifyListener() throws Exception {
1772 List<String> associations = new ArrayList<>();
1773 associations.add("a");
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04001774 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001775 mService.setPreferencesHelper(mPreferencesHelper);
1776 when(mPreferencesHelper.getNotificationChannel(eq(PKG), anyInt(),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001777 eq(mTestNotificationChannel.getId()), anyBoolean()))
1778 .thenReturn(mTestNotificationChannel);
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04001779 reset(mListeners);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001780 mBinderService.deleteNotificationChannel(PKG, mTestNotificationChannel.getId());
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04001781 verify(mListeners, times(1)).notifyNotificationChannelChanged(eq(PKG),
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001782 eq(Process.myUserHandle()), eq(mTestNotificationChannel),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001783 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_DELETED));
1784 }
1785
1786 @Test
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001787 public void testDeleteChannelGroupNotifyListener() throws Exception {
1788 List<String> associations = new ArrayList<>();
1789 associations.add("a");
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04001790 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001791 NotificationChannelGroup ncg = new NotificationChannelGroup("a", "b/c");
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001792 mService.setPreferencesHelper(mPreferencesHelper);
1793 when(mPreferencesHelper.getNotificationChannelGroup(eq(ncg.getId()), eq(PKG), anyInt()))
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001794 .thenReturn(ncg);
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04001795 reset(mListeners);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001796 mBinderService.deleteNotificationChannelGroup(PKG, ncg.getId());
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04001797 verify(mListeners, times(1)).notifyNotificationChannelGroupChanged(eq(PKG),
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001798 eq(Process.myUserHandle()), eq(ncg),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001799 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_DELETED));
1800 }
1801
1802 @Test
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001803 public void testUpdateNotificationChannelFromPrivilegedListener_success() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001804 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001805 List<String> associations = new ArrayList<>();
1806 associations.add("a");
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04001807 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001808 when(mPreferencesHelper.getNotificationChannel(eq(PKG), anyInt(),
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05001809 eq(mTestNotificationChannel.getId()), anyBoolean()))
1810 .thenReturn(mTestNotificationChannel);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001811
1812 mBinderService.updateNotificationChannelFromPrivilegedListener(
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001813 null, PKG, Process.myUserHandle(), mTestNotificationChannel);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001814
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001815 verify(mPreferencesHelper, times(1)).updateNotificationChannel(
Julia Reynolds8617e4e2017-09-18 16:52:37 -04001816 anyString(), anyInt(), any(), anyBoolean());
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001817
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04001818 verify(mListeners, never()).notifyNotificationChannelChanged(eq(PKG),
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001819 eq(Process.myUserHandle()), eq(mTestNotificationChannel),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001820 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_UPDATED));
1821 }
1822
1823 @Test
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001824 public void testUpdateNotificationChannelFromPrivilegedListener_noAccess() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001825 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001826 List<String> associations = new ArrayList<>();
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04001827 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001828
1829 try {
1830 mBinderService.updateNotificationChannelFromPrivilegedListener(
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001831 null, PKG, Process.myUserHandle(), mTestNotificationChannel);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001832 fail("listeners that don't have a companion device shouldn't be able to call this");
1833 } catch (SecurityException e) {
1834 // pass
1835 }
1836
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001837 verify(mPreferencesHelper, never()).updateNotificationChannel(
Julia Reynolds8617e4e2017-09-18 16:52:37 -04001838 anyString(), anyInt(), any(), anyBoolean());
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001839
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04001840 verify(mListeners, never()).notifyNotificationChannelChanged(eq(PKG),
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001841 eq(Process.myUserHandle()), eq(mTestNotificationChannel),
1842 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_UPDATED));
1843 }
1844
1845 @Test
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001846 public void testUpdateNotificationChannelFromPrivilegedListener_badUser() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001847 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001848 List<String> associations = new ArrayList<>();
1849 associations.add("a");
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04001850 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001851 mListener = mock(ManagedServices.ManagedServiceInfo.class);
Julia Reynolds4da79702017-06-01 11:06:10 -04001852 mListener.component = new ComponentName(PKG, PKG);
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001853 when(mListener.enabledAndUserMatches(anyInt())).thenReturn(false);
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04001854 when(mListeners.checkServiceTokenLocked(any())).thenReturn(mListener);
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001855
1856 try {
1857 mBinderService.updateNotificationChannelFromPrivilegedListener(
1858 null, PKG, UserHandle.ALL, mTestNotificationChannel);
1859 fail("incorrectly allowed a change to a user listener cannot see");
1860 } catch (SecurityException e) {
1861 // pass
1862 }
1863
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001864 verify(mPreferencesHelper, never()).updateNotificationChannel(
Julia Reynolds8617e4e2017-09-18 16:52:37 -04001865 anyString(), anyInt(), any(), anyBoolean());
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001866
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04001867 verify(mListeners, never()).notifyNotificationChannelChanged(eq(PKG),
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001868 eq(Process.myUserHandle()), eq(mTestNotificationChannel),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001869 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_UPDATED));
1870 }
1871
1872 @Test
Julia Reynolds48a6ed92018-10-22 12:52:03 -04001873 public void testGetNotificationChannelFromPrivilegedListener_cdm_success() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001874 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001875 List<String> associations = new ArrayList<>();
1876 associations.add("a");
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04001877 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001878
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001879 mBinderService.getNotificationChannelsFromPrivilegedListener(
1880 null, PKG, Process.myUserHandle());
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001881
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001882 verify(mPreferencesHelper, times(1)).getNotificationChannels(
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001883 anyString(), anyInt(), anyBoolean());
1884 }
1885
1886 @Test
Julia Reynolds48a6ed92018-10-22 12:52:03 -04001887 public void testGetNotificationChannelFromPrivilegedListener_cdm_noAccess() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001888 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001889 List<String> associations = new ArrayList<>();
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04001890 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001891
1892 try {
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001893 mBinderService.getNotificationChannelsFromPrivilegedListener(
1894 null, PKG, Process.myUserHandle());
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001895 fail("listeners that don't have a companion device shouldn't be able to call this");
1896 } catch (SecurityException e) {
1897 // pass
1898 }
1899
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001900 verify(mPreferencesHelper, never()).getNotificationChannels(
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001901 anyString(), anyInt(), anyBoolean());
1902 }
1903
1904 @Test
Julia Reynolds48a6ed92018-10-22 12:52:03 -04001905 public void testGetNotificationChannelFromPrivilegedListener_assistant_success()
1906 throws Exception {
1907 mService.setPreferencesHelper(mPreferencesHelper);
1908 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(new ArrayList<>());
1909 when(mAssistants.isServiceTokenValidLocked(any())).thenReturn(true);
1910
1911 mBinderService.getNotificationChannelsFromPrivilegedListener(
1912 null, PKG, Process.myUserHandle());
1913
1914 verify(mPreferencesHelper, times(1)).getNotificationChannels(
1915 anyString(), anyInt(), anyBoolean());
1916 }
1917
1918 @Test
Julia Reynolds268647a2018-10-25 16:54:27 -04001919 public void testGetNotificationChannelFromPrivilegedListener_assistant_noAccess()
1920 throws Exception {
Julia Reynolds48a6ed92018-10-22 12:52:03 -04001921 mService.setPreferencesHelper(mPreferencesHelper);
1922 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(new ArrayList<>());
1923 when(mAssistants.isServiceTokenValidLocked(any())).thenReturn(false);
1924
1925 try {
1926 mBinderService.getNotificationChannelsFromPrivilegedListener(
1927 null, PKG, Process.myUserHandle());
1928 fail("listeners that don't have a companion device shouldn't be able to call this");
1929 } catch (SecurityException e) {
1930 // pass
1931 }
1932
1933 verify(mPreferencesHelper, never()).getNotificationChannels(
1934 anyString(), anyInt(), anyBoolean());
1935 }
1936
1937 @Test
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001938 public void testGetNotificationChannelFromPrivilegedListener_badUser() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001939 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001940 List<String> associations = new ArrayList<>();
1941 associations.add("a");
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04001942 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001943 mListener = mock(ManagedServices.ManagedServiceInfo.class);
1944 when(mListener.enabledAndUserMatches(anyInt())).thenReturn(false);
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04001945 when(mListeners.checkServiceTokenLocked(any())).thenReturn(mListener);
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001946
1947 try {
1948 mBinderService.getNotificationChannelsFromPrivilegedListener(
1949 null, PKG, Process.myUserHandle());
1950 fail("listener getting channels from a user they cannot see");
1951 } catch (SecurityException e) {
1952 // pass
1953 }
1954
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001955 verify(mPreferencesHelper, never()).getNotificationChannels(
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001956 anyString(), anyInt(), anyBoolean());
1957 }
1958
1959 @Test
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001960 public void testGetNotificationChannelGroupsFromPrivilegedListener_success() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001961 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001962 List<String> associations = new ArrayList<>();
1963 associations.add("a");
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04001964 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001965
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001966 mBinderService.getNotificationChannelGroupsFromPrivilegedListener(
1967 null, PKG, Process.myUserHandle());
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001968
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001969 verify(mPreferencesHelper, times(1)).getNotificationChannelGroups(anyString(), anyInt());
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001970 }
1971
1972 @Test
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001973 public void testGetNotificationChannelGroupsFromPrivilegedListener_noAccess() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001974 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001975 List<String> associations = new ArrayList<>();
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04001976 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001977
1978 try {
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001979 mBinderService.getNotificationChannelGroupsFromPrivilegedListener(
1980 null, PKG, Process.myUserHandle());
1981 fail("listeners that don't have a companion device shouldn't be able to call this");
1982 } catch (SecurityException e) {
1983 // pass
1984 }
1985
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001986 verify(mPreferencesHelper, never()).getNotificationChannelGroups(anyString(), anyInt());
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001987 }
1988
1989 @Test
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001990 public void testGetNotificationChannelGroupsFromPrivilegedListener_badUser() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001991 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001992 List<String> associations = new ArrayList<>();
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04001993 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001994 mListener = mock(ManagedServices.ManagedServiceInfo.class);
1995 when(mListener.enabledAndUserMatches(anyInt())).thenReturn(false);
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04001996 when(mListeners.checkServiceTokenLocked(any())).thenReturn(mListener);
Julia Reynolds27c0a962018-12-10 12:37:28 -05001997 try {
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04001998 mBinderService.getNotificationChannelGroupsFromPrivilegedListener(
1999 null, PKG, Process.myUserHandle());
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002000 fail("listeners that don't have a companion device shouldn't be able to call this");
2001 } catch (SecurityException e) {
2002 // pass
2003 }
2004
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002005 verify(mPreferencesHelper, never()).getNotificationChannelGroups(anyString(), anyInt());
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002006 }
Julia Reynoldsda781472017-04-12 09:41:16 -04002007
2008 @Test
Julia Reynoldsda781472017-04-12 09:41:16 -04002009 public void testHasCompanionDevice_failure() throws Exception {
2010 when(mCompanionMgr.getAssociations(anyString(), anyInt())).thenThrow(
2011 new IllegalArgumentException());
Julia Reynolds503ed942017-10-04 16:04:56 -04002012 mService.hasCompanionDevice(mListener);
Julia Reynoldsda781472017-04-12 09:41:16 -04002013 }
Julia Reynolds727a7282017-04-13 10:54:01 -04002014
2015 @Test
Julia Reynolds0c245002019-03-27 16:10:11 -04002016 public void testHasCompanionDevice_noService() {
2017 mService = new TestableNotificationManagerService(mContext);
Julia Reynolds727a7282017-04-13 10:54:01 -04002018
Julia Reynolds503ed942017-10-04 16:04:56 -04002019 assertFalse(mService.hasCompanionDevice(mListener));
Julia Reynolds727a7282017-04-13 10:54:01 -04002020 }
2021
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002022 @Test
2023 public void testSnoozeRunnable_snoozeNonGrouped() throws Exception {
2024 final NotificationRecord nonGrouped = generateNotificationRecord(
2025 mTestNotificationChannel, 1, null, false);
2026 final NotificationRecord grouped = generateNotificationRecord(
2027 mTestNotificationChannel, 2, "group", false);
Julia Reynolds503ed942017-10-04 16:04:56 -04002028 mService.addNotification(grouped);
2029 mService.addNotification(nonGrouped);
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002030
2031 NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
Julia Reynolds503ed942017-10-04 16:04:56 -04002032 mService.new SnoozeNotificationRunnable(
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002033 nonGrouped.getKey(), 100, null);
2034 snoozeNotificationRunnable.run();
2035
2036 // only snooze the one notification
2037 verify(mSnoozeHelper, times(1)).snooze(any(NotificationRecord.class), anyLong());
Julia Reynolds503ed942017-10-04 16:04:56 -04002038 assertTrue(nonGrouped.getStats().hasSnoozed());
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002039 }
2040
2041 @Test
2042 public void testSnoozeRunnable_snoozeSummary_withChildren() throws Exception {
2043 final NotificationRecord parent = generateNotificationRecord(
2044 mTestNotificationChannel, 1, "group", true);
2045 final NotificationRecord child = generateNotificationRecord(
2046 mTestNotificationChannel, 2, "group", false);
2047 final NotificationRecord child2 = generateNotificationRecord(
2048 mTestNotificationChannel, 3, "group", false);
Julia Reynolds503ed942017-10-04 16:04:56 -04002049 mService.addNotification(parent);
2050 mService.addNotification(child);
2051 mService.addNotification(child2);
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002052
2053 NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
Julia Reynolds503ed942017-10-04 16:04:56 -04002054 mService.new SnoozeNotificationRunnable(
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002055 parent.getKey(), 100, null);
2056 snoozeNotificationRunnable.run();
2057
2058 // snooze parent and children
2059 verify(mSnoozeHelper, times(3)).snooze(any(NotificationRecord.class), anyLong());
2060 }
2061
2062 @Test
2063 public void testSnoozeRunnable_snoozeGroupChild_fellowChildren() throws Exception {
2064 final NotificationRecord parent = generateNotificationRecord(
2065 mTestNotificationChannel, 1, "group", true);
2066 final NotificationRecord child = generateNotificationRecord(
2067 mTestNotificationChannel, 2, "group", false);
2068 final NotificationRecord child2 = generateNotificationRecord(
2069 mTestNotificationChannel, 3, "group", false);
Julia Reynolds503ed942017-10-04 16:04:56 -04002070 mService.addNotification(parent);
2071 mService.addNotification(child);
2072 mService.addNotification(child2);
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002073
2074 NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
Julia Reynolds503ed942017-10-04 16:04:56 -04002075 mService.new SnoozeNotificationRunnable(
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002076 child2.getKey(), 100, null);
2077 snoozeNotificationRunnable.run();
2078
2079 // only snooze the one child
2080 verify(mSnoozeHelper, times(1)).snooze(any(NotificationRecord.class), anyLong());
2081 }
2082
2083 @Test
2084 public void testSnoozeRunnable_snoozeGroupChild_onlyChildOfSummary() throws Exception {
2085 final NotificationRecord parent = generateNotificationRecord(
2086 mTestNotificationChannel, 1, "group", true);
2087 assertTrue(parent.sbn.getNotification().isGroupSummary());
2088 final NotificationRecord child = generateNotificationRecord(
2089 mTestNotificationChannel, 2, "group", false);
Julia Reynolds503ed942017-10-04 16:04:56 -04002090 mService.addNotification(parent);
2091 mService.addNotification(child);
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002092
2093 NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
Julia Reynolds503ed942017-10-04 16:04:56 -04002094 mService.new SnoozeNotificationRunnable(
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002095 child.getKey(), 100, null);
2096 snoozeNotificationRunnable.run();
2097
2098 // snooze child and summary
2099 verify(mSnoozeHelper, times(2)).snooze(any(NotificationRecord.class), anyLong());
2100 }
2101
2102 @Test
2103 public void testSnoozeRunnable_snoozeGroupChild_noOthersInGroup() throws Exception {
2104 final NotificationRecord child = generateNotificationRecord(
2105 mTestNotificationChannel, 2, "group", false);
Julia Reynolds503ed942017-10-04 16:04:56 -04002106 mService.addNotification(child);
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002107
2108 NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
Julia Reynolds503ed942017-10-04 16:04:56 -04002109 mService.new SnoozeNotificationRunnable(
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002110 child.getKey(), 100, null);
2111 snoozeNotificationRunnable.run();
2112
2113 // snooze child only
2114 verify(mSnoozeHelper, times(1)).snooze(any(NotificationRecord.class), anyLong());
2115 }
2116
2117 @Test
2118 public void testPostGroupChild_unsnoozeParent() throws Exception {
2119 final NotificationRecord child = generateNotificationRecord(
2120 mTestNotificationChannel, 2, "group", false);
2121
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04002122 mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002123 child.sbn.getId(), child.sbn.getNotification(), child.sbn.getUserId());
2124 waitForIdle();
2125
2126 verify(mSnoozeHelper, times(1)).repostGroupSummary(
2127 anyString(), anyInt(), eq(child.getGroupKey()));
2128 }
2129
2130 @Test
2131 public void testPostNonGroup_noUnsnoozing() throws Exception {
2132 final NotificationRecord record = generateNotificationRecord(
2133 mTestNotificationChannel, 2, null, false);
2134
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04002135 mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002136 record.sbn.getId(), record.sbn.getNotification(), record.sbn.getUserId());
2137 waitForIdle();
2138
2139 verify(mSnoozeHelper, never()).repostGroupSummary(anyString(), anyInt(), anyString());
2140 }
2141
2142 @Test
2143 public void testPostGroupSummary_noUnsnoozing() throws Exception {
2144 final NotificationRecord parent = generateNotificationRecord(
2145 mTestNotificationChannel, 2, "group", true);
2146
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04002147 mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002148 parent.sbn.getId(), parent.sbn.getNotification(), parent.sbn.getUserId());
2149 waitForIdle();
2150
2151 verify(mSnoozeHelper, never()).repostGroupSummary(anyString(), anyInt(), anyString());
2152 }
Julia Reynoldsb852e562017-06-06 16:14:18 -04002153
2154 @Test
Julia Reynolds92febc32017-10-26 11:30:31 -04002155 public void testSetListenerAccessForUser() throws Exception {
2156 UserHandle user = UserHandle.of(10);
2157 ComponentName c = ComponentName.unflattenFromString("package/Component");
Julia Reynolds4afe2642019-05-01 08:42:24 -04002158 mBinderService.setNotificationListenerAccessGrantedForUser(c, user.getIdentifier(), true);
2159
Julia Reynolds92febc32017-10-26 11:30:31 -04002160
2161 verify(mContext, times(1)).sendBroadcastAsUser(any(), eq(user), any());
2162 verify(mListeners, times(1)).setPackageOrComponentEnabled(
2163 c.flattenToString(), user.getIdentifier(), true, true);
2164 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2165 c.flattenToString(), user.getIdentifier(), false, true);
2166 verify(mAssistants, never()).setPackageOrComponentEnabled(
2167 any(), anyInt(), anyBoolean(), anyBoolean());
2168 }
2169
2170 @Test
2171 public void testSetAssistantAccessForUser() throws Exception {
2172 UserHandle user = UserHandle.of(10);
Julia Reynolds4afe2642019-05-01 08:42:24 -04002173 List<UserInfo> uis = new ArrayList<>();
2174 UserInfo ui = new UserInfo();
2175 ui.id = 10;
2176 uis.add(ui);
Julia Reynolds92febc32017-10-26 11:30:31 -04002177 ComponentName c = ComponentName.unflattenFromString("package/Component");
Julia Reynolds4afe2642019-05-01 08:42:24 -04002178 when(mUm.getEnabledProfiles(10)).thenReturn(uis);
2179
2180 mBinderService.setNotificationAssistantAccessGrantedForUser(c, user.getIdentifier(), true);
Julia Reynolds92febc32017-10-26 11:30:31 -04002181
2182 verify(mContext, times(1)).sendBroadcastAsUser(any(), eq(user), any());
2183 verify(mAssistants, times(1)).setPackageOrComponentEnabled(
2184 c.flattenToString(), user.getIdentifier(), true, true);
Tony Mak9a3c1f12019-03-04 16:04:42 +00002185 verify(mAssistants).setUserSet(10, true);
Julia Reynolds92febc32017-10-26 11:30:31 -04002186 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2187 c.flattenToString(), user.getIdentifier(), false, true);
2188 verify(mListeners, never()).setPackageOrComponentEnabled(
2189 any(), anyInt(), anyBoolean(), anyBoolean());
2190 }
2191
2192 @Test
Fabian Kozynskid9425662019-01-29 13:08:30 -05002193 public void testGetAssistantAllowedForUser() throws Exception {
2194 UserHandle user = UserHandle.of(10);
2195 try {
2196 mBinderService.getAllowedNotificationAssistantForUser(user.getIdentifier());
2197 } catch (IllegalStateException e) {
2198 if (!e.getMessage().contains("At most one NotificationAssistant")) {
2199 throw e;
2200 }
2201 }
2202 verify(mAssistants, times(1)).getAllowedComponents(user.getIdentifier());
2203 }
2204
2205 @Test
2206 public void testGetAssistantAllowed() throws Exception {
2207 try {
2208 mBinderService.getAllowedNotificationAssistant();
2209 } catch (IllegalStateException e) {
2210 if (!e.getMessage().contains("At most one NotificationAssistant")) {
2211 throw e;
2212 }
2213 }
2214 verify(mAssistants, times(1)).getAllowedComponents(0);
2215 }
2216
2217 @Test
Julia Reynolds92febc32017-10-26 11:30:31 -04002218 public void testSetDndAccessForUser() throws Exception {
2219 UserHandle user = UserHandle.of(10);
2220 ComponentName c = ComponentName.unflattenFromString("package/Component");
Julia Reynolds4afe2642019-05-01 08:42:24 -04002221 mBinderService.setNotificationPolicyAccessGrantedForUser(
2222 c.getPackageName(), user.getIdentifier(), true);
Julia Reynolds92febc32017-10-26 11:30:31 -04002223
2224 verify(mContext, times(1)).sendBroadcastAsUser(any(), eq(user), any());
2225 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2226 c.getPackageName(), user.getIdentifier(), true, true);
2227 verify(mAssistants, never()).setPackageOrComponentEnabled(
2228 any(), anyInt(), anyBoolean(), anyBoolean());
2229 verify(mListeners, never()).setPackageOrComponentEnabled(
2230 any(), anyInt(), anyBoolean(), anyBoolean());
2231 }
2232
2233 @Test
Julia Reynoldsb852e562017-06-06 16:14:18 -04002234 public void testSetListenerAccess() throws Exception {
2235 ComponentName c = ComponentName.unflattenFromString("package/Component");
Julia Reynolds4afe2642019-05-01 08:42:24 -04002236 mBinderService.setNotificationListenerAccessGranted(c, true);
Julia Reynoldsb852e562017-06-06 16:14:18 -04002237
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002238 verify(mListeners, times(1)).setPackageOrComponentEnabled(
Julia Reynoldsb852e562017-06-06 16:14:18 -04002239 c.flattenToString(), 0, true, true);
2240 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2241 c.flattenToString(), 0, false, true);
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002242 verify(mAssistants, never()).setPackageOrComponentEnabled(
Julia Reynoldsb852e562017-06-06 16:14:18 -04002243 any(), anyInt(), anyBoolean(), anyBoolean());
2244 }
2245
2246 @Test
2247 public void testSetAssistantAccess() throws Exception {
Julia Reynolds4afe2642019-05-01 08:42:24 -04002248 List<UserInfo> uis = new ArrayList<>();
2249 UserInfo ui = new UserInfo();
2250 ui.id = 0;
2251 uis.add(ui);
2252 when(mUm.getEnabledProfiles(ui.id)).thenReturn(uis);
Julia Reynoldsb852e562017-06-06 16:14:18 -04002253 ComponentName c = ComponentName.unflattenFromString("package/Component");
Julia Reynolds4afe2642019-05-01 08:42:24 -04002254
2255 mBinderService.setNotificationAssistantAccessGranted(c, true);
Julia Reynoldsb852e562017-06-06 16:14:18 -04002256
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002257 verify(mAssistants, times(1)).setPackageOrComponentEnabled(
Julia Reynoldsb852e562017-06-06 16:14:18 -04002258 c.flattenToString(), 0, true, true);
2259 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2260 c.flattenToString(), 0, false, true);
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002261 verify(mListeners, never()).setPackageOrComponentEnabled(
Julia Reynoldsb852e562017-06-06 16:14:18 -04002262 any(), anyInt(), anyBoolean(), anyBoolean());
2263 }
2264
2265 @Test
Julia Reynolds4afe2642019-05-01 08:42:24 -04002266 public void testSetAssistantAccess_multiProfile() throws Exception {
2267 List<UserInfo> uis = new ArrayList<>();
2268 UserInfo ui = new UserInfo();
2269 ui.id = 0;
2270 uis.add(ui);
2271 UserInfo ui10 = new UserInfo();
2272 ui10.id = 10;
2273 uis.add(ui10);
2274 when(mUm.getEnabledProfiles(ui.id)).thenReturn(uis);
2275 ComponentName c = ComponentName.unflattenFromString("package/Component");
2276
2277 mBinderService.setNotificationAssistantAccessGranted(c, true);
2278
2279 verify(mAssistants, times(1)).setPackageOrComponentEnabled(
2280 c.flattenToString(), 0, true, true);
2281 verify(mAssistants, times(1)).setPackageOrComponentEnabled(
2282 c.flattenToString(), 10, true, true);
2283 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2284 c.flattenToString(), 0, false, true);
2285 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2286 c.flattenToString(), 10, false, true);
2287 verify(mListeners, never()).setPackageOrComponentEnabled(
2288 any(), anyInt(), anyBoolean(), anyBoolean());
2289 }
2290
2291 @Test
Fabian Kozynskid9425662019-01-29 13:08:30 -05002292 public void testSetAssistantAccess_nullWithAllowedAssistant() throws Exception {
2293 ArrayList<ComponentName> componentList = new ArrayList<>();
2294 ComponentName c = ComponentName.unflattenFromString("package/Component");
2295 componentList.add(c);
2296 when(mAssistants.getAllowedComponents(anyInt())).thenReturn(componentList);
Julia Reynolds4afe2642019-05-01 08:42:24 -04002297 List<UserInfo> uis = new ArrayList<>();
2298 UserInfo ui = new UserInfo();
2299 ui.id = 0;
2300 uis.add(ui);
2301 when(mUm.getEnabledProfiles(ui.id)).thenReturn(uis);
Fabian Kozynskid9425662019-01-29 13:08:30 -05002302
Julia Reynolds4afe2642019-05-01 08:42:24 -04002303 mBinderService.setNotificationAssistantAccessGranted(null, true);
Fabian Kozynskid9425662019-01-29 13:08:30 -05002304
2305 verify(mAssistants, times(1)).setPackageOrComponentEnabled(
2306 c.flattenToString(), 0, true, false);
2307 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2308 c.flattenToString(), 0, false, false);
2309 verify(mListeners, never()).setPackageOrComponentEnabled(
2310 any(), anyInt(), anyBoolean(), anyBoolean());
2311 }
2312
2313 @Test
2314 public void testSetAssistantAccessForUser_nullWithAllowedAssistant() throws Exception {
Julia Reynolds4afe2642019-05-01 08:42:24 -04002315 List<UserInfo> uis = new ArrayList<>();
2316 UserInfo ui = new UserInfo();
2317 ui.id = 10;
2318 uis.add(ui);
2319 UserHandle user = ui.getUserHandle();
Fabian Kozynskid9425662019-01-29 13:08:30 -05002320 ArrayList<ComponentName> componentList = new ArrayList<>();
2321 ComponentName c = ComponentName.unflattenFromString("package/Component");
2322 componentList.add(c);
2323 when(mAssistants.getAllowedComponents(anyInt())).thenReturn(componentList);
Julia Reynolds4afe2642019-05-01 08:42:24 -04002324 when(mUm.getEnabledProfiles(10)).thenReturn(uis);
Fabian Kozynskid9425662019-01-29 13:08:30 -05002325
Julia Reynolds4afe2642019-05-01 08:42:24 -04002326 mBinderService.setNotificationAssistantAccessGrantedForUser(
2327 null, user.getIdentifier(), true);
Fabian Kozynskid9425662019-01-29 13:08:30 -05002328
2329 verify(mAssistants, times(1)).setPackageOrComponentEnabled(
2330 c.flattenToString(), user.getIdentifier(), true, false);
Julia Reynolds4afe2642019-05-01 08:42:24 -04002331 verify(mAssistants).setUserSet(10, true);
Fabian Kozynskid9425662019-01-29 13:08:30 -05002332 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2333 c.flattenToString(), user.getIdentifier(), false, false);
2334 verify(mListeners, never()).setPackageOrComponentEnabled(
2335 any(), anyInt(), anyBoolean(), anyBoolean());
2336 }
2337
2338 @Test
Julia Reynolds4afe2642019-05-01 08:42:24 -04002339 public void testSetAssistantAccessForUser_workProfile_nullWithAllowedAssistant()
2340 throws Exception {
2341 List<UserInfo> uis = new ArrayList<>();
2342 UserInfo ui = new UserInfo();
2343 ui.id = 0;
2344 uis.add(ui);
2345 UserInfo ui10 = new UserInfo();
2346 ui10.id = 10;
2347 uis.add(ui10);
2348 UserHandle user = ui.getUserHandle();
2349 ArrayList<ComponentName> componentList = new ArrayList<>();
2350 ComponentName c = ComponentName.unflattenFromString("package/Component");
2351 componentList.add(c);
2352 when(mAssistants.getAllowedComponents(anyInt())).thenReturn(componentList);
2353 when(mUm.getEnabledProfiles(ui.id)).thenReturn(uis);
2354
2355 mBinderService.setNotificationAssistantAccessGrantedForUser(
2356 null, user.getIdentifier(), true);
2357
2358 verify(mAssistants, times(1)).setPackageOrComponentEnabled(
2359 c.flattenToString(), user.getIdentifier(), true, false);
2360 verify(mAssistants, times(1)).setPackageOrComponentEnabled(
2361 c.flattenToString(), ui10.id, true, false);
2362 verify(mAssistants).setUserSet(0, true);
2363 verify(mAssistants).setUserSet(10, true);
2364 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2365 c.flattenToString(), user.getIdentifier(), false, false);
2366 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2367 c.flattenToString(), ui10.id, false, false);
2368 verify(mListeners, never()).setPackageOrComponentEnabled(
2369 any(), anyInt(), anyBoolean(), anyBoolean());
2370 }
2371
2372 @Test
Julia Reynoldsb852e562017-06-06 16:14:18 -04002373 public void testSetDndAccess() throws Exception {
2374 ComponentName c = ComponentName.unflattenFromString("package/Component");
Julia Reynolds4afe2642019-05-01 08:42:24 -04002375
2376 mBinderService.setNotificationPolicyAccessGranted(c.getPackageName(), true);
Julia Reynoldsb852e562017-06-06 16:14:18 -04002377
2378 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2379 c.getPackageName(), 0, true, true);
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002380 verify(mAssistants, never()).setPackageOrComponentEnabled(
Julia Reynoldsb852e562017-06-06 16:14:18 -04002381 any(), anyInt(), anyBoolean(), anyBoolean());
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002382 verify(mListeners, never()).setPackageOrComponentEnabled(
Julia Reynoldsb852e562017-06-06 16:14:18 -04002383 any(), anyInt(), anyBoolean(), anyBoolean());
2384 }
Julia Reynolds68263d12017-06-21 14:21:19 -04002385
2386 @Test
2387 public void testSetListenerAccess_doesNothingOnLowRam() throws Exception {
2388 when(mActivityManager.isLowRamDevice()).thenReturn(true);
2389 ComponentName c = ComponentName.unflattenFromString("package/Component");
2390 mBinderService.setNotificationListenerAccessGranted(c, true);
2391
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002392 verify(mListeners, never()).setPackageOrComponentEnabled(
Julia Reynoldse1816412017-10-24 10:39:11 -04002393 anyString(), anyInt(), anyBoolean(), anyBoolean());
Julia Reynolds68263d12017-06-21 14:21:19 -04002394 verify(mConditionProviders, never()).setPackageOrComponentEnabled(
Julia Reynoldse1816412017-10-24 10:39:11 -04002395 anyString(), anyInt(), anyBoolean(), anyBoolean());
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002396 verify(mAssistants, never()).setPackageOrComponentEnabled(
Julia Reynolds68263d12017-06-21 14:21:19 -04002397 any(), anyInt(), anyBoolean(), anyBoolean());
2398 }
2399
2400 @Test
2401 public void testSetAssistantAccess_doesNothingOnLowRam() throws Exception {
2402 when(mActivityManager.isLowRamDevice()).thenReturn(true);
2403 ComponentName c = ComponentName.unflattenFromString("package/Component");
Julia Reynolds4afe2642019-05-01 08:42:24 -04002404 List<UserInfo> uis = new ArrayList<>();
2405 UserInfo ui = new UserInfo();
2406 ui.id = 0;
2407 uis.add(ui);
2408 when(mUm.getEnabledProfiles(ui.id)).thenReturn(uis);
2409
Julia Reynolds68263d12017-06-21 14:21:19 -04002410 mBinderService.setNotificationAssistantAccessGranted(c, true);
2411
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002412 verify(mListeners, never()).setPackageOrComponentEnabled(
Julia Reynoldse1816412017-10-24 10:39:11 -04002413 anyString(), anyInt(), anyBoolean(), anyBoolean());
Julia Reynolds68263d12017-06-21 14:21:19 -04002414 verify(mConditionProviders, never()).setPackageOrComponentEnabled(
Julia Reynoldse1816412017-10-24 10:39:11 -04002415 anyString(), anyInt(), anyBoolean(), anyBoolean());
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002416 verify(mAssistants, never()).setPackageOrComponentEnabled(
Julia Reynolds68263d12017-06-21 14:21:19 -04002417 any(), anyInt(), anyBoolean(), anyBoolean());
2418 }
2419
2420 @Test
2421 public void testSetDndAccess_doesNothingOnLowRam() throws Exception {
2422 when(mActivityManager.isLowRamDevice()).thenReturn(true);
2423 ComponentName c = ComponentName.unflattenFromString("package/Component");
2424 mBinderService.setNotificationPolicyAccessGranted(c.getPackageName(), true);
2425
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002426 verify(mListeners, never()).setPackageOrComponentEnabled(
Julia Reynoldse1816412017-10-24 10:39:11 -04002427 anyString(), anyInt(), anyBoolean(), anyBoolean());
Julia Reynolds68263d12017-06-21 14:21:19 -04002428 verify(mConditionProviders, never()).setPackageOrComponentEnabled(
Julia Reynoldse1816412017-10-24 10:39:11 -04002429 anyString(), anyInt(), anyBoolean(), anyBoolean());
2430 verify(mAssistants, never()).setPackageOrComponentEnabled(
2431 any(), anyInt(), anyBoolean(), anyBoolean());
2432 }
2433
2434 @Test
2435 public void testSetListenerAccess_doesNothingOnLowRam_exceptWatch() throws Exception {
2436 when(mPackageManagerClient.hasSystemFeature(FEATURE_WATCH)).thenReturn(true);
2437 when(mActivityManager.isLowRamDevice()).thenReturn(true);
2438 ComponentName c = ComponentName.unflattenFromString("package/Component");
Julia Reynolds4afe2642019-05-01 08:42:24 -04002439
2440 mBinderService.setNotificationListenerAccessGranted(c, true);
Julia Reynoldse1816412017-10-24 10:39:11 -04002441
2442 verify(mListeners, times(1)).setPackageOrComponentEnabled(
2443 c.flattenToString(), 0, true, true);
2444 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
Julia Reynolds68263d12017-06-21 14:21:19 -04002445 c.flattenToString(), 0, false, true);
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002446 verify(mAssistants, never()).setPackageOrComponentEnabled(
Julia Reynolds68263d12017-06-21 14:21:19 -04002447 any(), anyInt(), anyBoolean(), anyBoolean());
2448 }
Julia Reynolds8aebf352017-06-26 11:35:33 -04002449
2450 @Test
Julia Reynoldse1816412017-10-24 10:39:11 -04002451 public void testSetAssistantAccess_doesNothingOnLowRam_exceptWatch() throws Exception {
2452 when(mPackageManagerClient.hasSystemFeature(FEATURE_WATCH)).thenReturn(true);
2453 when(mActivityManager.isLowRamDevice()).thenReturn(true);
2454 ComponentName c = ComponentName.unflattenFromString("package/Component");
Julia Reynolds4afe2642019-05-01 08:42:24 -04002455 List<UserInfo> uis = new ArrayList<>();
2456 UserInfo ui = new UserInfo();
2457 ui.id = 0;
2458 uis.add(ui);
2459 when(mUm.getEnabledProfiles(ui.id)).thenReturn(uis);
2460
2461 mBinderService.setNotificationAssistantAccessGranted(c, true);
Julia Reynoldse1816412017-10-24 10:39:11 -04002462
2463 verify(mListeners, never()).setPackageOrComponentEnabled(
2464 anyString(), anyInt(), anyBoolean(), anyBoolean());
2465 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2466 c.flattenToString(), 0, false, true);
2467 verify(mAssistants, times(1)).setPackageOrComponentEnabled(
2468 c.flattenToString(), 0, true, true);
2469 }
2470
2471 @Test
2472 public void testSetDndAccess_doesNothingOnLowRam_exceptWatch() throws Exception {
2473 when(mPackageManagerClient.hasSystemFeature(FEATURE_WATCH)).thenReturn(true);
2474 when(mActivityManager.isLowRamDevice()).thenReturn(true);
2475 ComponentName c = ComponentName.unflattenFromString("package/Component");
Julia Reynolds4afe2642019-05-01 08:42:24 -04002476
2477 mBinderService.setNotificationPolicyAccessGranted(c.getPackageName(), true);
Julia Reynoldse1816412017-10-24 10:39:11 -04002478
2479 verify(mListeners, never()).setPackageOrComponentEnabled(
2480 anyString(), anyInt(), anyBoolean(), anyBoolean());
2481 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2482 c.getPackageName(), 0, true, true);
2483 verify(mAssistants, never()).setPackageOrComponentEnabled(
2484 any(), anyInt(), anyBoolean(), anyBoolean());
2485 }
2486
2487 @Test
Julia Reynolds8aebf352017-06-26 11:35:33 -04002488 public void testOnlyAutogroupIfGroupChanged_noPriorNoti_autogroups() throws Exception {
2489 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel, 0, null, false);
Julia Reynolds503ed942017-10-04 16:04:56 -04002490 mService.addEnqueuedNotification(r);
Julia Reynolds8aebf352017-06-26 11:35:33 -04002491 NotificationManagerService.PostNotificationRunnable runnable =
Julia Reynolds503ed942017-10-04 16:04:56 -04002492 mService.new PostNotificationRunnable(r.getKey());
Julia Reynolds8aebf352017-06-26 11:35:33 -04002493 runnable.run();
2494 waitForIdle();
2495
Julia Reynoldsa13b3e22017-08-10 16:58:54 -04002496 verify(mGroupHelper, times(1)).onNotificationPosted(any(), anyBoolean());
Julia Reynolds8aebf352017-06-26 11:35:33 -04002497 }
2498
2499 @Test
2500 public void testOnlyAutogroupIfGroupChanged_groupChanged_autogroups()
2501 throws Exception {
Julia Reynolds8617e4e2017-09-18 16:52:37 -04002502 NotificationRecord r =
2503 generateNotificationRecord(mTestNotificationChannel, 0, "group", false);
Julia Reynolds503ed942017-10-04 16:04:56 -04002504 mService.addNotification(r);
Julia Reynolds8aebf352017-06-26 11:35:33 -04002505
2506 r = generateNotificationRecord(mTestNotificationChannel, 0, null, false);
Julia Reynolds503ed942017-10-04 16:04:56 -04002507 mService.addEnqueuedNotification(r);
Julia Reynolds8aebf352017-06-26 11:35:33 -04002508 NotificationManagerService.PostNotificationRunnable runnable =
Julia Reynolds503ed942017-10-04 16:04:56 -04002509 mService.new PostNotificationRunnable(r.getKey());
Julia Reynolds8aebf352017-06-26 11:35:33 -04002510 runnable.run();
2511 waitForIdle();
2512
Julia Reynoldsa13b3e22017-08-10 16:58:54 -04002513 verify(mGroupHelper, times(1)).onNotificationPosted(any(), anyBoolean());
Julia Reynolds8aebf352017-06-26 11:35:33 -04002514 }
2515
2516 @Test
2517 public void testOnlyAutogroupIfGroupChanged_noGroupChanged_autogroups()
2518 throws Exception {
Julia Reynolds4db59552017-06-30 13:34:01 -04002519 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel, 0, "group",
2520 false);
Julia Reynolds503ed942017-10-04 16:04:56 -04002521 mService.addNotification(r);
2522 mService.addEnqueuedNotification(r);
Julia Reynolds8aebf352017-06-26 11:35:33 -04002523
2524 NotificationManagerService.PostNotificationRunnable runnable =
Julia Reynolds503ed942017-10-04 16:04:56 -04002525 mService.new PostNotificationRunnable(r.getKey());
Julia Reynolds8aebf352017-06-26 11:35:33 -04002526 runnable.run();
2527 waitForIdle();
2528
Julia Reynoldsa13b3e22017-08-10 16:58:54 -04002529 verify(mGroupHelper, never()).onNotificationPosted(any(), anyBoolean());
Julia Reynolds8aebf352017-06-26 11:35:33 -04002530 }
Beverly40239d92017-07-07 10:20:41 -04002531
Julia Reynolds4db59552017-06-30 13:34:01 -04002532 @Test
Brad Stenningd2e7a972018-10-01 09:08:42 -07002533 public void testDontAutogroupIfCritical() throws Exception {
2534 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel, 0, null, false);
2535 r.setCriticality(CriticalNotificationExtractor.CRITICAL_LOW);
2536 mService.addEnqueuedNotification(r);
2537 NotificationManagerService.PostNotificationRunnable runnable =
2538 mService.new PostNotificationRunnable(r.getKey());
2539 runnable.run();
2540
2541 r = generateNotificationRecord(mTestNotificationChannel, 1, null, false);
2542 r.setCriticality(CriticalNotificationExtractor.CRITICAL);
2543 runnable = mService.new PostNotificationRunnable(r.getKey());
2544 mService.addEnqueuedNotification(r);
2545
2546 runnable.run();
2547 waitForIdle();
2548
2549 verify(mGroupHelper, never()).onNotificationPosted(any(), anyBoolean());
2550 }
2551
2552 @Test
Julia Reynolds4db59552017-06-30 13:34:01 -04002553 public void testNoFakeColorizedPermission() throws Exception {
2554 when(mPackageManagerClient.checkPermission(any(), any())).thenReturn(PERMISSION_DENIED);
2555 Notification.Builder nb = new Notification.Builder(mContext,
2556 mTestNotificationChannel.getId())
2557 .setContentTitle("foo")
2558 .setColorized(true)
2559 .setFlag(Notification.FLAG_CAN_COLORIZE, true)
2560 .setSmallIcon(android.R.drawable.sym_def_app_icon);
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04002561 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, "tag", mUid, 0,
2562 nb.build(), new UserHandle(mUid), null, 0);
Julia Reynolds4db59552017-06-30 13:34:01 -04002563 NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
2564
2565 mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
2566 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
2567 waitForIdle();
2568
Julia Reynolds503ed942017-10-04 16:04:56 -04002569 NotificationRecord posted = mService.findNotificationLocked(
Julia Reynolds4db59552017-06-30 13:34:01 -04002570 PKG, null, nr.sbn.getId(), nr.sbn.getUserId());
2571
2572 assertFalse(posted.getNotification().isColorized());
2573 }
Julia Reynolds6ad0aec2017-07-05 08:47:03 -04002574
2575 @Test
2576 public void testGetNotificationCountLocked() throws Exception {
2577 for (int i = 0; i < 20; i++) {
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04002578 NotificationRecord r =
2579 generateNotificationRecord(mTestNotificationChannel, i, null, false);
Julia Reynolds503ed942017-10-04 16:04:56 -04002580 mService.addEnqueuedNotification(r);
Julia Reynolds6ad0aec2017-07-05 08:47:03 -04002581 }
2582 for (int i = 0; i < 20; i++) {
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04002583 NotificationRecord r =
2584 generateNotificationRecord(mTestNotificationChannel, i, null, false);
Julia Reynolds503ed942017-10-04 16:04:56 -04002585 mService.addNotification(r);
Julia Reynolds6ad0aec2017-07-05 08:47:03 -04002586 }
2587
2588 // another package
2589 Notification n =
2590 new Notification.Builder(mContext, mTestNotificationChannel.getId())
2591 .setSmallIcon(android.R.drawable.sym_def_app_icon)
2592 .build();
2593
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04002594 StatusBarNotification sbn = new StatusBarNotification("a", "a", 0, "tag", mUid, 0,
2595 n, new UserHandle(mUid), null, 0);
Julia Reynolds6ad0aec2017-07-05 08:47:03 -04002596 NotificationRecord otherPackage =
2597 new NotificationRecord(mContext, sbn, mTestNotificationChannel);
Julia Reynolds503ed942017-10-04 16:04:56 -04002598 mService.addEnqueuedNotification(otherPackage);
2599 mService.addNotification(otherPackage);
Julia Reynolds6ad0aec2017-07-05 08:47:03 -04002600
2601 // Same notifications are enqueued as posted, everything counts b/c id and tag don't match
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04002602 int userId = new UserHandle(mUid).getIdentifier();
Julia Reynolds8617e4e2017-09-18 16:52:37 -04002603 assertEquals(40,
Julia Reynolds503ed942017-10-04 16:04:56 -04002604 mService.getNotificationCountLocked(PKG, userId, 0, null));
Julia Reynolds8617e4e2017-09-18 16:52:37 -04002605 assertEquals(40,
Julia Reynolds503ed942017-10-04 16:04:56 -04002606 mService.getNotificationCountLocked(PKG, userId, 0, "tag2"));
Julia Reynolds8617e4e2017-09-18 16:52:37 -04002607 assertEquals(2,
Julia Reynolds503ed942017-10-04 16:04:56 -04002608 mService.getNotificationCountLocked("a", userId, 0, "banana"));
Julia Reynolds6ad0aec2017-07-05 08:47:03 -04002609
2610 // exclude a known notification - it's excluded from only the posted list, not enqueued
Julia Reynolds8617e4e2017-09-18 16:52:37 -04002611 assertEquals(39,
Julia Reynolds503ed942017-10-04 16:04:56 -04002612 mService.getNotificationCountLocked(PKG, userId, 0, "tag"));
Julia Reynoldseb3dca72017-07-11 10:39:58 -04002613 }
2614
2615 @Test
Julia Reynolds51710712017-07-19 13:48:07 -04002616 public void testAddAutogroup_requestsSort() throws Exception {
Julia Reynoldseb3dca72017-07-11 10:39:58 -04002617 RankingHandler rh = mock(RankingHandler.class);
Julia Reynolds503ed942017-10-04 16:04:56 -04002618 mService.setRankingHandler(rh);
Julia Reynoldseb3dca72017-07-11 10:39:58 -04002619
2620 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
Julia Reynolds503ed942017-10-04 16:04:56 -04002621 mService.addNotification(r);
2622 mService.addAutogroupKeyLocked(r.getKey());
Julia Reynolds51710712017-07-19 13:48:07 -04002623
2624 verify(rh, times(1)).requestSort();
2625 }
2626
2627 @Test
2628 public void testRemoveAutogroup_requestsSort() throws Exception {
2629 RankingHandler rh = mock(RankingHandler.class);
Julia Reynolds503ed942017-10-04 16:04:56 -04002630 mService.setRankingHandler(rh);
Julia Reynolds51710712017-07-19 13:48:07 -04002631
2632 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
2633 r.setOverrideGroupKey("TEST");
Julia Reynolds503ed942017-10-04 16:04:56 -04002634 mService.addNotification(r);
2635 mService.removeAutogroupKeyLocked(r.getKey());
Julia Reynoldseb3dca72017-07-11 10:39:58 -04002636
Julia Reynolds51710712017-07-19 13:48:07 -04002637 verify(rh, times(1)).requestSort();
2638 }
2639
2640 @Test
2641 public void testReaddAutogroup_noSort() throws Exception {
2642 RankingHandler rh = mock(RankingHandler.class);
Julia Reynolds503ed942017-10-04 16:04:56 -04002643 mService.setRankingHandler(rh);
Julia Reynolds51710712017-07-19 13:48:07 -04002644
2645 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
2646 r.setOverrideGroupKey("TEST");
Julia Reynolds503ed942017-10-04 16:04:56 -04002647 mService.addNotification(r);
2648 mService.addAutogroupKeyLocked(r.getKey());
Julia Reynolds51710712017-07-19 13:48:07 -04002649
2650 verify(rh, never()).requestSort();
Julia Reynoldseb3dca72017-07-11 10:39:58 -04002651 }
2652
2653 @Test
2654 public void testHandleRankingSort_sendsUpdateOnSignalExtractorChange() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002655 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynoldseb3dca72017-07-11 10:39:58 -04002656 NotificationManagerService.WorkerHandler handler = mock(
2657 NotificationManagerService.WorkerHandler.class);
Julia Reynolds503ed942017-10-04 16:04:56 -04002658 mService.setHandler(handler);
Julia Reynoldseb3dca72017-07-11 10:39:58 -04002659
2660 Map<String, Answer> answers = getSignalExtractorSideEffects();
2661 for (String message : answers.keySet()) {
Julia Reynolds503ed942017-10-04 16:04:56 -04002662 mService.clearNotifications();
Julia Reynoldseb3dca72017-07-11 10:39:58 -04002663 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
Julia Reynolds503ed942017-10-04 16:04:56 -04002664 mService.addNotification(r);
Julia Reynoldseb3dca72017-07-11 10:39:58 -04002665
2666 doAnswer(answers.get(message)).when(mRankingHelper).extractSignals(r);
2667
Julia Reynolds503ed942017-10-04 16:04:56 -04002668 mService.handleRankingSort();
Julia Reynoldseb3dca72017-07-11 10:39:58 -04002669 }
2670 verify(handler, times(answers.size())).scheduleSendRankingUpdate();
2671 }
2672
2673 @Test
2674 public void testHandleRankingSort_noUpdateWhenNoSignalChange() throws Exception {
Julia Reynolds503ed942017-10-04 16:04:56 -04002675 mService.setRankingHelper(mRankingHelper);
Julia Reynoldseb3dca72017-07-11 10:39:58 -04002676 NotificationManagerService.WorkerHandler handler = mock(
2677 NotificationManagerService.WorkerHandler.class);
Julia Reynolds503ed942017-10-04 16:04:56 -04002678 mService.setHandler(handler);
Julia Reynoldseb3dca72017-07-11 10:39:58 -04002679
2680 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
Julia Reynolds503ed942017-10-04 16:04:56 -04002681 mService.addNotification(r);
Julia Reynoldseb3dca72017-07-11 10:39:58 -04002682
Julia Reynolds503ed942017-10-04 16:04:56 -04002683 mService.handleRankingSort();
Julia Reynoldseb3dca72017-07-11 10:39:58 -04002684 verify(handler, never()).scheduleSendRankingUpdate();
Julia Reynolds6ad0aec2017-07-05 08:47:03 -04002685 }
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002686
2687 @Test
2688 public void testReadPolicyXml_readApprovedServicesFromXml() throws Exception {
Julia Reynoldsd6d5a592018-04-02 11:03:32 -04002689 final String upgradeXml = "<notification-policy version=\"1\">"
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002690 + "<ranking></ranking>"
2691 + "<enabled_listeners>"
2692 + "<service_listing approved=\"test\" user=\"0\" primary=\"true\" />"
2693 + "</enabled_listeners>"
2694 + "<enabled_assistants>"
2695 + "<service_listing approved=\"test\" user=\"0\" primary=\"true\" />"
2696 + "</enabled_assistants>"
2697 + "<dnd_apps>"
2698 + "<service_listing approved=\"test\" user=\"0\" primary=\"true\" />"
2699 + "</dnd_apps>"
2700 + "</notification-policy>";
Julia Reynolds503ed942017-10-04 16:04:56 -04002701 mService.readPolicyXml(
Annie Meng8b646fd2019-02-01 18:46:42 +00002702 new BufferedInputStream(new ByteArrayInputStream(upgradeXml.getBytes())),
2703 false,
2704 UserHandle.USER_ALL);
2705 verify(mListeners, times(1)).readXml(any(), any(), anyBoolean(), anyInt());
2706 verify(mConditionProviders, times(1)).readXml(any(), any(), anyBoolean(), anyInt());
2707 verify(mAssistants, times(1)).readXml(any(), any(), anyBoolean(), anyInt());
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002708
2709 // numbers are inflated for setup
2710 verify(mListeners, times(1)).migrateToXml();
2711 verify(mConditionProviders, times(1)).migrateToXml();
2712 verify(mAssistants, times(1)).migrateToXml();
Tony Mak9a3c1f12019-03-04 16:04:42 +00002713 verify(mAssistants, times(2)).resetDefaultAssistantsIfNecessary();
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002714 }
2715
2716 @Test
2717 public void testReadPolicyXml_readApprovedServicesFromSettings() throws Exception {
2718 final String preupgradeXml = "<notification-policy version=\"1\">"
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002719 + "<ranking></ranking>"
2720 + "</notification-policy>";
Julia Reynolds503ed942017-10-04 16:04:56 -04002721 mService.readPolicyXml(
Annie Meng8b646fd2019-02-01 18:46:42 +00002722 new BufferedInputStream(new ByteArrayInputStream(preupgradeXml.getBytes())),
2723 false,
2724 UserHandle.USER_ALL);
2725 verify(mListeners, never()).readXml(any(), any(), anyBoolean(), anyInt());
2726 verify(mConditionProviders, never()).readXml(any(), any(), anyBoolean(), anyInt());
2727 verify(mAssistants, never()).readXml(any(), any(), anyBoolean(), anyInt());
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002728
2729 // numbers are inflated for setup
2730 verify(mListeners, times(2)).migrateToXml();
2731 verify(mConditionProviders, times(2)).migrateToXml();
2732 verify(mAssistants, times(2)).migrateToXml();
Tony Mak9a3c1f12019-03-04 16:04:42 +00002733 verify(mAssistants, times(2)).resetDefaultAssistantsIfNecessary();
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002734 }
2735
Annie Meng8b646fd2019-02-01 18:46:42 +00002736 @Test
2737 public void testReadPolicyXml_doesNotRestoreManagedServicesForManagedUser() throws Exception {
2738 final String policyXml = "<notification-policy version=\"1\">"
2739 + "<ranking></ranking>"
2740 + "<enabled_listeners>"
2741 + "<service_listing approved=\"test\" user=\"10\" primary=\"true\" />"
2742 + "</enabled_listeners>"
2743 + "<enabled_assistants>"
2744 + "<service_listing approved=\"test\" user=\"10\" primary=\"true\" />"
2745 + "</enabled_assistants>"
2746 + "<dnd_apps>"
2747 + "<service_listing approved=\"test\" user=\"10\" primary=\"true\" />"
2748 + "</dnd_apps>"
2749 + "</notification-policy>";
Julia Reynolds0c245002019-03-27 16:10:11 -04002750 when(mUm.isManagedProfile(10)).thenReturn(true);
Annie Meng8b646fd2019-02-01 18:46:42 +00002751 mService.readPolicyXml(
2752 new BufferedInputStream(new ByteArrayInputStream(policyXml.getBytes())),
2753 true,
2754 10);
2755 verify(mListeners, never()).readXml(any(), any(), eq(true), eq(10));
2756 verify(mConditionProviders, never()).readXml(any(), any(), eq(true), eq(10));
2757 verify(mAssistants, never()).readXml(any(), any(), eq(true), eq(10));
2758 }
2759
2760 @Test
2761 public void testReadPolicyXml_restoresManagedServicesForNonManagedUser() throws Exception {
2762 final String policyXml = "<notification-policy version=\"1\">"
2763 + "<ranking></ranking>"
2764 + "<enabled_listeners>"
2765 + "<service_listing approved=\"test\" user=\"10\" primary=\"true\" />"
2766 + "</enabled_listeners>"
2767 + "<enabled_assistants>"
2768 + "<service_listing approved=\"test\" user=\"10\" primary=\"true\" />"
2769 + "</enabled_assistants>"
2770 + "<dnd_apps>"
2771 + "<service_listing approved=\"test\" user=\"10\" primary=\"true\" />"
2772 + "</dnd_apps>"
2773 + "</notification-policy>";
Julia Reynolds0c245002019-03-27 16:10:11 -04002774 when(mUm.isManagedProfile(10)).thenReturn(false);
Annie Meng8b646fd2019-02-01 18:46:42 +00002775 mService.readPolicyXml(
2776 new BufferedInputStream(new ByteArrayInputStream(policyXml.getBytes())),
2777 true,
2778 10);
2779 verify(mListeners, times(1)).readXml(any(), any(), eq(true), eq(10));
2780 verify(mConditionProviders, times(1)).readXml(any(), any(), eq(true), eq(10));
2781 verify(mAssistants, times(1)).readXml(any(), any(), eq(true), eq(10));
2782 }
Beverlyd4f96492017-08-02 13:36:11 -04002783
2784 @Test
2785 public void testLocaleChangedCallsUpdateDefaultZenModeRules() throws Exception {
2786 ZenModeHelper mZenModeHelper = mock(ZenModeHelper.class);
Julia Reynolds503ed942017-10-04 16:04:56 -04002787 mService.mZenModeHelper = mZenModeHelper;
2788 mService.mLocaleChangeReceiver.onReceive(mContext,
Beverlyd4f96492017-08-02 13:36:11 -04002789 new Intent(Intent.ACTION_LOCALE_CHANGED));
2790
2791 verify(mZenModeHelper, times(1)).updateDefaultZenRules();
2792 }
Julia Reynolds8617e4e2017-09-18 16:52:37 -04002793
2794 @Test
2795 public void testBumpFGImportance_noChannelChangePreOApp() throws Exception {
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06002796 String preOPkg = PKG_N_MR1;
Julia Reynolds8617e4e2017-09-18 16:52:37 -04002797 final ApplicationInfo legacy = new ApplicationInfo();
2798 legacy.targetSdkVersion = Build.VERSION_CODES.N_MR1;
2799 when(mPackageManagerClient.getApplicationInfoAsUser(eq(preOPkg), anyInt(), anyInt()))
2800 .thenReturn(legacy);
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04002801 when(mPackageManagerClient.getPackageUidAsUser(eq(preOPkg), anyInt()))
2802 .thenReturn(Binder.getCallingUid());
Julia Reynolds8617e4e2017-09-18 16:52:37 -04002803 getContext().setMockPackageManager(mPackageManagerClient);
2804
2805 Notification.Builder nb = new Notification.Builder(mContext,
2806 NotificationChannel.DEFAULT_CHANNEL_ID)
2807 .setContentTitle("foo")
2808 .setSmallIcon(android.R.drawable.sym_def_app_icon)
Julia Reynoldse5c60452018-04-30 14:41:36 -04002809 .setFlag(FLAG_FOREGROUND_SERVICE, true)
Julia Reynolds8617e4e2017-09-18 16:52:37 -04002810 .setPriority(Notification.PRIORITY_MIN);
2811
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04002812 StatusBarNotification sbn = new StatusBarNotification(preOPkg, preOPkg, 9, "tag",
2813 Binder.getCallingUid(), 0, nb.build(), new UserHandle(Binder.getCallingUid()), null, 0);
Julia Reynolds8617e4e2017-09-18 16:52:37 -04002814
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04002815 mBinderService.enqueueNotificationWithTag(sbn.getPackageName(), sbn.getOpPkg(),
2816 sbn.getTag(), sbn.getId(), sbn.getNotification(), sbn.getUserId());
Julia Reynolds8617e4e2017-09-18 16:52:37 -04002817 waitForIdle();
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04002818
Julia Reynolds8617e4e2017-09-18 16:52:37 -04002819 assertEquals(IMPORTANCE_LOW,
Julia Reynolds503ed942017-10-04 16:04:56 -04002820 mService.getNotificationRecord(sbn.getKey()).getImportance());
Julia Reynolds8617e4e2017-09-18 16:52:37 -04002821
2822 nb = new Notification.Builder(mContext)
2823 .setContentTitle("foo")
2824 .setSmallIcon(android.R.drawable.sym_def_app_icon)
Julia Reynoldse5c60452018-04-30 14:41:36 -04002825 .setFlag(FLAG_FOREGROUND_SERVICE, true)
Julia Reynolds8617e4e2017-09-18 16:52:37 -04002826 .setPriority(Notification.PRIORITY_MIN);
2827
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04002828 sbn = new StatusBarNotification(preOPkg, preOPkg, 9, "tag", Binder.getCallingUid(),
2829 0, nb.build(), new UserHandle(Binder.getCallingUid()), null, 0);
Julia Reynolds8617e4e2017-09-18 16:52:37 -04002830
2831 mBinderService.enqueueNotificationWithTag(preOPkg, preOPkg, "tag",
2832 sbn.getId(), sbn.getNotification(), sbn.getUserId());
2833 waitForIdle();
2834 assertEquals(IMPORTANCE_LOW,
Julia Reynolds503ed942017-10-04 16:04:56 -04002835 mService.getNotificationRecord(sbn.getKey()).getImportance());
Julia Reynolds8617e4e2017-09-18 16:52:37 -04002836
2837 NotificationChannel defaultChannel = mBinderService.getNotificationChannel(
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -04002838 preOPkg, mContext.getUserId(), preOPkg, NotificationChannel.DEFAULT_CHANNEL_ID);
Julia Reynolds8617e4e2017-09-18 16:52:37 -04002839 assertEquals(IMPORTANCE_UNSPECIFIED, defaultChannel.getImportance());
2840 }
Julia Reynolds503ed942017-10-04 16:04:56 -04002841
2842 @Test
2843 public void testStats_updatedOnDirectReply() throws Exception {
2844 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
2845 mService.addNotification(r);
2846
2847 mService.mNotificationDelegate.onNotificationDirectReplied(r.getKey());
2848 assertTrue(mService.getNotificationRecord(r.getKey()).getStats().hasDirectReplied());
Tony Makeda84a72018-11-19 17:01:32 +00002849 verify(mAssistants).notifyAssistantNotificationDirectReplyLocked(eq(r.sbn));
Julia Reynolds503ed942017-10-04 16:04:56 -04002850 }
2851
2852 @Test
Julia Reynolds84dc96b2017-11-14 09:51:01 -05002853 public void testStats_updatedOnUserExpansion() throws Exception {
2854 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
Julia Reynolds503ed942017-10-04 16:04:56 -04002855 mService.addNotification(r);
2856
Gustav Senntona8e38aa2019-01-22 14:55:39 +00002857 mService.mNotificationDelegate.onNotificationExpansionChanged(r.getKey(), true, true,
2858 NOTIFICATION_LOCATION_UNKNOWN);
Tony Makeda84a72018-11-19 17:01:32 +00002859 verify(mAssistants).notifyAssistantExpansionChangedLocked(eq(r.sbn), eq(true), eq((true)));
Julia Reynolds503ed942017-10-04 16:04:56 -04002860 assertTrue(mService.getNotificationRecord(r.getKey()).getStats().hasExpanded());
Tony Makeda84a72018-11-19 17:01:32 +00002861
Gustav Senntona8e38aa2019-01-22 14:55:39 +00002862 mService.mNotificationDelegate.onNotificationExpansionChanged(r.getKey(), true, false,
2863 NOTIFICATION_LOCATION_UNKNOWN);
Tony Makeda84a72018-11-19 17:01:32 +00002864 verify(mAssistants).notifyAssistantExpansionChangedLocked(eq(r.sbn), eq(true), eq((false)));
Julia Reynolds503ed942017-10-04 16:04:56 -04002865 assertTrue(mService.getNotificationRecord(r.getKey()).getStats().hasExpanded());
2866 }
2867
2868 @Test
Julia Reynolds84dc96b2017-11-14 09:51:01 -05002869 public void testStats_notUpdatedOnAutoExpansion() throws Exception {
2870 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
2871 mService.addNotification(r);
2872
Gustav Senntona8e38aa2019-01-22 14:55:39 +00002873 mService.mNotificationDelegate.onNotificationExpansionChanged(r.getKey(), false, true,
2874 NOTIFICATION_LOCATION_UNKNOWN);
Julia Reynolds84dc96b2017-11-14 09:51:01 -05002875 assertFalse(mService.getNotificationRecord(r.getKey()).getStats().hasExpanded());
Tony Makeda84a72018-11-19 17:01:32 +00002876 verify(mAssistants).notifyAssistantExpansionChangedLocked(eq(r.sbn), eq(false), eq((true)));
2877
Gustav Senntona8e38aa2019-01-22 14:55:39 +00002878 mService.mNotificationDelegate.onNotificationExpansionChanged(r.getKey(), false, false,
2879 NOTIFICATION_LOCATION_UNKNOWN);
Julia Reynolds84dc96b2017-11-14 09:51:01 -05002880 assertFalse(mService.getNotificationRecord(r.getKey()).getStats().hasExpanded());
Tony Makeda84a72018-11-19 17:01:32 +00002881 verify(mAssistants).notifyAssistantExpansionChangedLocked(
2882 eq(r.sbn), eq(false), eq((false)));
Julia Reynolds84dc96b2017-11-14 09:51:01 -05002883 }
2884
2885 @Test
Julia Reynolds503ed942017-10-04 16:04:56 -04002886 public void testStats_updatedOnViewSettings() throws Exception {
2887 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
2888 mService.addNotification(r);
2889
2890 mService.mNotificationDelegate.onNotificationSettingsViewed(r.getKey());
2891 assertTrue(mService.getNotificationRecord(r.getKey()).getStats().hasViewedSettings());
2892 }
2893
2894 @Test
2895 public void testStats_updatedOnVisibilityChanged() throws Exception {
2896 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
2897 mService.addNotification(r);
2898
Dieter Hsud39f0d52018-04-14 02:08:30 +08002899 final NotificationVisibility nv = NotificationVisibility.obtain(r.getKey(), 1, 2, true);
Julia Reynolds503ed942017-10-04 16:04:56 -04002900 mService.mNotificationDelegate.onNotificationVisibilityChanged(
2901 new NotificationVisibility[] {nv}, new NotificationVisibility[]{});
2902 assertTrue(mService.getNotificationRecord(r.getKey()).getStats().hasSeen());
2903 mService.mNotificationDelegate.onNotificationVisibilityChanged(
2904 new NotificationVisibility[] {}, new NotificationVisibility[]{nv});
2905 assertTrue(mService.getNotificationRecord(r.getKey()).getStats().hasSeen());
2906 }
2907
2908 @Test
2909 public void testStats_dismissalSurface() throws Exception {
2910 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
2911 mService.addNotification(r);
2912
Dieter Hsud39f0d52018-04-14 02:08:30 +08002913 final NotificationVisibility nv = NotificationVisibility.obtain(r.getKey(), 0, 1, true);
Julia Reynolds503ed942017-10-04 16:04:56 -04002914 mService.mNotificationDelegate.onNotificationClear(mUid, 0, PKG, r.sbn.getTag(),
Julia Reynoldsfd4099d2018-08-21 11:06:06 -04002915 r.sbn.getId(), r.getUserId(), r.getKey(), NotificationStats.DISMISSAL_AOD,
2916 NotificationStats.DISMISS_SENTIMENT_POSITIVE, nv);
Julia Reynolds503ed942017-10-04 16:04:56 -04002917 waitForIdle();
2918
2919 assertEquals(NotificationStats.DISMISSAL_AOD, r.getStats().getDismissalSurface());
2920 }
2921
2922 @Test
Julia Reynoldsfd4099d2018-08-21 11:06:06 -04002923 public void testStats_dismissalSentiment() throws Exception {
2924 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
2925 mService.addNotification(r);
2926
2927 final NotificationVisibility nv = NotificationVisibility.obtain(r.getKey(), 0, 1, true);
2928 mService.mNotificationDelegate.onNotificationClear(mUid, 0, PKG, r.sbn.getTag(),
2929 r.sbn.getId(), r.getUserId(), r.getKey(), NotificationStats.DISMISSAL_AOD,
2930 NotificationStats.DISMISS_SENTIMENT_NEGATIVE, nv);
2931 waitForIdle();
2932
2933 assertEquals(NotificationStats.DISMISS_SENTIMENT_NEGATIVE,
2934 r.getStats().getDismissalSentiment());
2935 }
2936
2937 @Test
Julia Reynolds70aaea72018-07-13 13:38:34 -04002938 public void testApplyAdjustmentMultiUser() throws Exception {
Julia Reynolds503ed942017-10-04 16:04:56 -04002939 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
2940 mService.addNotification(r);
2941 NotificationManagerService.WorkerHandler handler = mock(
2942 NotificationManagerService.WorkerHandler.class);
2943 mService.setHandler(handler);
2944
Julia Reynolds70aaea72018-07-13 13:38:34 -04002945 when(mAssistants.isSameUser(eq(null), anyInt())).thenReturn(false);
2946
Julia Reynolds503ed942017-10-04 16:04:56 -04002947 Bundle signals = new Bundle();
2948 signals.putInt(Adjustment.KEY_USER_SENTIMENT,
Julia Reynolds70aaea72018-07-13 13:38:34 -04002949 USER_SENTIMENT_NEGATIVE);
2950 Adjustment adjustment = new Adjustment(
2951 r.sbn.getPackageName(), r.getKey(), signals, "", r.getUser().getIdentifier());
2952 mBinderService.applyAdjustmentFromAssistant(null, adjustment);
2953
2954 waitForIdle();
2955
2956 verify(handler, timeout(300).times(0)).scheduleSendRankingUpdate();
2957 }
2958
2959 @Test
Julia Reynolds27c0a962018-12-10 12:37:28 -05002960 public void testAssistantBlockingTriggersCancel() throws Exception {
Julia Reynoldsefcdff42018-08-09 09:42:56 -04002961 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
2962 mService.addNotification(r);
2963 NotificationManagerService.WorkerHandler handler = mock(
2964 NotificationManagerService.WorkerHandler.class);
2965 mService.setHandler(handler);
2966
2967 Bundle signals = new Bundle();
Julia Reynoldsc7dcdc22019-03-25 10:26:14 -04002968 signals.putInt(KEY_IMPORTANCE, IMPORTANCE_NONE);
Julia Reynoldsefcdff42018-08-09 09:42:56 -04002969 Adjustment adjustment = new Adjustment(
2970 r.sbn.getPackageName(), r.getKey(), signals, "", r.getUser().getIdentifier());
2971 when(mAssistants.isSameUser(any(), anyInt())).thenReturn(true);
2972 mBinderService.applyAdjustmentFromAssistant(null, adjustment);
2973
2974 waitForIdle();
2975
2976 verify(handler, timeout(300).times(0)).scheduleSendRankingUpdate();
2977 verify(handler, times(1)).scheduleCancelNotification(any());
2978 }
2979
2980 @Test
Julia Reynolds70aaea72018-07-13 13:38:34 -04002981 public void testApplyEnqueuedAdjustmentFromAssistant_singleUser() throws Exception {
2982 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
2983 mService.addEnqueuedNotification(r);
2984 NotificationManagerService.WorkerHandler handler = mock(
2985 NotificationManagerService.WorkerHandler.class);
2986 mService.setHandler(handler);
2987 when(mAssistants.isSameUser(eq(null), anyInt())).thenReturn(true);
2988
2989 Bundle signals = new Bundle();
2990 signals.putInt(Adjustment.KEY_USER_SENTIMENT,
2991 USER_SENTIMENT_NEGATIVE);
2992 Adjustment adjustment = new Adjustment(
2993 r.sbn.getPackageName(), r.getKey(), signals, "", r.getUser().getIdentifier());
2994 mBinderService.applyEnqueuedAdjustmentFromAssistant(null, adjustment);
2995
2996 assertEquals(USER_SENTIMENT_NEGATIVE, r.getUserSentiment());
2997 }
2998
2999 @Test
Julia Reynoldsdc6adc62019-04-08 10:35:40 -04003000 public void testApplyEnqueuedAdjustmentFromAssistant_importance() throws Exception {
Julia Reynolds27c0a962018-12-10 12:37:28 -05003001 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
3002 mService.addEnqueuedNotification(r);
3003 NotificationManagerService.WorkerHandler handler = mock(
3004 NotificationManagerService.WorkerHandler.class);
3005 mService.setHandler(handler);
3006 when(mAssistants.isSameUser(eq(null), anyInt())).thenReturn(true);
3007
3008 Bundle signals = new Bundle();
Julia Reynoldsc7dcdc22019-03-25 10:26:14 -04003009 signals.putInt(KEY_IMPORTANCE, IMPORTANCE_LOW);
Julia Reynolds27c0a962018-12-10 12:37:28 -05003010 Adjustment adjustment = new Adjustment(
3011 r.sbn.getPackageName(), r.getKey(), signals, "", r.getUser().getIdentifier());
3012 mBinderService.applyEnqueuedAdjustmentFromAssistant(null, adjustment);
3013
3014 assertEquals(IMPORTANCE_LOW, r.getImportance());
3015 }
3016
3017 @Test
Julia Reynolds70aaea72018-07-13 13:38:34 -04003018 public void testApplyEnqueuedAdjustmentFromAssistant_crossUser() throws Exception {
3019 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
3020 mService.addEnqueuedNotification(r);
3021 NotificationManagerService.WorkerHandler handler = mock(
3022 NotificationManagerService.WorkerHandler.class);
3023 mService.setHandler(handler);
3024 when(mAssistants.isSameUser(eq(null), anyInt())).thenReturn(false);
3025
3026 Bundle signals = new Bundle();
3027 signals.putInt(Adjustment.KEY_USER_SENTIMENT,
3028 USER_SENTIMENT_NEGATIVE);
3029 Adjustment adjustment = new Adjustment(
3030 r.sbn.getPackageName(), r.getKey(), signals, "", r.getUser().getIdentifier());
3031 mBinderService.applyEnqueuedAdjustmentFromAssistant(null, adjustment);
3032
3033 assertEquals(USER_SENTIMENT_NEUTRAL, r.getUserSentiment());
3034
3035 waitForIdle();
3036
3037 verify(handler, timeout(300).times(0)).scheduleSendRankingUpdate();
3038 }
3039
3040 @Test
3041 public void testUserSentimentChangeTriggersUpdate() throws Exception {
3042 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
3043 mService.addNotification(r);
3044 NotificationManagerService.WorkerHandler handler = mock(
3045 NotificationManagerService.WorkerHandler.class);
3046 mService.setHandler(handler);
3047 when(mAssistants.isSameUser(eq(null), anyInt())).thenReturn(true);
3048
3049 Bundle signals = new Bundle();
3050 signals.putInt(Adjustment.KEY_USER_SENTIMENT,
3051 USER_SENTIMENT_NEGATIVE);
Julia Reynolds503ed942017-10-04 16:04:56 -04003052 Adjustment adjustment = new Adjustment(
3053 r.sbn.getPackageName(), r.getKey(), signals, "", r.getUser().getIdentifier());
3054 mBinderService.applyAdjustmentFromAssistant(null, adjustment);
3055
3056 waitForIdle();
3057
3058 verify(handler, timeout(300).times(1)).scheduleSendRankingUpdate();
3059 }
Julia Reynolds7bcb57b2018-01-22 10:37:58 -05003060
3061 @Test
Julia Reynolds666ccf02018-06-18 10:19:20 -04003062 public void testTooLateAdjustmentTriggersUpdate() throws Exception {
3063 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
3064 mService.addNotification(r);
3065 NotificationManagerService.WorkerHandler handler = mock(
3066 NotificationManagerService.WorkerHandler.class);
3067 mService.setHandler(handler);
Julia Reynolds70aaea72018-07-13 13:38:34 -04003068 when(mAssistants.isSameUser(eq(null), anyInt())).thenReturn(true);
Julia Reynolds666ccf02018-06-18 10:19:20 -04003069
3070 Bundle signals = new Bundle();
3071 signals.putInt(Adjustment.KEY_USER_SENTIMENT,
Julia Reynolds70aaea72018-07-13 13:38:34 -04003072 USER_SENTIMENT_NEGATIVE);
Julia Reynolds666ccf02018-06-18 10:19:20 -04003073 Adjustment adjustment = new Adjustment(
3074 r.sbn.getPackageName(), r.getKey(), signals, "", r.getUser().getIdentifier());
3075 mBinderService.applyEnqueuedAdjustmentFromAssistant(null, adjustment);
3076
3077 waitForIdle();
3078
3079 verify(handler, timeout(300).times(1)).scheduleSendRankingUpdate();
3080 }
3081
3082 @Test
3083 public void testEnqueuedAdjustmentAppliesAdjustments() throws Exception {
3084 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
3085 mService.addEnqueuedNotification(r);
3086 NotificationManagerService.WorkerHandler handler = mock(
3087 NotificationManagerService.WorkerHandler.class);
3088 mService.setHandler(handler);
Julia Reynolds70aaea72018-07-13 13:38:34 -04003089 when(mAssistants.isSameUser(eq(null), anyInt())).thenReturn(true);
Julia Reynolds666ccf02018-06-18 10:19:20 -04003090
3091 Bundle signals = new Bundle();
3092 signals.putInt(Adjustment.KEY_USER_SENTIMENT,
Julia Reynolds70aaea72018-07-13 13:38:34 -04003093 USER_SENTIMENT_NEGATIVE);
Julia Reynolds666ccf02018-06-18 10:19:20 -04003094 Adjustment adjustment = new Adjustment(
3095 r.sbn.getPackageName(), r.getKey(), signals, "", r.getUser().getIdentifier());
3096 mBinderService.applyEnqueuedAdjustmentFromAssistant(null, adjustment);
3097
Julia Reynolds70aaea72018-07-13 13:38:34 -04003098 assertEquals(USER_SENTIMENT_NEGATIVE,
Julia Reynolds666ccf02018-06-18 10:19:20 -04003099 r.getUserSentiment());
3100 }
3101
3102 @Test
Julia Reynoldsd78263d2018-01-30 10:40:41 -05003103 public void testRestore() throws Exception {
3104 int systemChecks = mService.countSystemChecks;
3105 mBinderService.applyRestore(null, UserHandle.USER_SYSTEM);
3106 assertEquals(1, mService.countSystemChecks - systemChecks);
3107 }
3108
3109 @Test
3110 public void testBackup() throws Exception {
3111 int systemChecks = mService.countSystemChecks;
3112 mBinderService.getBackupPayload(1);
3113 assertEquals(1, mService.countSystemChecks - systemChecks);
3114 }
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003115
3116 @Test
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003117 public void updateUriPermissions_update() throws Exception {
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003118 NotificationChannel c = new NotificationChannel(
Julia Reynolds27c0a962018-12-10 12:37:28 -05003119 TEST_CHANNEL_ID, TEST_CHANNEL_ID, IMPORTANCE_DEFAULT);
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003120 c.setSound(null, Notification.AUDIO_ATTRIBUTES_DEFAULT);
3121 Message message1 = new Message("", 0, "");
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003122 message1.setData("",
3123 ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 1));
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003124 Message message2 = new Message("", 1, "");
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003125 message2.setData("",
3126 ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 2));
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003127
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003128 Notification.Builder nbA = new Notification.Builder(mContext, c.getId())
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003129 .setContentTitle("foo")
3130 .setSmallIcon(android.R.drawable.sym_def_app_icon)
3131 .setStyle(new Notification.MessagingStyle("")
3132 .addMessage(message1)
3133 .addMessage(message2));
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003134 NotificationRecord recordA = new NotificationRecord(mContext, new StatusBarNotification(
3135 PKG, PKG, 0, "tag", mUid, 0, nbA.build(), new UserHandle(mUid), null, 0), c);
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003136
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003137 // First post means we grant access to both
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003138 reset(mUgm);
3139 reset(mUgmInternal);
3140 when(mUgmInternal.newUriPermissionOwner(any())).thenReturn(new Binder());
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003141 mService.updateUriPermissions(recordA, null, mContext.getPackageName(),
3142 UserHandle.USER_SYSTEM);
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003143 verify(mUgm, times(1)).grantUriPermissionFromOwner(any(), anyInt(), any(),
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003144 eq(message1.getDataUri()), anyInt(), anyInt(), anyInt());
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003145 verify(mUgm, times(1)).grantUriPermissionFromOwner(any(), anyInt(), any(),
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003146 eq(message2.getDataUri()), anyInt(), anyInt(), anyInt());
3147
3148 Notification.Builder nbB = new Notification.Builder(mContext, c.getId())
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003149 .setContentTitle("foo")
3150 .setSmallIcon(android.R.drawable.sym_def_app_icon)
3151 .setStyle(new Notification.MessagingStyle("").addMessage(message2));
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003152 NotificationRecord recordB = new NotificationRecord(mContext, new StatusBarNotification(PKG,
3153 PKG, 0, "tag", mUid, 0, nbB.build(), new UserHandle(mUid), null, 0), c);
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003154
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003155 // Update means we drop access to first
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003156 reset(mUgmInternal);
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003157 mService.updateUriPermissions(recordB, recordA, mContext.getPackageName(),
3158 UserHandle.USER_SYSTEM);
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003159 verify(mUgmInternal, times(1)).revokeUriPermissionFromOwner(any(),
3160 eq(message1.getDataUri()), anyInt(), anyInt());
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003161
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003162 // Update back means we grant access to first again
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003163 reset(mUgm);
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003164 mService.updateUriPermissions(recordA, recordB, mContext.getPackageName(),
3165 UserHandle.USER_SYSTEM);
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003166 verify(mUgm, times(1)).grantUriPermissionFromOwner(any(), anyInt(), any(),
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003167 eq(message1.getDataUri()), anyInt(), anyInt(), anyInt());
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003168
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003169 // And update to empty means we drop everything
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003170 reset(mUgmInternal);
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003171 mService.updateUriPermissions(null, recordB, mContext.getPackageName(),
3172 UserHandle.USER_SYSTEM);
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003173 verify(mUgmInternal, times(1)).revokeUriPermissionFromOwner(any(), eq(null),
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003174 anyInt(), anyInt());
3175 }
Julia Reynoldsccc6ae62018-03-01 16:24:49 -05003176
3177 @Test
Robin Leed107af62018-04-27 13:55:56 +02003178 public void testVisitUris() throws Exception {
3179 final Uri audioContents = Uri.parse("content://com.example/audio");
3180 final Uri backgroundImage = Uri.parse("content://com.example/background");
3181
3182 Bundle extras = new Bundle();
3183 extras.putParcelable(Notification.EXTRA_AUDIO_CONTENTS_URI, audioContents);
3184 extras.putString(Notification.EXTRA_BACKGROUND_IMAGE_URI, backgroundImage.toString());
3185
3186 Notification n = new Notification.Builder(mContext, "a")
3187 .setContentTitle("notification with uris")
3188 .setSmallIcon(android.R.drawable.sym_def_app_icon)
3189 .addExtras(extras)
3190 .build();
3191
3192 Consumer<Uri> visitor = (Consumer<Uri>) spy(Consumer.class);
3193 n.visitUris(visitor);
3194 verify(visitor, times(1)).accept(eq(audioContents));
3195 verify(visitor, times(1)).accept(eq(backgroundImage));
3196 }
3197
3198 @Test
Julia Reynoldsccc6ae62018-03-01 16:24:49 -05003199 public void testSetNotificationPolicy_preP_setOldFields() {
3200 ZenModeHelper mZenModeHelper = mock(ZenModeHelper.class);
3201 mService.mZenModeHelper = mZenModeHelper;
3202 NotificationManager.Policy userPolicy =
3203 new NotificationManager.Policy(0, 0, 0, SUPPRESSED_EFFECT_BADGE);
3204 when(mZenModeHelper.getNotificationPolicy()).thenReturn(userPolicy);
3205
3206 NotificationManager.Policy appPolicy = new NotificationManager.Policy(0, 0, 0,
3207 SUPPRESSED_EFFECT_SCREEN_ON | SUPPRESSED_EFFECT_SCREEN_OFF);
3208
3209 int expected = SUPPRESSED_EFFECT_BADGE
3210 | SUPPRESSED_EFFECT_SCREEN_ON | SUPPRESSED_EFFECT_SCREEN_OFF
Julia Reynoldseac2da22018-04-12 10:48:46 -04003211 | SUPPRESSED_EFFECT_PEEK | SUPPRESSED_EFFECT_LIGHTS
3212 | SUPPRESSED_EFFECT_FULL_SCREEN_INTENT;
Julia Reynoldsccc6ae62018-03-01 16:24:49 -05003213 int actual = mService.calculateSuppressedVisualEffects(appPolicy, userPolicy, O_MR1);
3214
3215 assertEquals(expected, actual);
3216 }
3217
3218 @Test
3219 public void testSetNotificationPolicy_preP_setNewFields() {
3220 ZenModeHelper mZenModeHelper = mock(ZenModeHelper.class);
3221 mService.mZenModeHelper = mZenModeHelper;
3222 NotificationManager.Policy userPolicy =
3223 new NotificationManager.Policy(0, 0, 0, SUPPRESSED_EFFECT_BADGE);
3224 when(mZenModeHelper.getNotificationPolicy()).thenReturn(userPolicy);
3225
3226 NotificationManager.Policy appPolicy = new NotificationManager.Policy(0, 0, 0,
3227 SUPPRESSED_EFFECT_NOTIFICATION_LIST);
3228
3229 int expected = SUPPRESSED_EFFECT_BADGE;
3230 int actual = mService.calculateSuppressedVisualEffects(appPolicy, userPolicy, O_MR1);
3231
3232 assertEquals(expected, actual);
3233 }
3234
3235 @Test
3236 public void testSetNotificationPolicy_preP_setOldNewFields() {
3237 ZenModeHelper mZenModeHelper = mock(ZenModeHelper.class);
3238 mService.mZenModeHelper = mZenModeHelper;
3239 NotificationManager.Policy userPolicy =
3240 new NotificationManager.Policy(0, 0, 0, SUPPRESSED_EFFECT_BADGE);
3241 when(mZenModeHelper.getNotificationPolicy()).thenReturn(userPolicy);
3242
3243 NotificationManager.Policy appPolicy = new NotificationManager.Policy(0, 0, 0,
3244 SUPPRESSED_EFFECT_SCREEN_ON | SUPPRESSED_EFFECT_STATUS_BAR);
3245
3246 int expected =
3247 SUPPRESSED_EFFECT_BADGE | SUPPRESSED_EFFECT_SCREEN_ON | SUPPRESSED_EFFECT_PEEK;
3248 int actual = mService.calculateSuppressedVisualEffects(appPolicy, userPolicy, O_MR1);
3249
3250 assertEquals(expected, actual);
3251 }
3252
3253 @Test
3254 public void testSetNotificationPolicy_P_setOldFields() {
3255 ZenModeHelper mZenModeHelper = mock(ZenModeHelper.class);
3256 mService.mZenModeHelper = mZenModeHelper;
3257 NotificationManager.Policy userPolicy =
3258 new NotificationManager.Policy(0, 0, 0, SUPPRESSED_EFFECT_BADGE);
3259 when(mZenModeHelper.getNotificationPolicy()).thenReturn(userPolicy);
3260
3261 NotificationManager.Policy appPolicy = new NotificationManager.Policy(0, 0, 0,
3262 SUPPRESSED_EFFECT_SCREEN_ON | SUPPRESSED_EFFECT_SCREEN_OFF);
3263
3264 int expected = SUPPRESSED_EFFECT_SCREEN_ON | SUPPRESSED_EFFECT_SCREEN_OFF
3265 | SUPPRESSED_EFFECT_PEEK | SUPPRESSED_EFFECT_AMBIENT
3266 | SUPPRESSED_EFFECT_LIGHTS | SUPPRESSED_EFFECT_FULL_SCREEN_INTENT;
3267 int actual = mService.calculateSuppressedVisualEffects(appPolicy, userPolicy, P);
3268
3269 assertEquals(expected, actual);
3270 }
3271
3272 @Test
3273 public void testSetNotificationPolicy_P_setNewFields() {
3274 ZenModeHelper mZenModeHelper = mock(ZenModeHelper.class);
3275 mService.mZenModeHelper = mZenModeHelper;
3276 NotificationManager.Policy userPolicy =
3277 new NotificationManager.Policy(0, 0, 0, SUPPRESSED_EFFECT_BADGE);
3278 when(mZenModeHelper.getNotificationPolicy()).thenReturn(userPolicy);
3279
3280 NotificationManager.Policy appPolicy = new NotificationManager.Policy(0, 0, 0,
3281 SUPPRESSED_EFFECT_NOTIFICATION_LIST | SUPPRESSED_EFFECT_AMBIENT
3282 | SUPPRESSED_EFFECT_LIGHTS | SUPPRESSED_EFFECT_FULL_SCREEN_INTENT);
3283
3284 int expected = SUPPRESSED_EFFECT_NOTIFICATION_LIST | SUPPRESSED_EFFECT_SCREEN_OFF
3285 | SUPPRESSED_EFFECT_AMBIENT | SUPPRESSED_EFFECT_LIGHTS
3286 | SUPPRESSED_EFFECT_FULL_SCREEN_INTENT;
3287 int actual = mService.calculateSuppressedVisualEffects(appPolicy, userPolicy, P);
3288
3289 assertEquals(expected, actual);
3290 }
3291
3292 @Test
3293 public void testSetNotificationPolicy_P_setOldNewFields() {
3294 ZenModeHelper mZenModeHelper = mock(ZenModeHelper.class);
3295 mService.mZenModeHelper = mZenModeHelper;
3296 NotificationManager.Policy userPolicy =
3297 new NotificationManager.Policy(0, 0, 0, SUPPRESSED_EFFECT_BADGE);
3298 when(mZenModeHelper.getNotificationPolicy()).thenReturn(userPolicy);
3299
3300 NotificationManager.Policy appPolicy = new NotificationManager.Policy(0, 0, 0,
3301 SUPPRESSED_EFFECT_SCREEN_ON | SUPPRESSED_EFFECT_STATUS_BAR);
3302
3303 int expected = SUPPRESSED_EFFECT_STATUS_BAR;
3304 int actual = mService.calculateSuppressedVisualEffects(appPolicy, userPolicy, P);
3305
3306 assertEquals(expected, actual);
3307
3308 appPolicy = new NotificationManager.Policy(0, 0, 0,
3309 SUPPRESSED_EFFECT_SCREEN_ON | SUPPRESSED_EFFECT_AMBIENT
3310 | SUPPRESSED_EFFECT_LIGHTS | SUPPRESSED_EFFECT_FULL_SCREEN_INTENT);
3311
3312 expected = SUPPRESSED_EFFECT_SCREEN_OFF | SUPPRESSED_EFFECT_AMBIENT
3313 | SUPPRESSED_EFFECT_LIGHTS | SUPPRESSED_EFFECT_FULL_SCREEN_INTENT;
3314 actual = mService.calculateSuppressedVisualEffects(appPolicy, userPolicy, P);
3315
3316 assertEquals(expected, actual);
3317 }
Julia Reynolds7217dc92018-03-07 12:12:09 -05003318
3319 @Test
Julia Reynoldse5c60452018-04-30 14:41:36 -04003320 public void testVisualDifference_foreground() {
3321 Notification.Builder nb1 = new Notification.Builder(mContext, "")
3322 .setContentTitle("foo");
3323 StatusBarNotification sbn1 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3324 nb1.build(), new UserHandle(mUid), null, 0);
3325 NotificationRecord r1 =
3326 new NotificationRecord(mContext, sbn1, mock(NotificationChannel.class));
3327
3328 Notification.Builder nb2 = new Notification.Builder(mContext, "")
3329 .setFlag(FLAG_FOREGROUND_SERVICE, true)
3330 .setContentTitle("bar");
3331 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3332 nb2.build(), new UserHandle(mUid), null, 0);
3333 NotificationRecord r2 =
3334 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
3335
3336 assertFalse(mService.isVisuallyInterruptive(r1, r2));
3337 }
3338
3339 @Test
Julia Reynolds7217dc92018-03-07 12:12:09 -05003340 public void testVisualDifference_diffTitle() {
3341 Notification.Builder nb1 = new Notification.Builder(mContext, "")
3342 .setContentTitle("foo");
3343 StatusBarNotification sbn1 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3344 nb1.build(), new UserHandle(mUid), null, 0);
3345 NotificationRecord r1 =
3346 new NotificationRecord(mContext, sbn1, mock(NotificationChannel.class));
3347
3348 Notification.Builder nb2 = new Notification.Builder(mContext, "")
3349 .setContentTitle("bar");
3350 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3351 nb2.build(), new UserHandle(mUid), null, 0);
3352 NotificationRecord r2 =
3353 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
3354
3355 assertTrue(mService.isVisuallyInterruptive(r1, r2));
3356 }
3357
3358 @Test
Dan Sandler7d67bd42018-05-15 14:06:38 -04003359 public void testVisualDifference_inboxStyle() {
3360 Notification.Builder nb1 = new Notification.Builder(mContext, "")
3361 .setStyle(new Notification.InboxStyle()
3362 .addLine("line1").addLine("line2"));
3363 StatusBarNotification sbn1 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3364 nb1.build(), new UserHandle(mUid), null, 0);
3365 NotificationRecord r1 =
3366 new NotificationRecord(mContext, sbn1, mock(NotificationChannel.class));
3367
3368 Notification.Builder nb2 = new Notification.Builder(mContext, "")
3369 .setStyle(new Notification.InboxStyle()
3370 .addLine("line1").addLine("line2_changed"));
3371 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3372 nb2.build(), new UserHandle(mUid), null, 0);
3373 NotificationRecord r2 =
3374 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
3375
3376 assertTrue(mService.isVisuallyInterruptive(r1, r2)); // line 2 changed unnoticed
3377
3378 Notification.Builder nb3 = new Notification.Builder(mContext, "")
3379 .setStyle(new Notification.InboxStyle()
3380 .addLine("line1"));
3381 StatusBarNotification sbn3 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3382 nb3.build(), new UserHandle(mUid), null, 0);
3383 NotificationRecord r3 =
3384 new NotificationRecord(mContext, sbn3, mock(NotificationChannel.class));
3385
3386 assertTrue(mService.isVisuallyInterruptive(r1, r3)); // line 2 removed unnoticed
3387
3388 Notification.Builder nb4 = new Notification.Builder(mContext, "")
3389 .setStyle(new Notification.InboxStyle()
3390 .addLine("line1").addLine("line2").addLine("line3"));
3391 StatusBarNotification sbn4 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3392 nb4.build(), new UserHandle(mUid), null, 0);
3393 NotificationRecord r4 =
3394 new NotificationRecord(mContext, sbn4, mock(NotificationChannel.class));
3395
3396 assertTrue(mService.isVisuallyInterruptive(r1, r4)); // line 3 added unnoticed
3397
3398 Notification.Builder nb5 = new Notification.Builder(mContext, "")
3399 .setContentText("not an inbox");
3400 StatusBarNotification sbn5 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3401 nb5.build(), new UserHandle(mUid), null, 0);
3402 NotificationRecord r5 =
3403 new NotificationRecord(mContext, sbn5, mock(NotificationChannel.class));
3404
3405 assertTrue(mService.isVisuallyInterruptive(r1, r5)); // changed Styles, went unnoticed
3406 }
3407
3408 @Test
Julia Reynolds7217dc92018-03-07 12:12:09 -05003409 public void testVisualDifference_diffText() {
3410 Notification.Builder nb1 = new Notification.Builder(mContext, "")
3411 .setContentText("foo");
3412 StatusBarNotification sbn1 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3413 nb1.build(), new UserHandle(mUid), null, 0);
3414 NotificationRecord r1 =
3415 new NotificationRecord(mContext, sbn1, mock(NotificationChannel.class));
3416
3417 Notification.Builder nb2 = new Notification.Builder(mContext, "")
3418 .setContentText("bar");
3419 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3420 nb2.build(), new UserHandle(mUid), null, 0);
3421 NotificationRecord r2 =
3422 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
3423
3424 assertTrue(mService.isVisuallyInterruptive(r1, r2));
3425 }
3426
3427 @Test
Dan Sandler7d67bd42018-05-15 14:06:38 -04003428 public void testVisualDifference_sameText() {
3429 Notification.Builder nb1 = new Notification.Builder(mContext, "")
3430 .setContentText("foo");
3431 StatusBarNotification sbn1 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3432 nb1.build(), new UserHandle(mUid), null, 0);
3433 NotificationRecord r1 =
3434 new NotificationRecord(mContext, sbn1, mock(NotificationChannel.class));
3435
3436 Notification.Builder nb2 = new Notification.Builder(mContext, "")
3437 .setContentText("foo");
3438 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3439 nb2.build(), new UserHandle(mUid), null, 0);
3440 NotificationRecord r2 =
3441 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
3442
3443 assertFalse(mService.isVisuallyInterruptive(r1, r2));
3444 }
3445
3446 @Test
3447 public void testVisualDifference_sameTextButStyled() {
3448 Notification.Builder nb1 = new Notification.Builder(mContext, "")
3449 .setContentText(Html.fromHtml("<b>foo</b>"));
3450 StatusBarNotification sbn1 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3451 nb1.build(), new UserHandle(mUid), null, 0);
3452 NotificationRecord r1 =
3453 new NotificationRecord(mContext, sbn1, mock(NotificationChannel.class));
3454
3455 Notification.Builder nb2 = new Notification.Builder(mContext, "")
3456 .setContentText(Html.fromHtml("<b>foo</b>"));
3457 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3458 nb2.build(), new UserHandle(mUid), null, 0);
3459 NotificationRecord r2 =
3460 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
3461
3462 assertFalse(mService.isVisuallyInterruptive(r1, r2));
3463 }
3464
3465 @Test
3466 public void testVisualDifference_diffTextButStyled() {
3467 Notification.Builder nb1 = new Notification.Builder(mContext, "")
3468 .setContentText(Html.fromHtml("<b>foo</b>"));
3469 StatusBarNotification sbn1 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3470 nb1.build(), new UserHandle(mUid), null, 0);
3471 NotificationRecord r1 =
3472 new NotificationRecord(mContext, sbn1, mock(NotificationChannel.class));
3473
3474 Notification.Builder nb2 = new Notification.Builder(mContext, "")
3475 .setContentText(Html.fromHtml("<b>bar</b>"));
3476 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3477 nb2.build(), new UserHandle(mUid), null, 0);
3478 NotificationRecord r2 =
3479 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
3480
3481 assertTrue(mService.isVisuallyInterruptive(r1, r2));
3482 }
3483
3484 @Test
Julia Reynolds7217dc92018-03-07 12:12:09 -05003485 public void testVisualDifference_diffProgress() {
3486 Notification.Builder nb1 = new Notification.Builder(mContext, "")
3487 .setProgress(100, 90, false);
3488 StatusBarNotification sbn1 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3489 nb1.build(), new UserHandle(mUid), null, 0);
3490 NotificationRecord r1 =
3491 new NotificationRecord(mContext, sbn1, mock(NotificationChannel.class));
3492
3493 Notification.Builder nb2 = new Notification.Builder(mContext, "")
3494 .setProgress(100, 100, false);
3495 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3496 nb2.build(), new UserHandle(mUid), null, 0);
3497 NotificationRecord r2 =
3498 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
3499
3500 assertTrue(mService.isVisuallyInterruptive(r1, r2));
3501 }
3502
3503 @Test
3504 public void testVisualDifference_diffProgressNotDone() {
3505 Notification.Builder nb1 = new Notification.Builder(mContext, "")
3506 .setProgress(100, 90, false);
3507 StatusBarNotification sbn1 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3508 nb1.build(), new UserHandle(mUid), null, 0);
3509 NotificationRecord r1 =
3510 new NotificationRecord(mContext, sbn1, mock(NotificationChannel.class));
3511
3512 Notification.Builder nb2 = new Notification.Builder(mContext, "")
3513 .setProgress(100, 91, false);
3514 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3515 nb2.build(), new UserHandle(mUid), null, 0);
3516 NotificationRecord r2 =
3517 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
3518
3519 assertFalse(mService.isVisuallyInterruptive(r1, r2));
3520 }
Beverly5a20a5e2018-03-06 15:02:44 -05003521
3522 @Test
Dan Sandler7d67bd42018-05-15 14:06:38 -04003523 public void testVisualDifference_sameProgressStillDone() {
3524 Notification.Builder nb1 = new Notification.Builder(mContext, "")
3525 .setProgress(100, 100, false);
3526 StatusBarNotification sbn1 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3527 nb1.build(), new UserHandle(mUid), null, 0);
3528 NotificationRecord r1 =
3529 new NotificationRecord(mContext, sbn1, mock(NotificationChannel.class));
3530
3531 Notification.Builder nb2 = new Notification.Builder(mContext, "")
3532 .setProgress(100, 100, false);
3533 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3534 nb2.build(), new UserHandle(mUid), null, 0);
3535 NotificationRecord r2 =
3536 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
3537
3538 assertFalse(mService.isVisuallyInterruptive(r1, r2));
3539 }
3540
3541 @Test
Julia Reynoldsa4fb9da2018-06-04 12:27:58 -04003542 public void testVisualDifference_summary() {
3543 Notification.Builder nb1 = new Notification.Builder(mContext, "")
3544 .setGroup("bananas")
3545 .setFlag(Notification.FLAG_GROUP_SUMMARY, true)
3546 .setContentText("foo");
3547 StatusBarNotification sbn1 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3548 nb1.build(), new UserHandle(mUid), null, 0);
3549 NotificationRecord r1 =
3550 new NotificationRecord(mContext, sbn1, mock(NotificationChannel.class));
3551
3552 Notification.Builder nb2 = new Notification.Builder(mContext, "")
3553 .setGroup("bananas")
3554 .setFlag(Notification.FLAG_GROUP_SUMMARY, true)
3555 .setContentText("bar");
3556 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3557 nb2.build(), new UserHandle(mUid), null, 0);
3558 NotificationRecord r2 =
3559 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
3560
3561 assertFalse(mService.isVisuallyInterruptive(r1, r2));
3562 }
3563
3564 @Test
Julia Reynolds760fa762018-06-19 15:39:23 -04003565 public void testVisualDifference_summaryNewNotification() {
3566 Notification.Builder nb2 = new Notification.Builder(mContext, "")
3567 .setGroup("bananas")
3568 .setFlag(Notification.FLAG_GROUP_SUMMARY, true)
3569 .setContentText("bar");
3570 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3571 nb2.build(), new UserHandle(mUid), null, 0);
3572 NotificationRecord r2 =
3573 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
3574
3575 assertFalse(mService.isVisuallyInterruptive(null, r2));
3576 }
3577
3578 @Test
Beverly5a20a5e2018-03-06 15:02:44 -05003579 public void testHideAndUnhideNotificationsOnSuspendedPackageBroadcast() {
3580 // post 2 notification from this package
3581 final NotificationRecord notif1 = generateNotificationRecord(
3582 mTestNotificationChannel, 1, null, true);
3583 final NotificationRecord notif2 = generateNotificationRecord(
3584 mTestNotificationChannel, 2, null, false);
3585 mService.addNotification(notif1);
3586 mService.addNotification(notif2);
3587
3588 // on broadcast, hide the 2 notifications
3589 mService.simulatePackageSuspendBroadcast(true, PKG);
3590 ArgumentCaptor<List> captorHide = ArgumentCaptor.forClass(List.class);
3591 verify(mListeners, times(1)).notifyHiddenLocked(captorHide.capture());
3592 assertEquals(2, captorHide.getValue().size());
3593
3594 // on broadcast, unhide the 2 notifications
3595 mService.simulatePackageSuspendBroadcast(false, PKG);
3596 ArgumentCaptor<List> captorUnhide = ArgumentCaptor.forClass(List.class);
3597 verify(mListeners, times(1)).notifyUnhiddenLocked(captorUnhide.capture());
3598 assertEquals(2, captorUnhide.getValue().size());
3599 }
3600
3601 @Test
3602 public void testNoNotificationsHiddenOnSuspendedPackageBroadcast() {
3603 // post 2 notification from this package
3604 final NotificationRecord notif1 = generateNotificationRecord(
3605 mTestNotificationChannel, 1, null, true);
3606 final NotificationRecord notif2 = generateNotificationRecord(
3607 mTestNotificationChannel, 2, null, false);
3608 mService.addNotification(notif1);
3609 mService.addNotification(notif2);
3610
3611 // on broadcast, nothing is hidden since no notifications are of package "test_package"
3612 mService.simulatePackageSuspendBroadcast(true, "test_package");
3613 ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class);
3614 verify(mListeners, times(1)).notifyHiddenLocked(captor.capture());
3615 assertEquals(0, captor.getValue().size());
3616 }
Kristian Monsen05f34792018-04-09 10:27:16 +02003617
3618 @Test
Julia Reynolds0e5a3432019-01-17 09:40:46 -05003619 public void testHideAndUnhideNotificationsOnDistractingPackageBroadcast() {
3620 // Post 2 notifications from 2 packages
3621 NotificationRecord pkgA = new NotificationRecord(mContext,
3622 generateSbn("a", 1000, 9, 0), mTestNotificationChannel);
3623 mService.addNotification(pkgA);
3624 NotificationRecord pkgB = new NotificationRecord(mContext,
3625 generateSbn("b", 1001, 9, 0), mTestNotificationChannel);
3626 mService.addNotification(pkgB);
3627
3628 // on broadcast, hide one of the packages
3629 mService.simulatePackageDistractionBroadcast(
3630 PackageManager.RESTRICTION_HIDE_NOTIFICATIONS, new String[] {"a"});
3631 ArgumentCaptor<List<NotificationRecord>> captorHide = ArgumentCaptor.forClass(List.class);
3632 verify(mListeners, times(1)).notifyHiddenLocked(captorHide.capture());
3633 assertEquals(1, captorHide.getValue().size());
3634 assertEquals("a", captorHide.getValue().get(0).sbn.getPackageName());
3635
3636 // on broadcast, unhide the package
3637 mService.simulatePackageDistractionBroadcast(
3638 PackageManager.RESTRICTION_HIDE_FROM_SUGGESTIONS, new String[] {"a"});
3639 ArgumentCaptor<List<NotificationRecord>> captorUnhide = ArgumentCaptor.forClass(List.class);
3640 verify(mListeners, times(1)).notifyUnhiddenLocked(captorUnhide.capture());
3641 assertEquals(1, captorUnhide.getValue().size());
3642 assertEquals("a", captorUnhide.getValue().get(0).sbn.getPackageName());
3643 }
3644
3645 @Test
3646 public void testHideAndUnhideNotificationsOnDistractingPackageBroadcast_multiPkg() {
3647 // Post 2 notifications from 2 packages
3648 NotificationRecord pkgA = new NotificationRecord(mContext,
3649 generateSbn("a", 1000, 9, 0), mTestNotificationChannel);
3650 mService.addNotification(pkgA);
3651 NotificationRecord pkgB = new NotificationRecord(mContext,
3652 generateSbn("b", 1001, 9, 0), mTestNotificationChannel);
3653 mService.addNotification(pkgB);
3654
3655 // on broadcast, hide one of the packages
3656 mService.simulatePackageDistractionBroadcast(
3657 PackageManager.RESTRICTION_HIDE_NOTIFICATIONS, new String[] {"a", "b"});
3658 ArgumentCaptor<List<NotificationRecord>> captorHide = ArgumentCaptor.forClass(List.class);
3659 verify(mListeners, times(2)).notifyHiddenLocked(captorHide.capture());
3660 assertEquals(2, captorHide.getValue().size());
3661 assertEquals("a", captorHide.getValue().get(0).sbn.getPackageName());
3662 assertEquals("b", captorHide.getValue().get(1).sbn.getPackageName());
3663
3664 // on broadcast, unhide the package
3665 mService.simulatePackageDistractionBroadcast(
3666 PackageManager.RESTRICTION_HIDE_FROM_SUGGESTIONS, new String[] {"a", "b"});
3667 ArgumentCaptor<List<NotificationRecord>> captorUnhide = ArgumentCaptor.forClass(List.class);
3668 verify(mListeners, times(2)).notifyUnhiddenLocked(captorUnhide.capture());
3669 assertEquals(2, captorUnhide.getValue().size());
3670 assertEquals("a", captorUnhide.getValue().get(0).sbn.getPackageName());
3671 assertEquals("b", captorUnhide.getValue().get(1).sbn.getPackageName());
3672 }
3673
3674 @Test
3675 public void testNoNotificationsHiddenOnDistractingPackageBroadcast() {
3676 // post notification from this package
3677 final NotificationRecord notif1 = generateNotificationRecord(
3678 mTestNotificationChannel, 1, null, true);
3679 mService.addNotification(notif1);
3680
3681 // on broadcast, nothing is hidden since no notifications are of package "test_package"
3682 mService.simulatePackageDistractionBroadcast(
3683 PackageManager.RESTRICTION_HIDE_NOTIFICATIONS, new String[] {"test_package"});
3684 ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class);
3685 verify(mListeners, times(1)).notifyHiddenLocked(captor.capture());
3686 assertEquals(0, captor.getValue().size());
3687 }
3688
3689 @Test
Kristian Monsen05f34792018-04-09 10:27:16 +02003690 public void testCanUseManagedServicesLowRamNoWatchNullPkg() {
3691 when(mPackageManagerClient.hasSystemFeature(FEATURE_WATCH)).thenReturn(false);
3692 when(mActivityManager.isLowRamDevice()).thenReturn(true);
3693 when(mResources.getStringArray(R.array.config_allowedManagedServicesOnLowRamDevices))
3694 .thenReturn(new String[] {"a", "b", "c"});
3695 when(mContext.getResources()).thenReturn(mResources);
3696
Julia Reynoldsd0ceefa2019-03-03 16:10:52 -05003697 assertEquals(false, mService.canUseManagedServices(null, 0, null));
Kristian Monsen05f34792018-04-09 10:27:16 +02003698 }
3699
3700 @Test
3701 public void testCanUseManagedServicesLowRamNoWatchValidPkg() {
3702 when(mPackageManagerClient.hasSystemFeature(FEATURE_WATCH)).thenReturn(false);
3703 when(mActivityManager.isLowRamDevice()).thenReturn(true);
3704 when(mResources.getStringArray(R.array.config_allowedManagedServicesOnLowRamDevices))
3705 .thenReturn(new String[] {"a", "b", "c"});
3706 when(mContext.getResources()).thenReturn(mResources);
3707
Julia Reynoldsd0ceefa2019-03-03 16:10:52 -05003708 assertEquals(true, mService.canUseManagedServices("b", 0, null));
Kristian Monsen05f34792018-04-09 10:27:16 +02003709 }
3710
3711 @Test
3712 public void testCanUseManagedServicesLowRamNoWatchNoValidPkg() {
3713 when(mPackageManagerClient.hasSystemFeature(FEATURE_WATCH)).thenReturn(false);
3714 when(mActivityManager.isLowRamDevice()).thenReturn(true);
3715 when(mResources.getStringArray(R.array.config_allowedManagedServicesOnLowRamDevices))
3716 .thenReturn(new String[] {"a", "b", "c"});
3717 when(mContext.getResources()).thenReturn(mResources);
3718
Julia Reynoldsd0ceefa2019-03-03 16:10:52 -05003719 assertEquals(false, mService.canUseManagedServices("d", 0, null));
Kristian Monsen05f34792018-04-09 10:27:16 +02003720 }
3721
3722 @Test
3723 public void testCanUseManagedServicesLowRamWatchNoValidPkg() {
3724 when(mPackageManagerClient.hasSystemFeature(FEATURE_WATCH)).thenReturn(true);
3725 when(mActivityManager.isLowRamDevice()).thenReturn(true);
3726 when(mResources.getStringArray(R.array.config_allowedManagedServicesOnLowRamDevices))
3727 .thenReturn(new String[] {"a", "b", "c"});
3728 when(mContext.getResources()).thenReturn(mResources);
3729
Julia Reynoldsd0ceefa2019-03-03 16:10:52 -05003730 assertEquals(true, mService.canUseManagedServices("d", 0, null));
Kristian Monsen05f34792018-04-09 10:27:16 +02003731 }
3732
3733 @Test
3734 public void testCanUseManagedServicesNoLowRamNoWatchValidPkg() {
3735 when(mPackageManagerClient.hasSystemFeature(FEATURE_WATCH)).thenReturn(false);
3736 when(mActivityManager.isLowRamDevice()).thenReturn(false);
3737 when(mResources.getStringArray(R.array.config_allowedManagedServicesOnLowRamDevices))
3738 .thenReturn(new String[] {"a", "b", "c"});
3739 when(mContext.getResources()).thenReturn(mResources);
3740
Julia Reynoldsd0ceefa2019-03-03 16:10:52 -05003741 assertEquals(true, mService.canUseManagedServices("d", 0 , null));
Kristian Monsen05f34792018-04-09 10:27:16 +02003742 }
3743
3744 @Test
3745 public void testCanUseManagedServicesNoLowRamWatchValidPkg() {
3746 when(mPackageManagerClient.hasSystemFeature(FEATURE_WATCH)).thenReturn(true);
3747 when(mActivityManager.isLowRamDevice()).thenReturn(false);
3748 when(mResources.getStringArray(R.array.config_allowedManagedServicesOnLowRamDevices))
3749 .thenReturn(new String[] {"a", "b", "c"});
3750 when(mContext.getResources()).thenReturn(mResources);
3751
Julia Reynoldsd0ceefa2019-03-03 16:10:52 -05003752 assertEquals(true, mService.canUseManagedServices("d", 0, null));
3753 }
3754
3755 @Test
3756 public void testCanUseManagedServices_hasPermission() throws Exception {
3757 when(mPackageManager.checkPermission("perm", "pkg", 0))
3758 .thenReturn(PackageManager.PERMISSION_GRANTED);
3759
3760 assertEquals(true, mService.canUseManagedServices("pkg", 0, "perm"));
3761 }
3762
3763 @Test
3764 public void testCanUseManagedServices_noPermission() throws Exception {
3765 when(mPackageManager.checkPermission("perm", "pkg", 0))
3766 .thenReturn(PackageManager.PERMISSION_DENIED);
3767
3768 assertEquals(false, mService.canUseManagedServices("pkg", 0, "perm"));
3769 }
3770
3771 @Test
3772 public void testCanUseManagedServices_permDoesNotMatter() {
3773 assertEquals(true, mService.canUseManagedServices("pkg", 0, null));
Kristian Monsen05f34792018-04-09 10:27:16 +02003774 }
Julia Reynoldsb3c68ff2018-05-22 14:58:39 -04003775
3776 @Test
3777 public void testOnNotificationVisibilityChanged_triggersInterruptionUsageStat() {
3778 final NotificationRecord r = generateNotificationRecord(
3779 mTestNotificationChannel, 1, null, true);
3780 r.setTextChanged(true);
3781 mService.addNotification(r);
3782
3783 mService.mNotificationDelegate.onNotificationVisibilityChanged(new NotificationVisibility[]
3784 {NotificationVisibility.obtain(r.getKey(), 1, 1, true)},
3785 new NotificationVisibility[]{});
3786
3787 verify(mAppUsageStats).reportInterruptiveNotification(anyString(), anyString(), anyInt());
3788 }
3789
3790 @Test
3791 public void testSetNotificationsShownFromListener_triggersInterruptionUsageStat()
3792 throws RemoteException {
3793 final NotificationRecord r = generateNotificationRecord(
3794 mTestNotificationChannel, 1, null, true);
3795 r.setTextChanged(true);
3796 mService.addNotification(r);
3797
3798 mBinderService.setNotificationsShownFromListener(null, new String[] {r.getKey()});
3799
3800 verify(mAppUsageStats).reportInterruptiveNotification(anyString(), anyString(), anyInt());
3801 }
3802
3803 @Test
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04003804 public void testMaybeRecordInterruptionLocked_doesNotRecordTwice()
Julia Reynoldsb3c68ff2018-05-22 14:58:39 -04003805 throws RemoteException {
3806 final NotificationRecord r = generateNotificationRecord(
3807 mTestNotificationChannel, 1, null, true);
3808 r.setInterruptive(true);
3809 mService.addNotification(r);
3810
3811 mService.maybeRecordInterruptionLocked(r);
3812 mService.maybeRecordInterruptionLocked(r);
3813
3814 verify(mAppUsageStats, times(1)).reportInterruptiveNotification(
3815 anyString(), anyString(), anyInt());
3816 }
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04003817
3818 @Test
Mady Mellorc39b4ae2019-01-09 17:11:37 -08003819 public void testBubble() throws Exception {
3820 mBinderService.setBubblesAllowed(PKG, mUid, false);
3821 assertFalse(mBinderService.areBubblesAllowedForPackage(PKG, mUid));
Julia Reynolds33ab8a02018-12-17 16:19:52 -05003822 }
3823
3824 @Test
Mady Mellor9db685a2019-01-23 13:23:37 -08003825 public void testUserApprovedBubblesForPackage() throws Exception {
3826 assertFalse(mBinderService.hasUserApprovedBubblesForPackage(PKG, mUid));
3827 mBinderService.setBubblesAllowed(PKG, mUid, true);
3828 assertTrue(mBinderService.hasUserApprovedBubblesForPackage(PKG, mUid));
3829 assertTrue(mBinderService.areBubblesAllowedForPackage(PKG, mUid));
3830 }
3831
3832 @Test
3833 public void testUserRejectsBubblesForPackage() throws Exception {
3834 assertFalse(mBinderService.hasUserApprovedBubblesForPackage(PKG, mUid));
3835 mBinderService.setBubblesAllowed(PKG, mUid, false);
3836 assertTrue(mBinderService.hasUserApprovedBubblesForPackage(PKG, mUid));
3837 assertFalse(mBinderService.areBubblesAllowedForPackage(PKG, mUid));
3838 }
3839
3840 @Test
Julia Reynoldsb6634872018-09-25 13:19:53 -04003841 public void testIsCallerInstantApp_primaryUser() throws Exception {
3842 ApplicationInfo info = new ApplicationInfo();
3843 info.privateFlags = ApplicationInfo.PRIVATE_FLAG_INSTANT;
3844 when(mPackageManager.getApplicationInfo(anyString(), anyInt(), eq(0))).thenReturn(info);
Julia Reynolds268647a2018-10-25 16:54:27 -04003845 when(mPackageManager.getPackagesForUid(anyInt())).thenReturn(new String[]{"any"});
Julia Reynoldsb6634872018-09-25 13:19:53 -04003846
Julia Reynolds268647a2018-10-25 16:54:27 -04003847 assertTrue(mService.isCallerInstantApp(45770, 0));
Julia Reynoldsb6634872018-09-25 13:19:53 -04003848
3849 info.privateFlags = 0;
Julia Reynolds268647a2018-10-25 16:54:27 -04003850 assertFalse(mService.isCallerInstantApp(575370, 0));
Julia Reynoldsb6634872018-09-25 13:19:53 -04003851 }
3852
3853 @Test
3854 public void testIsCallerInstantApp_secondaryUser() throws Exception {
3855 ApplicationInfo info = new ApplicationInfo();
3856 info.privateFlags = ApplicationInfo.PRIVATE_FLAG_INSTANT;
3857 when(mPackageManager.getApplicationInfo(anyString(), anyInt(), eq(10))).thenReturn(info);
3858 when(mPackageManager.getApplicationInfo(anyString(), anyInt(), eq(0))).thenReturn(null);
Julia Reynolds268647a2018-10-25 16:54:27 -04003859 when(mPackageManager.getPackagesForUid(anyInt())).thenReturn(new String[]{"any"});
Julia Reynoldsb6634872018-09-25 13:19:53 -04003860
Julia Reynolds268647a2018-10-25 16:54:27 -04003861 assertTrue(mService.isCallerInstantApp(68638450, 10));
Julia Reynoldsb6634872018-09-25 13:19:53 -04003862 }
3863
3864 @Test
Julia Reynolds86869c92019-06-21 10:45:06 -04003865 public void testIsCallerInstantApp_userAllNotification() throws Exception {
3866 ApplicationInfo info = new ApplicationInfo();
3867 info.privateFlags = ApplicationInfo.PRIVATE_FLAG_INSTANT;
3868 when(mPackageManager.getApplicationInfo(anyString(), anyInt(), eq(UserHandle.USER_SYSTEM)))
3869 .thenReturn(info);
3870 when(mPackageManager.getPackagesForUid(anyInt())).thenReturn(new String[]{"any"});
3871
3872 assertTrue(mService.isCallerInstantApp(45770, UserHandle.USER_ALL));
3873
3874 info.privateFlags = 0;
3875 assertFalse(mService.isCallerInstantApp(575370, UserHandle.USER_ALL ));
3876 }
3877
3878 @Test
Julia Reynoldsb6634872018-09-25 13:19:53 -04003879 public void testResolveNotificationUid_sameApp_nonSystemUser() throws Exception {
3880 ApplicationInfo info = new ApplicationInfo();
3881 info.uid = Binder.getCallingUid();
3882 when(mPackageManager.getApplicationInfo(anyString(), anyInt(), eq(10))).thenReturn(info);
3883 when(mPackageManager.getApplicationInfo(anyString(), anyInt(), eq(0))).thenReturn(null);
3884
3885 int actualUid = mService.resolveNotificationUid("caller", "caller", info.uid, 10);
3886
3887 assertEquals(info.uid, actualUid);
3888 }
3889
3890 @Test
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04003891 public void testResolveNotificationUid_sameApp() throws Exception {
3892 ApplicationInfo info = new ApplicationInfo();
3893 info.uid = Binder.getCallingUid();
Julia Reynoldsb6634872018-09-25 13:19:53 -04003894 when(mPackageManager.getApplicationInfo(anyString(), anyInt(), eq(0))).thenReturn(info);
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04003895
3896 int actualUid = mService.resolveNotificationUid("caller", "caller", info.uid, 0);
3897
3898 assertEquals(info.uid, actualUid);
3899 }
3900
3901 @Test
Julia Reynoldsecc1b572018-10-01 16:19:24 -04003902 public void testResolveNotificationUid_sameAppDiffPackage() throws Exception {
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04003903 ApplicationInfo info = new ApplicationInfo();
3904 info.uid = Binder.getCallingUid();
Julia Reynoldsecc1b572018-10-01 16:19:24 -04003905 when(mPackageManager.getApplicationInfo(anyString(), anyInt(), eq(0))).thenReturn(info);
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04003906
Julia Reynoldsecc1b572018-10-01 16:19:24 -04003907 int actualUid = mService.resolveNotificationUid("caller", "callerAlso", info.uid, 0);
3908
3909 assertEquals(info.uid, actualUid);
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04003910 }
3911
3912 @Test
3913 public void testResolveNotificationUid_sameAppWrongUid() throws Exception {
3914 ApplicationInfo info = new ApplicationInfo();
3915 info.uid = 1356347;
3916 when(mPackageManager.getApplicationInfo(anyString(), anyInt(), anyInt())).thenReturn(info);
3917
3918 try {
3919 mService.resolveNotificationUid("caller", "caller", 9, 0);
3920 fail("Incorrect uid didn't throw security exception");
3921 } catch (SecurityException e) {
3922 // yay
3923 }
3924 }
3925
3926 @Test
3927 public void testResolveNotificationUid_delegateAllowed() throws Exception {
3928 int expectedUid = 123;
3929
3930 when(mPackageManagerClient.getPackageUidAsUser("target", 0)).thenReturn(expectedUid);
3931 mService.setPreferencesHelper(mPreferencesHelper);
3932 when(mPreferencesHelper.isDelegateAllowed(anyString(), anyInt(), anyString(), anyInt()))
3933 .thenReturn(true);
3934
3935 assertEquals(expectedUid, mService.resolveNotificationUid("caller", "target", 9, 0));
3936 }
3937
3938 @Test
3939 public void testResolveNotificationUid_androidAllowed() throws Exception {
3940 int expectedUid = 123;
3941
3942 when(mPackageManagerClient.getPackageUidAsUser("target", 0)).thenReturn(expectedUid);
3943 // no delegate
3944
3945 assertEquals(expectedUid, mService.resolveNotificationUid("android", "target", 0, 0));
3946 }
3947
3948 @Test
3949 public void testResolveNotificationUid_delegateNotAllowed() throws Exception {
3950 when(mPackageManagerClient.getPackageUidAsUser("target", 0)).thenReturn(123);
3951 // no delegate
3952
3953 try {
3954 mService.resolveNotificationUid("caller", "target", 9, 0);
3955 fail("Incorrect uid didn't throw security exception");
3956 } catch (SecurityException e) {
3957 // yay
3958 }
3959 }
Julia Reynolds564273f2018-09-13 15:53:11 -04003960
3961 @Test
3962 public void testRemoveForegroundServiceFlagFromNotification_enqueued() {
3963 Notification n = new Notification.Builder(mContext, "").build();
3964 n.flags |= FLAG_FOREGROUND_SERVICE;
3965
3966 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 9, null, mUid, 0,
3967 n, new UserHandle(mUid), null, 0);
3968 NotificationRecord r = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
3969
3970 mService.addEnqueuedNotification(r);
3971
3972 mInternalService.removeForegroundServiceFlagFromNotification(
3973 PKG, r.sbn.getId(), r.sbn.getUserId());
3974
3975 waitForIdle();
3976
3977 verify(mListeners, timeout(200).times(0)).notifyPostedLocked(any(), any());
3978 }
3979
3980 @Test
3981 public void testRemoveForegroundServiceFlagFromNotification_posted() {
3982 Notification n = new Notification.Builder(mContext, "").build();
3983 n.flags |= FLAG_FOREGROUND_SERVICE;
3984
3985 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 9, null, mUid, 0,
3986 n, new UserHandle(mUid), null, 0);
3987 NotificationRecord r = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
3988
3989 mService.addNotification(r);
3990
3991 mInternalService.removeForegroundServiceFlagFromNotification(
3992 PKG, r.sbn.getId(), r.sbn.getUserId());
3993
3994 waitForIdle();
3995
3996 ArgumentCaptor<NotificationRecord> captor =
3997 ArgumentCaptor.forClass(NotificationRecord.class);
3998 verify(mListeners, times(1)).notifyPostedLocked(captor.capture(), any());
3999
4000 assertEquals(0, captor.getValue().getNotification().flags);
4001 }
Beverly58b24532018-10-02 09:08:23 -04004002
4003 @Test
4004 public void testAllowForegroundToasts() throws Exception {
4005 final String testPackage = "testPackageName";
4006 assertEquals(0, mService.mToastQueue.size());
4007 mService.isSystemUid = false;
4008
4009 // package is not suspended
4010 when(mPackageManager.isPackageSuspendedForUser(testPackage, UserHandle.getUserId(mUid)))
4011 .thenReturn(false);
4012
4013 // notifications from this package are blocked by the user
4014 mService.setPreferencesHelper(mPreferencesHelper);
4015 when(mPreferencesHelper.getImportance(testPackage, mUid)).thenReturn(IMPORTANCE_NONE);
4016
4017 // this app is in the foreground
4018 when(mActivityManager.getUidImportance(mUid)).thenReturn(IMPORTANCE_FOREGROUND);
4019
4020 // enqueue toast -> toast should still enqueue
4021 ((INotificationManager)mService.mService).enqueueToast(testPackage,
4022 new TestableToastCallback(), 2000, 0);
4023 assertEquals(1, mService.mToastQueue.size());
4024 }
4025
4026 @Test
4027 public void testDisallowToastsFromSuspendedPackages() throws Exception {
4028 final String testPackage = "testPackageName";
4029 assertEquals(0, mService.mToastQueue.size());
4030 mService.isSystemUid = false;
4031
4032 // package is suspended
4033 when(mPackageManager.isPackageSuspendedForUser(testPackage, UserHandle.getUserId(mUid)))
4034 .thenReturn(true);
4035
4036 // notifications from this package are NOT blocked by the user
4037 mService.setPreferencesHelper(mPreferencesHelper);
4038 when(mPreferencesHelper.getImportance(testPackage, mUid)).thenReturn(IMPORTANCE_LOW);
4039
4040 // enqueue toast -> no toasts enqueued
4041 ((INotificationManager)mService.mService).enqueueToast(testPackage,
4042 new TestableToastCallback(), 2000, 0);
4043 assertEquals(0, mService.mToastQueue.size());
4044 }
4045
4046 @Test
4047 public void testDisallowToastsFromBlockedApps() throws Exception {
4048 final String testPackage = "testPackageName";
4049 assertEquals(0, mService.mToastQueue.size());
4050 mService.isSystemUid = false;
4051
4052 // package is not suspended
4053 when(mPackageManager.isPackageSuspendedForUser(testPackage, UserHandle.getUserId(mUid)))
4054 .thenReturn(false);
4055
4056 // notifications from this package are blocked by the user
4057 mService.setPreferencesHelper(mPreferencesHelper);
4058 when(mPreferencesHelper.getImportance(testPackage, mUid)).thenReturn(IMPORTANCE_NONE);
4059
4060 // this app is NOT in the foreground
4061 when(mActivityManager.getUidImportance(mUid)).thenReturn(IMPORTANCE_GONE);
4062
4063 // enqueue toast -> no toasts enqueued
4064 ((INotificationManager)mService.mService).enqueueToast(testPackage,
4065 new TestableToastCallback(), 2000, 0);
4066 assertEquals(0, mService.mToastQueue.size());
4067 }
4068
4069 @Test
4070 public void testAlwaysAllowSystemToasts() throws Exception {
4071 final String testPackage = "testPackageName";
4072 assertEquals(0, mService.mToastQueue.size());
4073 mService.isSystemUid = true;
4074
4075 // package is suspended
4076 when(mPackageManager.isPackageSuspendedForUser(testPackage, UserHandle.getUserId(mUid)))
4077 .thenReturn(true);
4078
4079 // notifications from this package ARE blocked by the user
4080 mService.setPreferencesHelper(mPreferencesHelper);
4081 when(mPreferencesHelper.getImportance(testPackage, mUid)).thenReturn(IMPORTANCE_NONE);
4082
4083 // this app is NOT in the foreground
4084 when(mActivityManager.getUidImportance(mUid)).thenReturn(IMPORTANCE_GONE);
4085
4086 // enqueue toast -> system toast can still be enqueued
4087 ((INotificationManager)mService.mService).enqueueToast(testPackage,
4088 new TestableToastCallback(), 2000, 0);
4089 assertEquals(1, mService.mToastQueue.size());
4090 }
Tony Mak29996702018-11-26 16:23:34 +00004091
4092 @Test
4093 public void testOnNotificationSmartReplySent() {
4094 final int replyIndex = 2;
4095 final String reply = "Hello";
Milo Sredkov13d88112019-02-01 12:23:24 +00004096 final boolean modifiedBeforeSending = true;
Tony Mak29996702018-11-26 16:23:34 +00004097 final boolean generatedByAssistant = true;
4098
4099 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
Milo Sredkov13d88112019-02-01 12:23:24 +00004100 r.setSuggestionsGeneratedByAssistant(generatedByAssistant);
Tony Mak29996702018-11-26 16:23:34 +00004101 mService.addNotification(r);
4102
4103 mService.mNotificationDelegate.onNotificationSmartReplySent(
Milo Sredkov13d88112019-02-01 12:23:24 +00004104 r.getKey(), replyIndex, reply, NOTIFICATION_LOCATION_UNKNOWN,
4105 modifiedBeforeSending);
Tony Mak29996702018-11-26 16:23:34 +00004106 verify(mAssistants).notifyAssistantSuggestedReplySent(
4107 eq(r.sbn), eq(reply), eq(generatedByAssistant));
4108 }
Tony Mak7d4b3a52018-11-27 17:29:36 +00004109
4110 @Test
4111 public void testOnNotificationActionClick() {
4112 final int actionIndex = 2;
4113 final Notification.Action action =
4114 new Notification.Action.Builder(null, "text", null).build();
4115 final boolean generatedByAssistant = false;
4116
4117 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
4118 mService.addNotification(r);
4119
4120 NotificationVisibility notificationVisibility =
4121 NotificationVisibility.obtain(r.getKey(), 1, 2, true);
4122 mService.mNotificationDelegate.onNotificationActionClick(
4123 10, 10, r.getKey(), actionIndex, action, notificationVisibility,
4124 generatedByAssistant);
4125 verify(mAssistants).notifyAssistantActionClicked(
4126 eq(r.sbn), eq(actionIndex), eq(action), eq(generatedByAssistant));
4127 }
Gustav Sennton44dc5882018-12-13 14:38:50 +00004128
4129 @Test
4130 public void testLogSmartSuggestionsVisible_triggerOnExpandAndVisible() {
4131 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
4132 mService.addNotification(r);
4133
Gustav Senntona8e38aa2019-01-22 14:55:39 +00004134 mService.mNotificationDelegate.onNotificationExpansionChanged(r.getKey(), false, true,
4135 NOTIFICATION_LOCATION_UNKNOWN);
Gustav Sennton44dc5882018-12-13 14:38:50 +00004136 NotificationVisibility[] notificationVisibility = new NotificationVisibility[] {
4137 NotificationVisibility.obtain(r.getKey(), 0, 0, true)
4138 };
4139 mService.mNotificationDelegate.onNotificationVisibilityChanged(notificationVisibility,
4140 new NotificationVisibility[0]);
4141
4142 assertEquals(1, mService.countLogSmartSuggestionsVisible);
4143 }
4144
4145 @Test
4146 public void testLogSmartSuggestionsVisible_noTriggerOnExpand() {
4147 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
4148 mService.addNotification(r);
4149
Gustav Senntona8e38aa2019-01-22 14:55:39 +00004150 mService.mNotificationDelegate.onNotificationExpansionChanged(r.getKey(), false, true,
4151 NOTIFICATION_LOCATION_UNKNOWN);
Gustav Sennton44dc5882018-12-13 14:38:50 +00004152
4153 assertEquals(0, mService.countLogSmartSuggestionsVisible);
4154 }
4155
4156 @Test
4157 public void testLogSmartSuggestionsVisible_noTriggerOnVisible() {
4158 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
4159 mService.addNotification(r);
4160
Julia Reynolds95334132018-12-19 11:15:35 -05004161 NotificationVisibility[] notificationVisibility = new NotificationVisibility[]{
Gustav Sennton44dc5882018-12-13 14:38:50 +00004162 NotificationVisibility.obtain(r.getKey(), 0, 0, true)
4163 };
4164 mService.mNotificationDelegate.onNotificationVisibilityChanged(notificationVisibility,
4165 new NotificationVisibility[0]);
4166
4167 assertEquals(0, mService.countLogSmartSuggestionsVisible);
4168 }
Julia Reynolds95334132018-12-19 11:15:35 -05004169
4170 public void testReportSeen_delegated() {
4171 Notification.Builder nb =
4172 new Notification.Builder(mContext, mTestNotificationChannel.getId())
4173 .setContentTitle("foo")
4174 .setSmallIcon(android.R.drawable.sym_def_app_icon);
4175
4176 StatusBarNotification sbn = new StatusBarNotification(PKG, "opPkg", 0, "tag", mUid, 0,
4177 nb.build(), new UserHandle(mUid), null, 0);
4178 NotificationRecord r = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
4179
4180 mService.reportSeen(r);
4181 verify(mAppUsageStats, never()).reportEvent(anyString(), anyInt(), anyInt());
4182
4183 }
4184
4185 @Test
4186 public void testReportSeen_notDelegated() {
4187 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
4188
4189 mService.reportSeen(r);
4190 verify(mAppUsageStats, times(1)).reportEvent(anyString(), anyInt(), anyInt());
4191 }
Julia Reynolds3207e2f2018-12-20 09:39:53 -05004192
4193 @Test
4194 public void testNotificationStats_notificationError() {
4195 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
4196 mService.addNotification(r);
4197
4198 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, "tag", mUid, 0,
4199 new Notification.Builder(mContext, mTestNotificationChannel.getId()).build(),
4200 new UserHandle(mUid), null, 0);
4201 NotificationRecord update = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
4202 mService.addEnqueuedNotification(update);
4203 assertNull(update.sbn.getNotification().getSmallIcon());
4204
4205 NotificationManagerService.PostNotificationRunnable runnable =
4206 mService.new PostNotificationRunnable(update.getKey());
4207 runnable.run();
4208 waitForIdle();
4209
4210 ArgumentCaptor<NotificationStats> captor = ArgumentCaptor.forClass(NotificationStats.class);
4211 verify(mListeners).notifyRemovedLocked(any(), anyInt(), captor.capture());
4212 assertNotNull(captor.getValue());
4213 }
Tony Mak9a3c1f12019-03-04 16:04:42 +00004214
4215 @Test
Julia Reynolds7a6d07a2019-03-18 11:31:56 -04004216 public void testCanNotifyAsUser_crossUser() throws Exception {
4217 // same user no problem
4218 mBinderService.canNotifyAsPackage("src", "target", mContext.getUserId());
4219
4220 // cross user, no permission, problem
4221 try {
4222 mBinderService.canNotifyAsPackage("src", "target", mContext.getUserId() + 1);
4223 fail("Should not be callable cross user without cross user permission");
4224 } catch (SecurityException e) {
4225 // good
4226 }
4227
4228 // cross user, with permission, no problem
4229 TestablePermissions perms = mContext.getTestablePermissions();
4230 perms.setPermission(android.Manifest.permission.INTERACT_ACROSS_USERS, PERMISSION_GRANTED);
4231 mBinderService.canNotifyAsPackage("src", "target", mContext.getUserId() + 1);
4232 }
4233
4234 @Test
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -04004235 public void testgetNotificationChannels_crossUser() throws Exception {
4236 // same user no problem
4237 mBinderService.getNotificationChannels("src", "target", mContext.getUserId());
4238
4239 // cross user, no permission, problem
4240 try {
4241 mBinderService.getNotificationChannels("src", "target", mContext.getUserId() + 1);
4242 fail("Should not be callable cross user without cross user permission");
4243 } catch (SecurityException e) {
4244 // good
4245 }
4246
4247 // cross user, with permission, no problem
4248 TestablePermissions perms = mContext.getTestablePermissions();
4249 perms.setPermission(android.Manifest.permission.INTERACT_ACROSS_USERS, PERMISSION_GRANTED);
4250 mBinderService.getNotificationChannels("src", "target", mContext.getUserId() + 1);
4251 }
4252
4253 @Test
Tony Mak9a3c1f12019-03-04 16:04:42 +00004254 public void setDefaultAssistantForUser_fromConfigXml() {
4255 clearDeviceConfig();
4256 ComponentName xmlConfig = new ComponentName("config", "xml");
4257 when(mResources
4258 .getString(
4259 com.android.internal.R.string.config_defaultAssistantAccessComponent))
4260 .thenReturn(xmlConfig.flattenToString());
4261 when(mContext.getResources()).thenReturn(mResources);
4262 when(mAssistants.queryPackageForServices(eq(null), anyInt(), eq(0)))
4263 .thenReturn(Collections.singleton(xmlConfig));
4264 mService.setNotificationAssistantAccessGrantedCallback(
4265 mNotificationAssistantAccessGrantedCallback);
4266
4267 mService.setDefaultAssistantForUser(0);
4268
4269 verify(mNotificationAssistantAccessGrantedCallback)
4270 .onGranted(eq(xmlConfig), eq(0), eq(true));
4271 }
4272
4273 @Test
4274 public void setDefaultAssistantForUser_fromDeviceConfig() {
4275 ComponentName xmlConfig = new ComponentName("xml", "config");
4276 ComponentName deviceConfig = new ComponentName("device", "config");
4277 setDefaultAssistantInDeviceConfig(deviceConfig.flattenToString());
4278 when(mResources
4279 .getString(com.android.internal.R.string.config_defaultAssistantAccessComponent))
4280 .thenReturn(xmlConfig.flattenToString());
4281 when(mContext.getResources()).thenReturn(mResources);
4282 when(mAssistants.queryPackageForServices(eq(null), anyInt(), eq(0)))
4283 .thenReturn(new ArraySet<>(Arrays.asList(xmlConfig, deviceConfig)));
4284 mService.setNotificationAssistantAccessGrantedCallback(
4285 mNotificationAssistantAccessGrantedCallback);
4286
4287 mService.setDefaultAssistantForUser(0);
4288
4289 verify(mNotificationAssistantAccessGrantedCallback)
4290 .onGranted(eq(deviceConfig), eq(0), eq(true));
4291 }
4292
4293 @Test
4294 public void setDefaultAssistantForUser_deviceConfigInvalid() {
4295 ComponentName xmlConfig = new ComponentName("xml", "config");
4296 ComponentName deviceConfig = new ComponentName("device", "config");
4297 setDefaultAssistantInDeviceConfig(deviceConfig.flattenToString());
4298 when(mResources
4299 .getString(com.android.internal.R.string.config_defaultAssistantAccessComponent))
4300 .thenReturn(xmlConfig.flattenToString());
4301 when(mContext.getResources()).thenReturn(mResources);
4302 // Only xmlConfig is valid, deviceConfig is not.
4303 when(mAssistants.queryPackageForServices(eq(null), anyInt(), eq(0)))
4304 .thenReturn(Collections.singleton(xmlConfig));
4305 mService.setNotificationAssistantAccessGrantedCallback(
4306 mNotificationAssistantAccessGrantedCallback);
4307
4308 mService.setDefaultAssistantForUser(0);
4309
4310 verify(mNotificationAssistantAccessGrantedCallback)
4311 .onGranted(eq(xmlConfig), eq(0), eq(true));
4312 }
4313
Mady Mellor7eb18ef2019-03-27 14:03:46 -07004314 @Test
Mady Mellor65dcaa92019-04-03 12:21:44 -07004315 public void testFlagBubble() throws RemoteException {
4316 // Bubbles are allowed!
Mady Mellorc6820342019-05-20 12:04:36 -07004317 setUpPrefsForBubbles(true /* global */, true /* app */, true /* channel */);
Mady Mellor65dcaa92019-04-03 12:21:44 -07004318
4319 // Notif with bubble metadata but not our other misc requirements
4320 NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel,
4321 null /* tvExtender */, true /* isBubble */);
4322
4323 // Say we're foreground
4324 when(mActivityManager.getPackageImportance(nr.sbn.getPackageName())).thenReturn(
4325 IMPORTANCE_FOREGROUND);
4326
4327 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
4328 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
4329 waitForIdle();
4330
4331 StatusBarNotification[] notifs = mBinderService.getActiveNotifications(PKG);
4332 assertEquals(1, notifs.length);
4333 assertTrue((notifs[0].getNotification().flags & FLAG_BUBBLE) != 0);
4334 assertTrue(mService.getNotificationRecord(
4335 nr.sbn.getKey()).getNotification().isBubbleNotification());
4336 }
4337
4338 @Test
Mady Mellorc6820342019-05-20 12:04:36 -07004339 public void testFlagBubble_noFlag_appNotAllowed() throws RemoteException {
4340 // Bubbles are allowed!
4341 setUpPrefsForBubbles(true /* global */, false /* app */, true /* channel */);
4342
4343 // Notif with bubble metadata but not our other misc requirements
4344 NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel,
4345 null /* tvExtender */, true /* isBubble */);
4346
4347 // Say we're foreground
4348 when(mActivityManager.getPackageImportance(nr.sbn.getPackageName())).thenReturn(
4349 IMPORTANCE_FOREGROUND);
4350
4351 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
4352 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
4353 waitForIdle();
4354
4355 StatusBarNotification[] notifs = mBinderService.getActiveNotifications(PKG);
4356 assertEquals(1, notifs.length);
4357 assertEquals((notifs[0].getNotification().flags & FLAG_BUBBLE), 0);
4358 assertFalse(mService.getNotificationRecord(
4359 nr.sbn.getKey()).getNotification().isBubbleNotification());
4360 }
4361
4362 @Test
Mady Mellorbe797962019-04-01 16:04:24 -07004363 public void testFlagBubbleNotifs_flag_appForeground() throws RemoteException {
Mady Mellor7eb18ef2019-03-27 14:03:46 -07004364 // Bubbles are allowed!
Mady Mellorc6820342019-05-20 12:04:36 -07004365 setUpPrefsForBubbles(true /* global */, true /* app */, true /* channel */);
Mady Mellor7eb18ef2019-03-27 14:03:46 -07004366
Mady Mellorbe797962019-04-01 16:04:24 -07004367 // Notif with bubble metadata but not our other misc requirements
4368 NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel,
4369 null /* tvExtender */, true /* isBubble */);
4370
4371 // Say we're foreground
4372 when(mActivityManager.getPackageImportance(nr.sbn.getPackageName())).thenReturn(
4373 IMPORTANCE_FOREGROUND);
4374
4375 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
4376 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
4377 waitForIdle();
4378
4379 // yes allowed, yes foreground, yes bubble
4380 assertTrue(mService.getNotificationRecord(
4381 nr.sbn.getKey()).getNotification().isBubbleNotification());
4382 }
4383
4384 @Test
4385 public void testFlagBubbleNotifs_noFlag_appNotForeground() throws RemoteException {
4386 // Bubbles are allowed!
Mady Mellorc6820342019-05-20 12:04:36 -07004387 setUpPrefsForBubbles(true /* global */, true /* app */, true /* channel */);
Mady Mellorbe797962019-04-01 16:04:24 -07004388
4389 // Notif with bubble metadata but not our other misc requirements
4390 NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel,
4391 null /* tvExtender */, true /* isBubble */);
4392
4393 // Make sure we're NOT foreground
4394 when(mActivityManager.getPackageImportance(nr.sbn.getPackageName())).thenReturn(
4395 IMPORTANCE_VISIBLE);
4396
4397 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
4398 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
4399 waitForIdle();
4400
4401 // yes allowed but NOT foreground, no bubble
4402 assertFalse(mService.getNotificationRecord(
4403 nr.sbn.getKey()).getNotification().isBubbleNotification());
4404 }
4405
4406 @Test
4407 public void testFlagBubbleNotifs_flag_previousForegroundFlag() throws RemoteException {
4408 // Bubbles are allowed!
Mady Mellorc6820342019-05-20 12:04:36 -07004409 setUpPrefsForBubbles(true /* global */, true /* app */, true /* channel */);
Mady Mellorbe797962019-04-01 16:04:24 -07004410
4411 // Notif with bubble metadata but not our other misc requirements
4412 NotificationRecord nr1 = generateNotificationRecord(mTestNotificationChannel,
4413 null /* tvExtender */, true /* isBubble */);
4414
4415 // Send notif when we're foreground
4416 when(mActivityManager.getPackageImportance(nr1.sbn.getPackageName())).thenReturn(
4417 IMPORTANCE_FOREGROUND);
4418 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
4419 nr1.sbn.getId(), nr1.sbn.getNotification(), nr1.sbn.getUserId());
4420 waitForIdle();
4421
4422 // yes allowed, yes foreground, yes bubble
4423 assertTrue(mService.getNotificationRecord(
4424 nr1.sbn.getKey()).getNotification().isBubbleNotification());
4425
4426 // Send a new update when we're not foreground
4427 NotificationRecord nr2 = generateNotificationRecord(mTestNotificationChannel,
4428 null /* tvExtender */, true /* isBubble */);
4429
4430 when(mActivityManager.getPackageImportance(nr2.sbn.getPackageName())).thenReturn(
4431 IMPORTANCE_VISIBLE);
4432 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
4433 nr2.sbn.getId(), nr2.sbn.getNotification(), nr2.sbn.getUserId());
4434 waitForIdle();
4435
4436 // yes allowed, previously foreground / flagged, yes bubble
4437 assertTrue(mService.getNotificationRecord(
4438 nr2.sbn.getKey()).getNotification().isBubbleNotification());
4439
4440 StatusBarNotification[] notifs2 = mBinderService.getActiveNotifications(PKG);
4441 assertEquals(1, notifs2.length);
4442 assertEquals(1, mService.getNotificationRecordCount());
4443 }
4444
4445 @Test
4446 public void testFlagBubbleNotifs_noFlag_previousForegroundFlag_afterRemoval()
4447 throws RemoteException {
4448 // Bubbles are allowed!
Mady Mellorc6820342019-05-20 12:04:36 -07004449 setUpPrefsForBubbles(true /* global */, true /* app */, true /* channel */);
Mady Mellorbe797962019-04-01 16:04:24 -07004450
4451 // Notif with bubble metadata but not our other misc requirements
4452 NotificationRecord nr1 = generateNotificationRecord(mTestNotificationChannel,
4453 null /* tvExtender */, true /* isBubble */);
4454
4455 // Send notif when we're foreground
4456 when(mActivityManager.getPackageImportance(nr1.sbn.getPackageName())).thenReturn(
4457 IMPORTANCE_FOREGROUND);
4458 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
4459 nr1.sbn.getId(), nr1.sbn.getNotification(), nr1.sbn.getUserId());
4460 waitForIdle();
4461
4462 // yes allowed, yes foreground, yes bubble
4463 assertTrue(mService.getNotificationRecord(
4464 nr1.sbn.getKey()).getNotification().isBubbleNotification());
4465
4466 // Remove the bubble
4467 mBinderService.cancelNotificationWithTag(PKG, "tag", nr1.sbn.getId(),
4468 nr1.sbn.getUserId());
4469 waitForIdle();
4470
4471 StatusBarNotification[] notifs = mBinderService.getActiveNotifications(PKG);
4472 assertEquals(0, notifs.length);
4473 assertEquals(0, mService.getNotificationRecordCount());
4474
4475 // Send a new update when we're not foreground
4476 NotificationRecord nr2 = generateNotificationRecord(mTestNotificationChannel,
4477 null /* tvExtender */, true /* isBubble */);
4478
4479 when(mActivityManager.getPackageImportance(nr2.sbn.getPackageName())).thenReturn(
4480 IMPORTANCE_VISIBLE);
4481 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
4482 nr2.sbn.getId(), nr2.sbn.getNotification(), nr2.sbn.getUserId());
4483 waitForIdle();
4484
4485 // yes allowed, but was removed & no foreground, so no bubble
4486 assertFalse(mService.getNotificationRecord(
4487 nr2.sbn.getKey()).getNotification().isBubbleNotification());
4488
4489 StatusBarNotification[] notifs2 = mBinderService.getActiveNotifications(PKG);
4490 assertEquals(1, notifs2.length);
4491 assertEquals(1, mService.getNotificationRecordCount());
4492 }
4493
4494 @Test
4495 public void testFlagBubbleNotifs_flag_messaging() throws RemoteException {
4496 // Bubbles are allowed!
Mady Mellorc6820342019-05-20 12:04:36 -07004497 setUpPrefsForBubbles(true /* global */, true /* app */, true /* channel */);
Mady Mellorbe797962019-04-01 16:04:24 -07004498
4499 // Give it bubble metadata
Mady Mellor7eb18ef2019-03-27 14:03:46 -07004500 Notification.BubbleMetadata data = getBasicBubbleMetadataBuilder().build();
Mady Mellorbe797962019-04-01 16:04:24 -07004501 // Give it a person
4502 Person person = new Person.Builder()
4503 .setName("bubblebot")
4504 .build();
Mady Mellora10448e2019-04-26 13:50:58 -07004505 // It needs remote input to be bubble-able
4506 RemoteInput remoteInput = new RemoteInput.Builder("reply_key").setLabel("reply").build();
4507 PendingIntent inputIntent = PendingIntent.getActivity(mContext, 0, new Intent(), 0);
4508 Icon icon = Icon.createWithResource(mContext, android.R.drawable.sym_def_app_icon);
4509 Notification.Action replyAction = new Notification.Action.Builder(icon, "Reply",
4510 inputIntent).addRemoteInput(remoteInput)
4511 .build();
Mady Mellorbe797962019-04-01 16:04:24 -07004512 // Make it messaging style
Mady Mellor7eb18ef2019-03-27 14:03:46 -07004513 Notification.Builder nb = new Notification.Builder(mContext,
4514 mTestNotificationChannel.getId())
4515 .setContentTitle("foo")
4516 .setBubbleMetadata(data)
Mady Mellorbe797962019-04-01 16:04:24 -07004517 .setStyle(new Notification.MessagingStyle(person)
4518 .setConversationTitle("Bubble Chat")
4519 .addMessage("Hello?",
4520 SystemClock.currentThreadTimeMillis() - 300000, person)
4521 .addMessage("Is it me you're looking for?",
4522 SystemClock.currentThreadTimeMillis(), person)
4523 )
Mady Mellora10448e2019-04-26 13:50:58 -07004524 .setActions(replyAction)
Mady Mellorbe797962019-04-01 16:04:24 -07004525 .setSmallIcon(android.R.drawable.sym_def_app_icon);
4526
4527 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, null, mUid, 0,
4528 nb.build(), new UserHandle(mUid), null, 0);
4529 NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
4530
4531 mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
4532 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
4533 waitForIdle();
4534
4535 // yes allowed, yes messaging, yes bubble
4536 assertTrue(mService.getNotificationRecord(
4537 sbn.getKey()).getNotification().isBubbleNotification());
4538 }
4539
4540 @Test
4541 public void testFlagBubbleNotifs_flag_phonecall() throws RemoteException {
4542 // Bubbles are allowed!
Mady Mellorc6820342019-05-20 12:04:36 -07004543 setUpPrefsForBubbles(true /* global */, true /* app */, true /* channel */);
Mady Mellorbe797962019-04-01 16:04:24 -07004544
4545 // Give it bubble metadata
4546 Notification.BubbleMetadata data = getBasicBubbleMetadataBuilder().build();
4547 // Give it a person
4548 Person person = new Person.Builder()
4549 .setName("bubblebot")
4550 .build();
4551 // Make it a phone call
4552 Notification.Builder nb = new Notification.Builder(mContext,
4553 mTestNotificationChannel.getId())
4554 .setCategory(CATEGORY_CALL)
4555 .addPerson(person)
4556 .setContentTitle("foo")
4557 .setBubbleMetadata(data)
4558 .setSmallIcon(android.R.drawable.sym_def_app_icon);
4559
4560 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, null, mUid, 0,
4561 nb.build(), new UserHandle(mUid), null, 0);
4562 // Make sure it has foreground service
4563 sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
4564 NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
4565
4566 mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
4567 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
4568 waitForIdle();
4569
4570 // yes phone call, yes person, yes foreground service, yes bubble
4571 assertTrue(mService.getNotificationRecord(
4572 sbn.getKey()).getNotification().isBubbleNotification());
4573 }
4574
4575 @Test
4576 public void testFlagBubbleNotifs_noFlag_phonecall_noForegroundService() throws RemoteException {
4577 // Bubbles are allowed!
Mady Mellorc6820342019-05-20 12:04:36 -07004578 setUpPrefsForBubbles(true /* global */, true /* app */, true /* channel */);
Mady Mellorbe797962019-04-01 16:04:24 -07004579
4580 // Give it bubble metadata
4581 Notification.BubbleMetadata data = getBasicBubbleMetadataBuilder().build();
4582 // Give it a person
4583 Person person = new Person.Builder()
4584 .setName("bubblebot")
4585 .build();
4586 // Make it a phone call
4587 Notification.Builder nb = new Notification.Builder(mContext,
4588 mTestNotificationChannel.getId())
4589 .setCategory(CATEGORY_CALL)
4590 .addPerson(person)
4591 .setContentTitle("foo")
4592 .setBubbleMetadata(data)
Mady Mellor7eb18ef2019-03-27 14:03:46 -07004593 .setSmallIcon(android.R.drawable.sym_def_app_icon);
4594
4595 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, null, mUid, 0,
4596 nb.build(), new UserHandle(mUid), null, 0);
4597 NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
4598
4599 mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
4600 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
4601 waitForIdle();
4602
Mady Mellorbe797962019-04-01 16:04:24 -07004603 // yes phone call, yes person, NO foreground service, no bubble
4604 assertFalse(mService.getNotificationRecord(
Mady Mellor7eb18ef2019-03-27 14:03:46 -07004605 sbn.getKey()).getNotification().isBubbleNotification());
4606 }
4607
4608 @Test
Mady Mellorbe797962019-04-01 16:04:24 -07004609 public void testFlagBubbleNotifs_noFlag_phonecall_noPerson() throws RemoteException {
4610 // Bubbles are allowed!
Mady Mellorc6820342019-05-20 12:04:36 -07004611 setUpPrefsForBubbles(true /* global */, true /* app */, true /* channel */);
Mady Mellorbe797962019-04-01 16:04:24 -07004612
4613 // Give it bubble metadata
4614 Notification.BubbleMetadata data = getBasicBubbleMetadataBuilder().build();
4615 // Make it a phone call
4616 Notification.Builder nb = new Notification.Builder(mContext,
4617 mTestNotificationChannel.getId())
4618 .setCategory(CATEGORY_CALL)
4619 .setContentTitle("foo")
4620 .setBubbleMetadata(data)
4621 .setSmallIcon(android.R.drawable.sym_def_app_icon);
4622
4623 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, null, mUid, 0,
4624 nb.build(), new UserHandle(mUid), null, 0);
4625 // Make sure it has foreground service
4626 sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
4627 NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
4628
4629 mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
4630 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
4631 waitForIdle();
4632
4633 // yes phone call, yes foreground service, BUT NO person, no bubble
4634 assertFalse(mService.getNotificationRecord(
4635 sbn.getKey()).getNotification().isBubbleNotification());
4636 }
4637
4638 @Test
4639 public void testFlagBubbleNotifs_noFlag_phonecall_noCategory() throws RemoteException {
4640 // Bubbles are allowed!
Mady Mellorc6820342019-05-20 12:04:36 -07004641 setUpPrefsForBubbles(true /* global */, true /* app */, true /* channel */);
Mady Mellorbe797962019-04-01 16:04:24 -07004642
4643 // Give it bubble metadata
4644 Notification.BubbleMetadata data = getBasicBubbleMetadataBuilder().build();
4645 // Give it a person
4646 Person person = new Person.Builder()
4647 .setName("bubblebot")
4648 .build();
4649 // No category
4650 Notification.Builder nb = new Notification.Builder(mContext,
4651 mTestNotificationChannel.getId())
4652 .addPerson(person)
4653 .setContentTitle("foo")
4654 .setBubbleMetadata(data)
4655 .setSmallIcon(android.R.drawable.sym_def_app_icon);
4656
4657 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, null, mUid, 0,
4658 nb.build(), new UserHandle(mUid), null, 0);
4659 // Make sure it has foreground service
4660 sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
4661 NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
4662
4663 mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
4664 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
4665 waitForIdle();
4666
4667 // yes person, yes foreground service, BUT NO call, no bubble
4668 assertFalse(mService.getNotificationRecord(
4669 sbn.getKey()).getNotification().isBubbleNotification());
4670 }
4671
4672 @Test
4673 public void testFlagBubbleNotifs_noFlag_messaging_appNotAllowed() throws RemoteException {
Mady Mellor7eb18ef2019-03-27 14:03:46 -07004674 // Bubbles are NOT allowed!
Mady Mellorc6820342019-05-20 12:04:36 -07004675 setUpPrefsForBubbles(false /* global */, true /* app */, true /* channel */);
Mady Mellor7eb18ef2019-03-27 14:03:46 -07004676
Mady Mellorbe797962019-04-01 16:04:24 -07004677 // Give it bubble metadata
Mady Mellor7eb18ef2019-03-27 14:03:46 -07004678 Notification.BubbleMetadata data = getBasicBubbleMetadataBuilder().build();
Mady Mellorbe797962019-04-01 16:04:24 -07004679 // Give it a person
4680 Person person = new Person.Builder()
4681 .setName("bubblebot")
4682 .build();
4683 // Make it messaging style
Mady Mellor7eb18ef2019-03-27 14:03:46 -07004684 Notification.Builder nb = new Notification.Builder(mContext,
4685 mTestNotificationChannel.getId())
4686 .setContentTitle("foo")
4687 .setBubbleMetadata(data)
Mady Mellorbe797962019-04-01 16:04:24 -07004688 .setStyle(new Notification.MessagingStyle(person)
4689 .setConversationTitle("Bubble Chat")
4690 .addMessage("Hello?",
4691 SystemClock.currentThreadTimeMillis() - 300000, person)
4692 .addMessage("Is it me you're looking for?",
4693 SystemClock.currentThreadTimeMillis(), person)
4694 )
Mady Mellor7eb18ef2019-03-27 14:03:46 -07004695 .setSmallIcon(android.R.drawable.sym_def_app_icon);
4696
4697 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, null, mUid, 0,
4698 nb.build(), new UserHandle(mUid), null, 0);
4699 NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
4700
4701 // Post the notification
4702 mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
4703 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
4704 waitForIdle();
4705
4706 // not allowed, no bubble
4707 assertFalse(mService.getNotificationRecord(
4708 sbn.getKey()).getNotification().isBubbleNotification());
4709 }
4710
4711 @Test
Mady Mellorbe797962019-04-01 16:04:24 -07004712 public void testFlagBubbleNotifs_noFlag_notBubble() throws RemoteException {
Mady Mellor7eb18ef2019-03-27 14:03:46 -07004713 // Bubbles are allowed!
Mady Mellorc6820342019-05-20 12:04:36 -07004714 setUpPrefsForBubbles(true /* global */, true /* app */, true /* channel */);
Mady Mellor7eb18ef2019-03-27 14:03:46 -07004715
4716 // Notif WITHOUT bubble metadata
Mady Mellorbe797962019-04-01 16:04:24 -07004717 NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel);
Mady Mellor7eb18ef2019-03-27 14:03:46 -07004718
4719 // Post the notification
Mady Mellorbe797962019-04-01 16:04:24 -07004720 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Mady Mellor7eb18ef2019-03-27 14:03:46 -07004721 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
4722 waitForIdle();
4723
4724 // no bubble metadata, no bubble
4725 assertFalse(mService.getNotificationRecord(
Mady Mellorbe797962019-04-01 16:04:24 -07004726 nr.sbn.getKey()).getNotification().isBubbleNotification());
Mady Mellor7eb18ef2019-03-27 14:03:46 -07004727 }
4728
4729 @Test
Mady Mellorbe797962019-04-01 16:04:24 -07004730 public void testFlagBubbleNotifs_noFlag_messaging_channelNotAllowed() throws RemoteException {
Mady Mellorc6820342019-05-20 12:04:36 -07004731 // Bubbles are allowed except on this channel
4732 setUpPrefsForBubbles(true /* global */, true /* app */, false /* channel */);
Mady Mellor7eb18ef2019-03-27 14:03:46 -07004733
Mady Mellorbe797962019-04-01 16:04:24 -07004734 // Give it bubble metadata
Mady Mellor7eb18ef2019-03-27 14:03:46 -07004735 Notification.BubbleMetadata data = getBasicBubbleMetadataBuilder().build();
Mady Mellorbe797962019-04-01 16:04:24 -07004736 // Give it a person
4737 Person person = new Person.Builder()
4738 .setName("bubblebot")
4739 .build();
4740 // Make it messaging style
Mady Mellor7eb18ef2019-03-27 14:03:46 -07004741 Notification.Builder nb = new Notification.Builder(mContext,
4742 mTestNotificationChannel.getId())
4743 .setContentTitle("foo")
4744 .setBubbleMetadata(data)
Mady Mellorbe797962019-04-01 16:04:24 -07004745 .setStyle(new Notification.MessagingStyle(person)
4746 .setConversationTitle("Bubble Chat")
4747 .addMessage("Hello?",
4748 SystemClock.currentThreadTimeMillis() - 300000, person)
4749 .addMessage("Is it me you're looking for?",
4750 SystemClock.currentThreadTimeMillis(), person)
4751 )
Mady Mellor7eb18ef2019-03-27 14:03:46 -07004752 .setSmallIcon(android.R.drawable.sym_def_app_icon);
4753
4754 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, null, mUid, 0,
4755 nb.build(), new UserHandle(mUid), null, 0);
4756 NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
4757
4758 // Post the notification
4759 mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
4760 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
4761 waitForIdle();
4762
4763 // channel not allowed, no bubble
4764 assertFalse(mService.getNotificationRecord(
4765 sbn.getKey()).getNotification().isBubbleNotification());
4766 }
Tony Mak9a3c1f12019-03-04 16:04:42 +00004767
Mady Mellor49b1bf12019-03-29 12:00:02 -07004768 @Test
Mady Mellorbe797962019-04-01 16:04:24 -07004769 public void testFlagBubbleNotifs_noFlag_phonecall_notAllowed() throws RemoteException {
Mady Mellorc6820342019-05-20 12:04:36 -07004770 // Bubbles are not allowed!
4771 setUpPrefsForBubbles(false /* global */, true /* app */, true /* channel */);
Mady Mellorbe797962019-04-01 16:04:24 -07004772
4773 // Give it bubble metadata
4774 Notification.BubbleMetadata data = getBasicBubbleMetadataBuilder().build();
4775 // Give it a person
4776 Person person = new Person.Builder()
4777 .setName("bubblebot")
4778 .build();
4779 // Make it a phone call
4780 Notification.Builder nb = new Notification.Builder(mContext,
4781 mTestNotificationChannel.getId())
4782 .setCategory(CATEGORY_CALL)
4783 .addPerson(person)
4784 .setContentTitle("foo")
4785 .setBubbleMetadata(data)
4786 .setSmallIcon(android.R.drawable.sym_def_app_icon);
4787
4788 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, null, mUid, 0,
4789 nb.build(), new UserHandle(mUid), null, 0);
4790 // Make sure it has foreground service
4791 sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
4792 NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
4793
4794 mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
4795 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
4796 waitForIdle();
4797
4798 // yes phone call, yes person, yes foreground service, but not allowed, no bubble
4799 assertFalse(mService.getNotificationRecord(
4800 sbn.getKey()).getNotification().isBubbleNotification());
4801 }
4802
4803 @Test
4804 public void testFlagBubbleNotifs_noFlag_phonecall_channelNotAllowed() throws RemoteException {
Mady Mellorc6820342019-05-20 12:04:36 -07004805 // Bubbles are allowed, but not on channel.
4806 setUpPrefsForBubbles(true /* global */, true /* app */, false /* channel */);
Mady Mellorbe797962019-04-01 16:04:24 -07004807
4808 // Give it bubble metadata
4809 Notification.BubbleMetadata data = getBasicBubbleMetadataBuilder().build();
4810 // Give it a person
4811 Person person = new Person.Builder()
4812 .setName("bubblebot")
4813 .build();
4814 // Make it a phone call
4815 Notification.Builder nb = new Notification.Builder(mContext,
4816 mTestNotificationChannel.getId())
4817 .setCategory(CATEGORY_CALL)
4818 .addPerson(person)
4819 .setContentTitle("foo")
4820 .setBubbleMetadata(data)
4821 .setSmallIcon(android.R.drawable.sym_def_app_icon);
4822
4823 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, null, mUid, 0,
4824 nb.build(), new UserHandle(mUid), null, 0);
4825 // Make sure it has foreground service
4826 sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
4827 NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
4828
4829 mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
4830 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
4831 waitForIdle();
4832
4833 // yes phone call, yes person, yes foreground service, but channel not allowed, no bubble
4834 assertFalse(mService.getNotificationRecord(
4835 sbn.getKey()).getNotification().isBubbleNotification());
4836 }
4837
4838 @Test
Mady Mellor49b1bf12019-03-29 12:00:02 -07004839 public void testCancelAllNotifications_cancelsBubble() throws Exception {
4840 final NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel);
4841 nr.sbn.getNotification().flags |= FLAG_BUBBLE;
4842 mService.addNotification(nr);
4843
4844 mBinderService.cancelAllNotifications(PKG, nr.sbn.getUserId());
4845 waitForIdle();
4846
4847 StatusBarNotification[] notifs = mBinderService.getActiveNotifications(PKG);
4848 assertEquals(0, notifs.length);
4849 assertEquals(0, mService.getNotificationRecordCount());
4850 }
4851
4852 @Test
4853 public void testAppCancelNotifications_cancelsBubbles() throws Exception {
4854 final NotificationRecord nrBubble = generateNotificationRecord(mTestNotificationChannel);
4855 nrBubble.sbn.getNotification().flags |= FLAG_BUBBLE;
4856
4857 // Post the notification
4858 mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
4859 nrBubble.sbn.getId(), nrBubble.sbn.getNotification(), nrBubble.sbn.getUserId());
4860 waitForIdle();
4861
4862 StatusBarNotification[] notifs = mBinderService.getActiveNotifications(PKG);
4863 assertEquals(1, notifs.length);
4864 assertEquals(1, mService.getNotificationRecordCount());
4865
4866 mBinderService.cancelNotificationWithTag(PKG, null, nrBubble.sbn.getId(),
4867 nrBubble.sbn.getUserId());
4868 waitForIdle();
4869
4870 StatusBarNotification[] notifs2 = mBinderService.getActiveNotifications(PKG);
4871 assertEquals(0, notifs2.length);
4872 assertEquals(0, mService.getNotificationRecordCount());
4873 }
4874
4875 @Test
4876 public void testCancelAllNotificationsFromListener_ignoresBubbles() throws Exception {
4877 final NotificationRecord nrNormal = generateNotificationRecord(mTestNotificationChannel);
4878 final NotificationRecord nrBubble = generateNotificationRecord(mTestNotificationChannel);
4879 nrBubble.sbn.getNotification().flags |= FLAG_BUBBLE;
4880
4881 mService.addNotification(nrNormal);
4882 mService.addNotification(nrBubble);
4883
4884 mService.getBinderService().cancelNotificationsFromListener(null, null);
4885 waitForIdle();
4886
4887 StatusBarNotification[] notifs = mBinderService.getActiveNotifications(PKG);
4888 assertEquals(1, notifs.length);
4889 assertEquals(1, mService.getNotificationRecordCount());
4890 }
4891
4892 @Test
4893 public void testCancelNotificationsFromListener_ignoresBubbles() throws Exception {
4894 final NotificationRecord nrNormal = generateNotificationRecord(mTestNotificationChannel);
4895 final NotificationRecord nrBubble = generateNotificationRecord(mTestNotificationChannel);
4896 nrBubble.sbn.getNotification().flags |= FLAG_BUBBLE;
4897
4898 mService.addNotification(nrNormal);
4899 mService.addNotification(nrBubble);
4900
4901 String[] keys = {nrNormal.sbn.getKey(), nrBubble.sbn.getKey()};
4902 mService.getBinderService().cancelNotificationsFromListener(null, keys);
4903 waitForIdle();
4904
4905 StatusBarNotification[] notifs = mBinderService.getActiveNotifications(PKG);
4906 assertEquals(1, notifs.length);
4907 assertEquals(1, mService.getNotificationRecordCount());
4908 }
Julia Reynoldsad6dd352019-03-07 16:46:22 -05004909
Julia Reynolds4214da92019-04-10 15:04:06 -04004910 @Test
Julia Reynolds088c4482019-04-10 12:43:27 -04004911 public void testGetAllowedAssistantAdjustments() throws Exception {
4912 List<String> capabilities = mBinderService.getAllowedAssistantAdjustments(null);
Julia Reynoldsad6dd352019-03-07 16:46:22 -05004913 assertNotNull(capabilities);
4914
4915 for (int i = capabilities.size() - 1; i >= 0; i--) {
4916 String capability = capabilities.get(i);
Julia Reynolds088c4482019-04-10 12:43:27 -04004917 mBinderService.disallowAssistantAdjustment(capability);
4918 assertEquals(i + 1, mBinderService.getAllowedAssistantAdjustments(null).size());
4919 List<String> currentCapabilities = mBinderService.getAllowedAssistantAdjustments(null);
Julia Reynoldsad6dd352019-03-07 16:46:22 -05004920 assertNotNull(currentCapabilities);
4921 assertFalse(currentCapabilities.contains(capability));
4922 }
4923 }
Julia Reynoldsc7dcdc22019-03-25 10:26:14 -04004924
Julia Reynolds4214da92019-04-10 15:04:06 -04004925 @Test
Julia Reynoldsc7dcdc22019-03-25 10:26:14 -04004926 public void testAdjustRestrictedKey() throws Exception {
4927 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
Julia Reynolds4214da92019-04-10 15:04:06 -04004928 mService.addNotification(r);
4929 when(mAssistants.isSameUser(any(), anyInt())).thenReturn(true);
Julia Reynoldsc7dcdc22019-03-25 10:26:14 -04004930
4931 when(mAssistants.isAdjustmentAllowed(KEY_IMPORTANCE)).thenReturn(true);
4932 when(mAssistants.isAdjustmentAllowed(KEY_USER_SENTIMENT)).thenReturn(false);
4933
4934 Bundle signals = new Bundle();
4935 signals.putInt(KEY_IMPORTANCE, IMPORTANCE_LOW);
4936 signals.putInt(KEY_USER_SENTIMENT, USER_SENTIMENT_NEGATIVE);
4937 Adjustment adjustment = new Adjustment(r.sbn.getPackageName(), r.getKey(), signals,
4938 "", r.getUser().getIdentifier());
4939
4940 mBinderService.applyAdjustmentFromAssistant(null, adjustment);
4941 r.applyAdjustments();
4942
4943 assertEquals(IMPORTANCE_LOW, r.getAssistantImportance());
4944 assertEquals(USER_SENTIMENT_NEUTRAL, r.getUserSentiment());
4945 }
Julia Reynolds657d1642019-03-27 12:15:57 -04004946
Julia Reynolds4214da92019-04-10 15:04:06 -04004947 @Test
Julia Reynoldsa94365d2019-04-09 10:48:43 -04004948 public void testAutomaticZenRuleValidation_policyFilterAgreement() throws Exception {
Julia Reynolds4214da92019-04-10 15:04:06 -04004949 when(mConditionProviders.isPackageOrComponentAllowed(anyString(), anyInt()))
4950 .thenReturn(true);
4951 mService.setZenHelper(mock(ZenModeHelper.class));
4952 ComponentName owner = new ComponentName(mContext, this.getClass());
Julia Reynoldsa94365d2019-04-09 10:48:43 -04004953 ZenPolicy zenPolicy = new ZenPolicy.Builder().allowAlarms(true).build();
4954 boolean isEnabled = true;
4955 AutomaticZenRule rule = new AutomaticZenRule("test", owner, owner, mock(Uri.class),
4956 zenPolicy, NotificationManager.INTERRUPTION_FILTER_NONE, isEnabled);
4957
4958 try {
4959 mBinderService.addAutomaticZenRule(rule);
Julia Reynolds4214da92019-04-10 15:04:06 -04004960 fail("Zen policy only applies to priority only mode");
Julia Reynoldsa94365d2019-04-09 10:48:43 -04004961 } catch (IllegalArgumentException e) {
4962 // yay
4963 }
4964
4965 rule = new AutomaticZenRule("test", owner, owner, mock(Uri.class),
4966 zenPolicy, NotificationManager.INTERRUPTION_FILTER_PRIORITY, isEnabled);
4967 mBinderService.addAutomaticZenRule(rule);
4968
4969 rule = new AutomaticZenRule("test", owner, owner, mock(Uri.class),
4970 null, NotificationManager.INTERRUPTION_FILTER_NONE, isEnabled);
4971 mBinderService.addAutomaticZenRule(rule);
4972 }
4973
Julia Reynolds4214da92019-04-10 15:04:06 -04004974 @Test
Julia Reynolds657d1642019-03-27 12:15:57 -04004975 public void testAreNotificationsEnabledForPackage_crossUser() throws Exception {
4976 try {
4977 mBinderService.areNotificationsEnabledForPackage(mContext.getPackageName(),
4978 mUid + UserHandle.PER_USER_RANGE);
4979 fail("Cannot call cross user without permission");
4980 } catch (SecurityException e) {
4981 // pass
4982 }
4983
4984 // cross user, with permission, no problem
4985 TestablePermissions perms = mContext.getTestablePermissions();
4986 perms.setPermission(android.Manifest.permission.INTERACT_ACROSS_USERS, PERMISSION_GRANTED);
4987 mBinderService.areNotificationsEnabledForPackage(mContext.getPackageName(),
4988 mUid + UserHandle.PER_USER_RANGE);
4989 }
Julia Reynolds2f7592d2019-03-27 12:17:23 -04004990
Julia Reynolds4214da92019-04-10 15:04:06 -04004991 @Test
Julia Reynolds2f7592d2019-03-27 12:17:23 -04004992 public void testAreBubblesAllowedForPackage_crossUser() throws Exception {
4993 try {
4994 mBinderService.areBubblesAllowedForPackage(mContext.getPackageName(),
4995 mUid + UserHandle.PER_USER_RANGE);
4996 fail("Cannot call cross user without permission");
4997 } catch (SecurityException e) {
4998 // pass
4999 }
5000
5001 // cross user, with permission, no problem
5002 TestablePermissions perms = mContext.getTestablePermissions();
5003 perms.setPermission(android.Manifest.permission.INTERACT_ACROSS_USERS, PERMISSION_GRANTED);
5004 mBinderService.areBubblesAllowedForPackage(mContext.getPackageName(),
5005 mUid + UserHandle.PER_USER_RANGE);
5006 }
Mady Mellora54e9fa2019-04-18 13:26:18 -07005007
5008 @Test
5009 public void testNotificationBubbleChanged_false() throws Exception {
5010 // Bubbles are allowed!
Mady Mellorc6820342019-05-20 12:04:36 -07005011 setUpPrefsForBubbles(true /* global */, true /* app */, true /* channel */);
Mady Mellora54e9fa2019-04-18 13:26:18 -07005012
5013 // Notif with bubble metadata but not our other misc requirements
5014 NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel,
5015 null /* tvExtender */, true /* isBubble */);
5016
5017 // Say we're foreground
5018 when(mActivityManager.getPackageImportance(nr.sbn.getPackageName())).thenReturn(
5019 IMPORTANCE_FOREGROUND);
5020
5021 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
5022 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
5023 waitForIdle();
5024
Mady Mellor66efd5e2019-05-15 13:38:11 -07005025 // Reset as this is called when the notif is first sent
5026 reset(mListeners);
5027
Mady Mellora54e9fa2019-04-18 13:26:18 -07005028 // First we were a bubble
5029 StatusBarNotification[] notifsBefore = mBinderService.getActiveNotifications(PKG);
5030 assertEquals(1, notifsBefore.length);
5031 assertTrue((notifsBefore[0].getNotification().flags & FLAG_BUBBLE) != 0);
5032
5033 // Notify we're not a bubble
5034 mService.mNotificationDelegate.onNotificationBubbleChanged(nr.getKey(), false);
5035 waitForIdle();
5036
Mady Mellor3a0a1b42019-05-23 06:40:21 -07005037 // Make sure we are not a bubble
5038 StatusBarNotification[] notifsAfter = mBinderService.getActiveNotifications(PKG);
5039 assertEquals(1, notifsAfter.length);
5040 assertEquals((notifsAfter[0].getNotification().flags & FLAG_BUBBLE), 0);
Mady Mellora54e9fa2019-04-18 13:26:18 -07005041 }
5042
5043 @Test
5044 public void testNotificationBubbleChanged_true() throws Exception {
5045 // Bubbles are allowed!
Mady Mellorc6820342019-05-20 12:04:36 -07005046 setUpPrefsForBubbles(true /* global */, true /* app */, true /* channel */);
Mady Mellora54e9fa2019-04-18 13:26:18 -07005047
5048 // Plain notification that has bubble metadata
5049 NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel,
5050 null /* tvExtender */, true /* isBubble */);
5051 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
5052 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
5053 waitForIdle();
5054
5055 // Would be a normal notification because wouldn't have met requirements to bubble
5056 StatusBarNotification[] notifsBefore = mBinderService.getActiveNotifications(PKG);
5057 assertEquals(1, notifsBefore.length);
5058 assertEquals((notifsBefore[0].getNotification().flags & FLAG_BUBBLE), 0);
5059
5060 // Make the package foreground so that we're allowed to be a bubble
5061 when(mActivityManager.getPackageImportance(nr.sbn.getPackageName())).thenReturn(
5062 IMPORTANCE_FOREGROUND);
5063
Mady Mellor66efd5e2019-05-15 13:38:11 -07005064 // Reset as this is called when the notif is first sent
5065 reset(mListeners);
5066
Mady Mellora54e9fa2019-04-18 13:26:18 -07005067 // Notify we are now a bubble
5068 mService.mNotificationDelegate.onNotificationBubbleChanged(nr.getKey(), true);
5069 waitForIdle();
5070
Mady Mellor3a0a1b42019-05-23 06:40:21 -07005071 // Make sure we are a bubble
5072 StatusBarNotification[] notifsAfter = mBinderService.getActiveNotifications(PKG);
5073 assertEquals(1, notifsAfter.length);
5074 assertTrue((notifsAfter[0].getNotification().flags & FLAG_BUBBLE) != 0);
Mady Mellora54e9fa2019-04-18 13:26:18 -07005075 }
5076
5077 @Test
5078 public void testNotificationBubbleChanged_true_notAllowed() throws Exception {
5079 // Bubbles are allowed!
Mady Mellorc6820342019-05-20 12:04:36 -07005080 setUpPrefsForBubbles(true /* global */, true /* app */, true /* channel */);
Mady Mellora54e9fa2019-04-18 13:26:18 -07005081
5082 // Notif that is not a bubble
5083 NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel,
5084 null /* tvExtender */, true /* isBubble */);
5085 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
5086 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
5087 waitForIdle();
5088
Mady Mellor66efd5e2019-05-15 13:38:11 -07005089 // Reset as this is called when the notif is first sent
5090 reset(mListeners);
5091
Mady Mellora54e9fa2019-04-18 13:26:18 -07005092 // Would be a normal notification because wouldn't have met requirements to bubble
5093 StatusBarNotification[] notifsBefore = mBinderService.getActiveNotifications(PKG);
5094 assertEquals(1, notifsBefore.length);
5095 assertEquals((notifsBefore[0].getNotification().flags & FLAG_BUBBLE), 0);
5096
5097 // Notify we are now a bubble
5098 mService.mNotificationDelegate.onNotificationBubbleChanged(nr.getKey(), true);
5099 waitForIdle();
5100
5101 // We still wouldn't be a bubble because the notification didn't meet requirements
5102 StatusBarNotification[] notifsAfter = mBinderService.getActiveNotifications(PKG);
5103 assertEquals(1, notifsAfter.length);
5104 assertEquals((notifsAfter[0].getNotification().flags & FLAG_BUBBLE), 0);
5105 }
Mady Mellor5c11a2e2019-04-25 17:26:15 -07005106
5107 @Test
5108 public void testNotificationBubbles_disabled_lowRamDevice() throws Exception {
5109 // Bubbles are allowed!
Mady Mellorc6820342019-05-20 12:04:36 -07005110 setUpPrefsForBubbles(true /* global */, true /* app */, true /* channel */);
Mady Mellor5c11a2e2019-04-25 17:26:15 -07005111
5112 // Plain notification that has bubble metadata
5113 NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel,
5114 null /* tvExtender */, true /* isBubble */);
5115 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
5116 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
5117 waitForIdle();
5118
5119 // Would be a normal notification because wouldn't have met requirements to bubble
5120 StatusBarNotification[] notifsBefore = mBinderService.getActiveNotifications(PKG);
5121 assertEquals(1, notifsBefore.length);
5122 assertEquals((notifsBefore[0].getNotification().flags & FLAG_BUBBLE), 0);
5123
5124 // Make the package foreground so that we're allowed to be a bubble
5125 when(mActivityManager.getPackageImportance(nr.sbn.getPackageName())).thenReturn(
5126 IMPORTANCE_FOREGROUND);
5127
5128 // And we are low ram
5129 when(mActivityManager.isLowRamDevice()).thenReturn(true);
5130
5131 // We wouldn't be a bubble because the notification didn't meet requirements (low ram)
5132 StatusBarNotification[] notifsAfter = mBinderService.getActiveNotifications(PKG);
5133 assertEquals(1, notifsAfter.length);
5134 assertEquals((notifsAfter[0].getNotification().flags & FLAG_BUBBLE), 0);
Mady Mellor5c11a2e2019-04-25 17:26:15 -07005135 }
Mady Mellora7731962019-06-17 17:57:02 -07005136
5137 @Test
5138 public void testNotificationBubbles_flagAutoExpandForeground_fails_notForeground()
5139 throws Exception {
5140 // Bubbles are allowed!
5141 setUpPrefsForBubbles(true /* global */, true /* app */, true /* channel */);
5142
5143 // Give it bubble metadata
5144 Notification.BubbleMetadata data = getBasicBubbleMetadataBuilder()
5145 .setSuppressNotification(true)
5146 .setAutoExpandBubble(true).build();
5147 // Give it a person
5148 Person person = new Person.Builder()
5149 .setName("bubblebot")
5150 .build();
5151 // It needs remote input to be bubble-able
5152 RemoteInput remoteInput = new RemoteInput.Builder("reply_key").setLabel("reply").build();
5153 PendingIntent inputIntent = PendingIntent.getActivity(mContext, 0, new Intent(), 0);
5154 Icon icon = Icon.createWithResource(mContext, android.R.drawable.sym_def_app_icon);
5155 Notification.Action replyAction = new Notification.Action.Builder(icon, "Reply",
5156 inputIntent).addRemoteInput(remoteInput)
5157 .build();
5158 // Make it messaging style
5159 Notification.Builder nb = new Notification.Builder(mContext,
5160 mTestNotificationChannel.getId())
5161 .setContentTitle("foo")
5162 .setBubbleMetadata(data)
5163 .setStyle(new Notification.MessagingStyle(person)
5164 .setConversationTitle("Bubble Chat")
5165 .addMessage("Hello?",
5166 SystemClock.currentThreadTimeMillis() - 300000, person)
5167 .addMessage("Is it me you're looking for?",
5168 SystemClock.currentThreadTimeMillis(), person)
5169 )
5170 .setActions(replyAction)
5171 .setSmallIcon(android.R.drawable.sym_def_app_icon);
5172
5173 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, null, mUid, 0,
5174 nb.build(), new UserHandle(mUid), null, 0);
5175 NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
5176
5177 // Ensure we're not foreground
5178 when(mActivityManager.getPackageImportance(nr.sbn.getPackageName())).thenReturn(
5179 IMPORTANCE_VISIBLE);
5180
5181 mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
5182 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
5183 waitForIdle();
5184
5185 // yes allowed, yes messaging, yes bubble
5186 Notification notif = mService.getNotificationRecord(sbn.getKey()).getNotification();
5187 assertTrue(notif.isBubbleNotification());
5188
5189 // Our flags should have failed since we're not foreground
5190 assertFalse(notif.getBubbleMetadata().getAutoExpandBubble());
5191 assertFalse(notif.getBubbleMetadata().isNotificationSuppressed());
5192 }
5193
5194 @Test
5195 public void testNotificationBubbles_flagAutoExpandForeground_succeeds_foreground()
5196 throws RemoteException {
5197 // Bubbles are allowed!
5198 setUpPrefsForBubbles(true /* global */, true /* app */, true /* channel */);
5199
5200 // Give it bubble metadata
5201 Notification.BubbleMetadata data = getBasicBubbleMetadataBuilder()
5202 .setSuppressNotification(true)
5203 .setAutoExpandBubble(true).build();
5204 // Give it a person
5205 Person person = new Person.Builder()
5206 .setName("bubblebot")
5207 .build();
5208 // It needs remote input to be bubble-able
5209 RemoteInput remoteInput = new RemoteInput.Builder("reply_key").setLabel("reply").build();
5210 PendingIntent inputIntent = PendingIntent.getActivity(mContext, 0, new Intent(), 0);
5211 Icon icon = Icon.createWithResource(mContext, android.R.drawable.sym_def_app_icon);
5212 Notification.Action replyAction = new Notification.Action.Builder(icon, "Reply",
5213 inputIntent).addRemoteInput(remoteInput)
5214 .build();
5215 // Make it messaging style
5216 Notification.Builder nb = new Notification.Builder(mContext,
5217 mTestNotificationChannel.getId())
5218 .setContentTitle("foo")
5219 .setBubbleMetadata(data)
5220 .setStyle(new Notification.MessagingStyle(person)
5221 .setConversationTitle("Bubble Chat")
5222 .addMessage("Hello?",
5223 SystemClock.currentThreadTimeMillis() - 300000, person)
5224 .addMessage("Is it me you're looking for?",
5225 SystemClock.currentThreadTimeMillis(), person)
5226 )
5227 .setActions(replyAction)
5228 .setSmallIcon(android.R.drawable.sym_def_app_icon);
5229
5230 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, null, mUid, 0,
5231 nb.build(), new UserHandle(mUid), null, 0);
5232 NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
5233
5234 // Ensure we are in the foreground
5235 when(mActivityManager.getPackageImportance(nr.sbn.getPackageName())).thenReturn(
5236 IMPORTANCE_FOREGROUND);
5237
5238 mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
5239 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
5240 waitForIdle();
5241
5242 // yes allowed, yes messaging, yes bubble
5243 Notification notif = mService.getNotificationRecord(sbn.getKey()).getNotification();
5244 assertTrue(notif.isBubbleNotification());
5245
5246 // Our flags should have failed since we are foreground
5247 assertTrue(notif.getBubbleMetadata().getAutoExpandBubble());
5248 assertTrue(notif.getBubbleMetadata().isNotificationSuppressed());
5249 }
Mady Mellor22f2f072019-04-18 13:26:18 -07005250
5251 @Test
5252 public void testNotificationBubbles_bubbleChildrenStay_whenGroupSummaryDismissed()
5253 throws Exception {
5254 // Bubbles are allowed!
5255 setUpPrefsForBubbles(true /* global */, true /* app */, true /* channel */);
5256
5257 NotificationRecord nrSummary = addGroupWithBubblesAndValidateAdded(
5258 true /* summaryAutoCancel */);
5259
5260 // Dismiss summary
5261 final NotificationVisibility nv = NotificationVisibility.obtain(nrSummary.getKey(), 1, 2,
5262 true);
5263 mService.mNotificationDelegate.onNotificationClear(mUid, 0, PKG, nrSummary.sbn.getTag(),
5264 nrSummary.sbn.getId(), nrSummary.getUserId(), nrSummary.getKey(),
5265 NotificationStats.DISMISSAL_SHADE,
5266 NotificationStats.DISMISS_SENTIMENT_NEUTRAL, nv);
5267 waitForIdle();
5268
5269 // The bubble should still exist
5270 StatusBarNotification[] notifsAfter = mBinderService.getActiveNotifications(PKG);
5271 assertEquals(1, notifsAfter.length);
5272 }
5273
5274 @Test
5275 public void testNotificationBubbles_bubbleChildrenStay_whenGroupSummaryClicked()
5276 throws Exception {
5277 // Bubbles are allowed!
5278 setUpPrefsForBubbles(true /* global */, true /* app */, true /* channel */);
5279
5280 NotificationRecord nrSummary = addGroupWithBubblesAndValidateAdded(
5281 true /* summaryAutoCancel */);
5282
5283 // Click summary
5284 final NotificationVisibility nv = NotificationVisibility.obtain(nrSummary.getKey(), 1, 2,
5285 true);
5286 mService.mNotificationDelegate.onNotificationClick(mUid, Binder.getCallingPid(),
5287 nrSummary.getKey(), nv);
5288 waitForIdle();
5289
5290 // The bubble should still exist
5291 StatusBarNotification[] notifsAfter = mBinderService.getActiveNotifications(PKG);
5292 assertEquals(1, notifsAfter.length);
5293 }
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -05005294}