blob: ecdd9e548e6a2fa4763086c9f7313fadf95ef798 [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;
Mady Mellorbe797962019-04-01 16:04:24 -070020import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
Mady Mellor22f2f072019-04-18 13:26:18 -070021import static android.app.Notification.FLAG_AUTO_CANCEL;
Mady Mellor49b1bf12019-03-29 12:00:02 -070022import static android.app.Notification.FLAG_BUBBLE;
Julia Reynoldse5c60452018-04-30 14:41:36 -040023import static android.app.Notification.FLAG_FOREGROUND_SERVICE;
Mady Mellora92268c2020-03-09 17:25:08 -070024import static android.app.NotificationChannel.USER_LOCKED_ALLOW_BUBBLE;
25import static android.app.NotificationManager.BUBBLE_PREFERENCE_ALL;
26import static android.app.NotificationManager.BUBBLE_PREFERENCE_NONE;
27import static android.app.NotificationManager.BUBBLE_PREFERENCE_SELECTED;
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -050028import static android.app.NotificationManager.EXTRA_BLOCKED_STATE;
Julia Reynolds27c0a962018-12-10 12:37:28 -050029import static android.app.NotificationManager.IMPORTANCE_DEFAULT;
Julia Reynolds8617e4e2017-09-18 16:52:37 -040030import static android.app.NotificationManager.IMPORTANCE_HIGH;
Julia Reynolds73ed76b2017-04-04 17:04:38 -040031import static android.app.NotificationManager.IMPORTANCE_LOW;
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -050032import static android.app.NotificationManager.IMPORTANCE_MAX;
Julia Reynolds4da79702017-06-01 11:06:10 -040033import static android.app.NotificationManager.IMPORTANCE_NONE;
Julia Reynolds8617e4e2017-09-18 16:52:37 -040034import static android.app.NotificationManager.IMPORTANCE_UNSPECIFIED;
Julia Reynolds24edc002020-01-29 16:35:32 -050035import static android.app.NotificationManager.Policy.PRIORITY_CATEGORY_CALLS;
36import static android.app.NotificationManager.Policy.PRIORITY_CATEGORY_CONVERSATIONS;
Julia Reynoldsccc6ae62018-03-01 16:24:49 -050037import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_AMBIENT;
38import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_BADGE;
39import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_FULL_SCREEN_INTENT;
40import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_LIGHTS;
41import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_NOTIFICATION_LIST;
42import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_PEEK;
43import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_SCREEN_OFF;
44import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_SCREEN_ON;
45import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_STATUS_BAR;
Mady Mellora92268c2020-03-09 17:25:08 -070046import static android.content.pm.ActivityInfo.RESIZE_MODE_RESIZEABLE;
Julia Reynoldse1816412017-10-24 10:39:11 -040047import static android.content.pm.PackageManager.FEATURE_WATCH;
Julia Reynolds4db59552017-06-30 13:34:01 -040048import static android.content.pm.PackageManager.PERMISSION_DENIED;
Julia Reynolds7a6d07a2019-03-18 11:31:56 -040049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Julia Reynoldsccc6ae62018-03-01 16:24:49 -050050import static android.os.Build.VERSION_CODES.O_MR1;
51import static android.os.Build.VERSION_CODES.P;
Julia Reynolds57a974b2019-10-07 11:51:47 -040052import static android.os.UserHandle.USER_SYSTEM;
Julia Reynoldsc7dcdc22019-03-25 10:26:14 -040053import static android.service.notification.Adjustment.KEY_IMPORTANCE;
54import static android.service.notification.Adjustment.KEY_USER_SENTIMENT;
Tony Makeda84a72018-11-19 17:01:32 +000055import static android.service.notification.NotificationListenerService.Ranking.USER_SENTIMENT_NEGATIVE;
56import static android.service.notification.NotificationListenerService.Ranking.USER_SENTIMENT_NEUTRAL;
Julia Reynolds73ed76b2017-04-04 17:04:38 -040057
Geoffrey Pitsch03533712017-01-05 10:30:07 -050058import static junit.framework.Assert.assertEquals;
Julia Reynolds727a7282017-04-13 10:54:01 -040059import static junit.framework.Assert.assertFalse;
Julia Reynolds92febc32017-10-26 11:30:31 -040060import static junit.framework.Assert.assertNotNull;
Julia Reynolds8617e4e2017-09-18 16:52:37 -040061import static junit.framework.Assert.assertNull;
Julia Reynoldsbaff4002016-12-15 11:34:26 -050062import static junit.framework.Assert.assertTrue;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -050063import static junit.framework.Assert.fail;
Julia Reynoldsbaff4002016-12-15 11:34:26 -050064
Jay Aliomerfea80252019-11-20 18:14:24 -050065import static org.mockito.ArgumentMatchers.isNull;
Julia Reynolds5f20e9f2017-01-30 08:54:53 -050066import static org.mockito.Matchers.anyBoolean;
Julia Reynoldsa78cdff2017-04-26 10:19:25 -040067import static org.mockito.Matchers.anyLong;
Julia Reynoldsbaff4002016-12-15 11:34:26 -050068import static org.mockito.Matchers.anyString;
69import static org.mockito.Matchers.eq;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -050070import static org.mockito.Mockito.any;
71import static org.mockito.Mockito.anyInt;
Julia Reynoldsb6c83742019-07-30 18:03:40 -040072import static org.mockito.Mockito.clearInvocations;
Julia Reynoldseb3dca72017-07-11 10:39:58 -040073import static org.mockito.Mockito.doAnswer;
Julia Reynolds4afe2642019-05-01 08:42:24 -040074import static org.mockito.Mockito.doNothing;
Julia Reynoldsea58c202020-02-03 12:52:49 -050075import static org.mockito.Mockito.doThrow;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -050076import static org.mockito.Mockito.mock;
Julia Reynolds73ed76b2017-04-04 17:04:38 -040077import static org.mockito.Mockito.never;
78import static org.mockito.Mockito.reset;
Julia Reynolds503ed942017-10-04 16:04:56 -040079import static org.mockito.Mockito.spy;
80import static org.mockito.Mockito.timeout;
Julia Reynoldsbaff4002016-12-15 11:34:26 -050081import static org.mockito.Mockito.times;
82import static org.mockito.Mockito.verify;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -050083import static org.mockito.Mockito.when;
84
Julia Reynolds68263d12017-06-21 14:21:19 -040085import android.app.ActivityManager;
Mady Mellor13f9bc82020-03-24 19:09:28 -070086import android.app.ActivityManagerInternal;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -040087import android.app.AppOpsManager;
Julia Reynoldsa94365d2019-04-09 10:48:43 -040088import android.app.AutomaticZenRule;
Julia Reynoldse0d711f2017-09-01 08:50:47 -040089import android.app.IActivityManager;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -050090import android.app.INotificationManager;
Julia Reynolds268647a2018-10-25 16:54:27 -040091import android.app.ITransientNotification;
92import android.app.IUriGrantsManager;
Julia Reynoldsbaff4002016-12-15 11:34:26 -050093import android.app.Notification;
Julia Reynoldse0d711f2017-09-01 08:50:47 -040094import android.app.Notification.MessagingStyle.Message;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -050095import android.app.NotificationChannel;
Julia Reynolds73ed76b2017-04-04 17:04:38 -040096import android.app.NotificationChannelGroup;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -050097import android.app.NotificationManager;
Mady Mellor7eb18ef2019-03-27 14:03:46 -070098import android.app.PendingIntent;
Mady Mellorbe797962019-04-01 16:04:24 -070099import android.app.Person;
Mady Mellora10448e2019-04-26 13:50:58 -0700100import android.app.RemoteInput;
Yotam Aron74299972020-01-16 16:20:58 +0200101import android.app.StatsManager;
Jason Parks50322ff2018-03-27 10:23:33 -0500102import android.app.admin.DevicePolicyManagerInternal;
Julia Reynolds7217dc92018-03-07 12:12:09 -0500103import android.app.usage.UsageStatsManagerInternal;
Julia Reynolds73ed76b2017-04-04 17:04:38 -0400104import android.companion.ICompanionDeviceManager;
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500105import android.content.ComponentName;
Jeff Sharkey6a97cc32018-04-17 12:16:20 -0600106import android.content.ContentUris;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500107import android.content.Context;
Beverlyd4f96492017-08-02 13:36:11 -0400108import android.content.Intent;
Mady Mellora92268c2020-03-09 17:25:08 -0700109import android.content.pm.ActivityInfo;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500110import android.content.pm.ApplicationInfo;
111import android.content.pm.IPackageManager;
Mady Mellor2ac2d3a2020-01-08 17:18:54 -0800112import android.content.pm.LauncherApps;
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500113import android.content.pm.PackageManager;
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500114import android.content.pm.ParceledListSlice;
Mady Mellor2ac2d3a2020-01-08 17:18:54 -0800115import android.content.pm.ShortcutInfo;
Julia Reynoldsfa273072020-04-14 15:31:21 -0400116import android.content.pm.ShortcutServiceInternal;
Julia Reynolds4afe2642019-05-01 08:42:24 -0400117import android.content.pm.UserInfo;
Kristian Monsen05f34792018-04-09 10:27:16 +0200118import android.content.res.Resources;
Julia Reynolds73ed76b2017-04-04 17:04:38 -0400119import android.graphics.Color;
Mady Mellor7eb18ef2019-03-27 14:03:46 -0700120import android.graphics.drawable.Icon;
Julia Reynolds76c096d2017-06-19 08:16:04 -0400121import android.media.AudioManager;
Julia Reynoldse0d711f2017-09-01 08:50:47 -0400122import android.net.Uri;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500123import android.os.Binder;
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400124import android.os.Build;
Julia Reynolds503ed942017-10-04 16:04:56 -0400125import android.os.Bundle;
Julia Reynoldse0d711f2017-09-01 08:50:47 -0400126import android.os.IBinder;
Julia Reynolds0f767342019-12-18 09:11:55 -0500127import android.os.Parcel;
Julia Reynoldsf27d6b22017-04-13 15:48:16 -0400128import android.os.Process;
Julia Reynoldsb3c68ff2018-05-22 14:58:39 -0400129import android.os.RemoteException;
Mady Mellorbe797962019-04-01 16:04:24 -0700130import android.os.SystemClock;
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500131import android.os.UserHandle;
Julia Reynolds0c245002019-03-27 16:10:11 -0400132import android.os.UserManager;
Tony Mak9a3c1f12019-03-04 16:04:42 +0000133import android.provider.DeviceConfig;
Jeff Sharkey6a97cc32018-04-17 12:16:20 -0600134import android.provider.MediaStore;
Tony Mak9a3c1f12019-03-04 16:04:42 +0000135import android.provider.Settings;
Julia Reynolds503ed942017-10-04 16:04:56 -0400136import android.service.notification.Adjustment;
Julia Reynolds882f2062020-02-05 12:11:38 -0500137import android.service.notification.ConversationChannelWrapper;
Julia Reynolds73ed76b2017-04-04 17:04:38 -0400138import android.service.notification.NotificationListenerService;
Julia Reynolds503ed942017-10-04 16:04:56 -0400139import android.service.notification.NotificationStats;
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500140import android.service.notification.StatusBarNotification;
Julia Reynoldsa94365d2019-04-09 10:48:43 -0400141import android.service.notification.ZenPolicy;
Will Brockmanaf25fbd2020-03-26 15:49:47 -0400142import android.telephony.TelephonyManager;
Geoffrey Pitsch8185d382017-05-19 18:41:32 -0400143import android.test.suitebuilder.annotation.SmallTest;
Jason Monk745d0a82017-04-17 11:34:22 -0400144import android.testing.AndroidTestingRunner;
Julia Reynolds92febc32017-10-26 11:30:31 -0400145import android.testing.TestableContext;
Geoffrey Pitsch415e4542017-04-10 13:12:58 -0400146import android.testing.TestableLooper;
Jason Monk745d0a82017-04-17 11:34:22 -0400147import android.testing.TestableLooper.RunWithLooper;
Julia Reynolds7a6d07a2019-03-18 11:31:56 -0400148import android.testing.TestablePermissions;
Julia Reynolds57a974b2019-10-07 11:51:47 -0400149import android.testing.TestableResources;
Dan Sandler7d67bd42018-05-15 14:06:38 -0400150import android.text.Html;
Julia Reynolds0f767342019-12-18 09:11:55 -0500151import android.text.TextUtils;
Julia Reynoldseb3dca72017-07-11 10:39:58 -0400152import android.util.ArrayMap;
Tony Mak9a3c1f12019-03-04 16:04:42 +0000153import android.util.ArraySet;
Julia Reynoldsb852e562017-06-06 16:14:18 -0400154import android.util.AtomicFile;
Julia Reynolds469144c2019-06-21 14:30:28 -0400155import android.util.Xml;
Julia Reynoldsb681ffe2019-06-19 13:40:46 -0400156import android.widget.RemoteViews;
Julia Reynoldseb3dca72017-07-11 10:39:58 -0400157
Mady Mellor49b1bf12019-03-29 12:00:02 -0700158import androidx.annotation.Nullable;
159import androidx.test.InstrumentationRegistry;
160
Tony Mak9a3c1f12019-03-04 16:04:42 +0000161import com.android.internal.config.sysui.SystemUiDeviceConfigFlags;
Will Brockmancfd98302020-01-29 15:57:30 -0500162import com.android.internal.logging.InstanceIdSequence;
163import com.android.internal.logging.InstanceIdSequenceFake;
Julia Reynolds503ed942017-10-04 16:04:56 -0400164import com.android.internal.statusbar.NotificationVisibility;
Julia Reynolds469144c2019-06-21 14:30:28 -0400165import com.android.internal.util.FastXmlSerializer;
Mady Mellor13f9bc82020-03-24 19:09:28 -0700166import com.android.server.DeviceIdleInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700167import com.android.server.LocalServices;
Beverly58b24532018-10-02 09:08:23 -0400168import com.android.server.SystemService;
Jason Monk74f5e362017-12-06 08:56:33 -0500169import com.android.server.UiServiceTestCase;
Julia Reynoldseb3dca72017-07-11 10:39:58 -0400170import com.android.server.lights.LightsManager;
Ivailo Karamanolevf773e102020-01-16 16:10:42 +0100171import com.android.server.lights.LogicalLight;
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -0400172import com.android.server.notification.NotificationManagerService.NotificationAssistants;
173import com.android.server.notification.NotificationManagerService.NotificationListeners;
Bernardo Rufino18725b62020-01-21 14:12:43 +0000174import com.android.server.statusbar.StatusBarManagerInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700175import com.android.server.uri.UriGrantsManagerInternal;
Bernardo Rufinoe6cb3102020-03-06 20:33:11 +0000176import com.android.server.wm.ActivityTaskManagerInternal;
Beverly58b24532018-10-02 09:08:23 -0400177import com.android.server.wm.WindowManagerInternal;
Julia Reynoldseb3dca72017-07-11 10:39:58 -0400178
179import org.junit.After;
180import org.junit.Before;
181import org.junit.Test;
182import org.junit.runner.RunWith;
Julia Reynolds40f00d72017-12-12 10:47:32 -0500183import org.mockito.ArgumentCaptor;
184import org.mockito.Mock;
185import org.mockito.MockitoAnnotations;
Julia Reynoldseb3dca72017-07-11 10:39:58 -0400186import org.mockito.stubbing.Answer;
Julia Reynolds469144c2019-06-21 14:30:28 -0400187import org.xmlpull.v1.XmlPullParser;
188import org.xmlpull.v1.XmlSerializer;
Julia Reynolds5f20e9f2017-01-30 08:54:53 -0500189
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -0400190import java.io.BufferedInputStream;
Julia Reynolds469144c2019-06-21 14:30:28 -0400191import java.io.BufferedOutputStream;
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -0400192import java.io.ByteArrayInputStream;
Julia Reynolds469144c2019-06-21 14:30:28 -0400193import java.io.ByteArrayOutputStream;
Julia Reynoldsb852e562017-06-06 16:14:18 -0400194import java.io.File;
Julia Reynoldsb852e562017-06-06 16:14:18 -0400195import java.io.FileOutputStream;
Julia Reynolds73ed76b2017-04-04 17:04:38 -0400196import java.util.ArrayList;
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500197import java.util.Arrays;
Tony Mak9a3c1f12019-03-04 16:04:42 +0000198import java.util.Collections;
Julia Reynolds73ed76b2017-04-04 17:04:38 -0400199import java.util.List;
Julia Reynoldseb3dca72017-07-11 10:39:58 -0400200import java.util.Map;
Robin Leed107af62018-04-27 13:55:56 +0200201import java.util.function.Consumer;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500202
Julia Reynoldsb681ffe2019-06-19 13:40:46 -0400203
Geoffrey Pitsch8185d382017-05-19 18:41:32 -0400204@SmallTest
Jason Monk745d0a82017-04-17 11:34:22 -0400205@RunWith(AndroidTestingRunner.class)
206@RunWithLooper
Jason Monk74f5e362017-12-06 08:56:33 -0500207public class NotificationManagerServiceTest extends UiServiceTestCase {
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -0500208 private static final String TEST_CHANNEL_ID = "NotificationManagerServiceTestChannelId";
Tony Mak9a3c1f12019-03-04 16:04:42 +0000209
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400210 private final int mUid = Binder.getCallingUid();
Julia Reynoldsd78263d2018-01-30 10:40:41 -0500211 private TestableNotificationManagerService mService;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500212 private INotificationManager mBinderService;
Geoffrey Pitsch415e4542017-04-10 13:12:58 -0400213 private NotificationManagerInternal mInternalService;
Mady Mellor56515c42020-02-18 17:58:36 -0800214 private ShortcutHelper mShortcutHelper;
Julia Reynoldsda781472017-04-12 09:41:16 -0400215 @Mock
216 private IPackageManager mPackageManager;
217 @Mock
218 private PackageManager mPackageManagerClient;
Beverly58b24532018-10-02 09:08:23 -0400219 @Mock
220 private WindowManagerInternal mWindowManagerInternal;
Julia Reynolds92febc32017-10-26 11:30:31 -0400221 private TestableContext mContext = spy(getContext());
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -0500222 private final String PKG = mContext.getPackageName();
Geoffrey Pitsch415e4542017-04-10 13:12:58 -0400223 private TestableLooper mTestableLooper;
Julia Reynoldsda781472017-04-12 09:41:16 -0400224 @Mock
225 private RankingHelper mRankingHelper;
Aaron Heuckrothe5bec152018-07-09 16:26:09 -0400226 @Mock private PreferencesHelper mPreferencesHelper;
Julia Reynoldsb852e562017-06-06 16:14:18 -0400227 AtomicFile mPolicyFile;
228 File mFile;
229 @Mock
Geoffrey Pitschd5bcf212017-06-01 15:45:35 -0400230 private NotificationUsageStats mUsageStats;
Julia Reynolds76c096d2017-06-19 08:16:04 -0400231 @Mock
Julia Reynoldsb3c68ff2018-05-22 14:58:39 -0400232 private UsageStatsManagerInternal mAppUsageStats;
233 @Mock
Julia Reynolds76c096d2017-06-19 08:16:04 -0400234 private AudioManager mAudioManager;
Julia Reynolds68263d12017-06-21 14:21:19 -0400235 @Mock
Mady Mellor2ac2d3a2020-01-08 17:18:54 -0800236 private LauncherApps mLauncherApps;
237 @Mock
Julia Reynoldsfa273072020-04-14 15:31:21 -0400238 private ShortcutServiceInternal mShortcutServiceInternal;
239 @Mock
Julia Reynolds68263d12017-06-21 14:21:19 -0400240 ActivityManager mActivityManager;
Kristian Monsen05f34792018-04-09 10:27:16 +0200241 @Mock
242 Resources mResources;
Julia Reynoldsb6c83742019-07-30 18:03:40 -0400243 @Mock
244 RankingHandler mRankingHandler;
Julia Reynolds3ff26d22017-06-19 08:16:04 -0400245
Julia Reynoldsb317ff72019-11-26 14:20:51 -0500246 private static final int MAX_POST_DELAY = 1000;
247
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -0500248 private NotificationChannel mTestNotificationChannel = new NotificationChannel(
Julia Reynolds27c0a962018-12-10 12:37:28 -0500249 TEST_CHANNEL_ID, TEST_CHANNEL_ID, IMPORTANCE_DEFAULT);
Gustav Senntona8e38aa2019-01-22 14:55:39 +0000250
251 private static final int NOTIFICATION_LOCATION_UNKNOWN = 0;
252
Julia Reynoldsda781472017-04-12 09:41:16 -0400253 @Mock
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -0400254 private NotificationListeners mListeners;
255 @Mock private NotificationAssistants mAssistants;
Julia Reynoldsb852e562017-06-06 16:14:18 -0400256 @Mock private ConditionProviders mConditionProviders;
Julia Reynoldsda781472017-04-12 09:41:16 -0400257 private ManagedServices.ManagedServiceInfo mListener;
258 @Mock private ICompanionDeviceManager mCompanionMgr;
Julia Reynoldsa78cdff2017-04-26 10:19:25 -0400259 @Mock SnoozeHelper mSnoozeHelper;
Julia Reynolds8aebf352017-06-26 11:35:33 -0400260 @Mock GroupHelper mGroupHelper;
Julia Reynoldse0d711f2017-09-01 08:50:47 -0400261 @Mock
262 IBinder mPermOwner;
263 @Mock
264 IActivityManager mAm;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700265 @Mock
Bernardo Rufinoe6cb3102020-03-06 20:33:11 +0000266 ActivityTaskManagerInternal mAtm;
267 @Mock
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700268 IUriGrantsManager mUgm;
269 @Mock
270 UriGrantsManagerInternal mUgmInternal;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -0400271 @Mock
272 AppOpsManager mAppOpsManager;
Annie Meng8b646fd2019-02-01 18:46:42 +0000273 @Mock
Tony Mak9a3c1f12019-03-04 16:04:42 +0000274 private TestableNotificationManagerService.NotificationAssistantAccessGrantedCallback
275 mNotificationAssistantAccessGrantedCallback;
Julia Reynolds0c245002019-03-27 16:10:11 -0400276 @Mock
277 UserManager mUm;
Julia Reynoldsb317ff72019-11-26 14:20:51 -0500278 @Mock
279 NotificationHistoryManager mHistoryManager;
Yotam Aron74299972020-01-16 16:20:58 +0200280 @Mock
281 StatsManager mStatsManager;
Will Brockman2b6959e2020-01-22 09:59:50 -0500282 NotificationRecordLoggerFake mNotificationRecordLogger = new NotificationRecordLoggerFake();
Will Brockmancfd98302020-01-29 15:57:30 -0500283 private InstanceIdSequence mNotificationInstanceIdSequence = new InstanceIdSequenceFake(
284 1 << 30);
Bernardo Rufino18725b62020-01-21 14:12:43 +0000285 @Mock
286 StatusBarManagerInternal mStatusBar;
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500287
Geoffrey Pitsch415e4542017-04-10 13:12:58 -0400288 // Use a Testable subclass so we can simulate calls from the system without failing.
289 private static class TestableNotificationManagerService extends NotificationManagerService {
Julia Reynoldsd78263d2018-01-30 10:40:41 -0500290 int countSystemChecks = 0;
Brad Stenning8c991ea2018-07-31 13:33:01 -0700291 boolean isSystemUid = true;
Gustav Sennton44dc5882018-12-13 14:38:50 +0000292 int countLogSmartSuggestionsVisible = 0;
Tony Mak9a3c1f12019-03-04 16:04:42 +0000293 @Nullable
294 NotificationAssistantAccessGrantedCallback mNotificationAssistantAccessGrantedCallback;
Julia Reynoldsd78263d2018-01-30 10:40:41 -0500295
Will Brockmancfd98302020-01-29 15:57:30 -0500296 TestableNotificationManagerService(Context context, NotificationRecordLogger logger,
297 InstanceIdSequence notificationInstanceIdSequence) {
298 super(context, logger, notificationInstanceIdSequence);
Amith Yamasani803eab692017-11-09 17:47:04 -0800299 }
Geoffrey Pitsch415e4542017-04-10 13:12:58 -0400300
Mady Mellor56515c42020-02-18 17:58:36 -0800301 RankingHelper getRankingHelper() {
302 return mRankingHelper;
303 }
304
Geoffrey Pitsch415e4542017-04-10 13:12:58 -0400305 @Override
Geoffrey Pitsch27684152017-05-02 11:41:31 -0400306 protected boolean isCallingUidSystem() {
Julia Reynoldsd78263d2018-01-30 10:40:41 -0500307 countSystemChecks++;
Brad Stenning8c991ea2018-07-31 13:33:01 -0700308 return isSystemUid;
Geoffrey Pitsch27684152017-05-02 11:41:31 -0400309 }
310
311 @Override
312 protected boolean isCallerSystemOrPhone() {
Julia Reynoldsd78263d2018-01-30 10:40:41 -0500313 countSystemChecks++;
Brad Stenning8c991ea2018-07-31 13:33:01 -0700314 return isSystemUid;
Julia Reynolds73ed76b2017-04-04 17:04:38 -0400315 }
Julia Reynolds727a7282017-04-13 10:54:01 -0400316
317 @Override
318 protected ICompanionDeviceManager getCompanionManager() {
319 return null;
320 }
Amith Yamasani803eab692017-11-09 17:47:04 -0800321
322 @Override
Amith Yamasani7ec89412018-02-07 08:48:49 -0800323 protected void reportUserInteraction(NotificationRecord r) {
324 return;
325 }
Julia Reynoldsb62dad42018-11-26 16:33:02 -0500326
327 @Override
328 protected void handleSavePolicyFile() {
329 return;
330 }
Gustav Sennton44dc5882018-12-13 14:38:50 +0000331
332 @Override
Gustav Senntonc7d0d322019-01-07 15:36:41 +0000333 void logSmartSuggestionsVisible(NotificationRecord r, int notificationLocation) {
334 super.logSmartSuggestionsVisible(r, notificationLocation);
Gustav Sennton44dc5882018-12-13 14:38:50 +0000335 countLogSmartSuggestionsVisible++;
336 }
337
Annie Meng8b646fd2019-02-01 18:46:42 +0000338 @Override
Tony Mak9a3c1f12019-03-04 16:04:42 +0000339 protected void setNotificationAssistantAccessGrantedForUserInternal(
340 ComponentName assistant, int userId, boolean granted) {
341 if (mNotificationAssistantAccessGrantedCallback != null) {
342 mNotificationAssistantAccessGrantedCallback.onGranted(assistant, userId, granted);
343 return;
344 }
345 super.setNotificationAssistantAccessGrantedForUserInternal(assistant, userId, granted);
346 }
347
348 private void setNotificationAssistantAccessGrantedCallback(
349 @Nullable NotificationAssistantAccessGrantedCallback callback) {
350 this.mNotificationAssistantAccessGrantedCallback = callback;
351 }
352
353 interface NotificationAssistantAccessGrantedCallback {
354 void onGranted(ComponentName assistant, int userId, boolean granted);
355 }
Mady Mellor56515c42020-02-18 17:58:36 -0800356 }
357
Beverly58b24532018-10-02 09:08:23 -0400358 private class TestableToastCallback extends ITransientNotification.Stub {
359 @Override
360 public void show(IBinder windowToken) {
361 }
362
363 @Override
364 public void hide() {
365 }
366 }
367
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500368 @Before
369 public void setUp() throws Exception {
Beverly24d103b2020-02-18 17:40:57 -0500370 // Shell permisssions will override permissions of our app, so add all necessary permissions
Beverly080782f2020-02-24 16:42:57 -0500371 // for this test here:
Stanislav Zholnin872afd42019-03-12 15:57:25 +0000372 InstrumentationRegistry.getInstrumentation().getUiAutomation().adoptShellPermissionIdentity(
Beverly24d103b2020-02-18 17:40:57 -0500373 "android.permission.WRITE_DEVICE_CONFIG",
374 "android.permission.READ_DEVICE_CONFIG",
375 "android.permission.READ_CONTACTS");
Stanislav Zholnin872afd42019-03-12 15:57:25 +0000376
Julia Reynoldsda781472017-04-12 09:41:16 -0400377 MockitoAnnotations.initMocks(this);
Chris Wren89aa2262017-05-05 18:05:56 -0400378
Mady Mellor13f9bc82020-03-24 19:09:28 -0700379 DeviceIdleInternal deviceIdleInternal = mock(DeviceIdleInternal.class);
380 when(deviceIdleInternal.getNotificationWhitelistDuration()).thenReturn(3000L);
381 ActivityManagerInternal activityManagerInternal = mock(ActivityManagerInternal.class);
382
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700383 LocalServices.removeServiceForTest(UriGrantsManagerInternal.class);
384 LocalServices.addService(UriGrantsManagerInternal.class, mUgmInternal);
Beverly58b24532018-10-02 09:08:23 -0400385 LocalServices.removeServiceForTest(WindowManagerInternal.class);
386 LocalServices.addService(WindowManagerInternal.class, mWindowManagerInternal);
Bernardo Rufino18725b62020-01-21 14:12:43 +0000387 LocalServices.removeServiceForTest(StatusBarManagerInternal.class);
388 LocalServices.addService(StatusBarManagerInternal.class, mStatusBar);
Mady Mellor13f9bc82020-03-24 19:09:28 -0700389 LocalServices.removeServiceForTest(DeviceIdleInternal.class);
390 LocalServices.addService(DeviceIdleInternal.class, deviceIdleInternal);
391 LocalServices.removeServiceForTest(ActivityManagerInternal.class);
392 LocalServices.addService(ActivityManagerInternal.class, activityManagerInternal);
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700393
Julia Reynolds4afe2642019-05-01 08:42:24 -0400394 doNothing().when(mContext).sendBroadcastAsUser(any(), any(), any());
395
Will Brockmancfd98302020-01-29 15:57:30 -0500396 mService = new TestableNotificationManagerService(mContext, mNotificationRecordLogger,
397 mNotificationInstanceIdSequence);
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500398
Julia Reynoldseb3dca72017-07-11 10:39:58 -0400399 // Use this testable looper.
400 mTestableLooper = TestableLooper.get(this);
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500401 // MockPackageManager - default returns ApplicationInfo with matching calling UID
Julia Reynolds92febc32017-10-26 11:30:31 -0400402 mContext.setMockPackageManager(mPackageManagerClient);
Julia Reynoldsb681ffe2019-06-19 13:40:46 -0400403
Julia Reynolds73ed76b2017-04-04 17:04:38 -0400404 when(mPackageManager.getApplicationInfo(anyString(), anyInt(), anyInt()))
Julia Reynoldsb681ffe2019-06-19 13:40:46 -0400405 .thenAnswer((Answer<ApplicationInfo>) invocation -> {
406 Object[] args = invocation.getArguments();
407 return getApplicationInfo((String) args[0], mUid);
408 });
Julia Reynolds5f20e9f2017-01-30 08:54:53 -0500409 when(mPackageManagerClient.getApplicationInfoAsUser(anyString(), anyInt(), anyInt()))
Julia Reynoldsb681ffe2019-06-19 13:40:46 -0400410 .thenAnswer((Answer<ApplicationInfo>) invocation -> {
411 Object[] args = invocation.getArguments();
412 return getApplicationInfo((String) args[0], mUid);
413 });
Julia Reynolds92febc32017-10-26 11:30:31 -0400414 when(mPackageManagerClient.getPackageUidAsUser(any(), anyInt())).thenReturn(mUid);
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500415 final LightsManager mockLightsManager = mock(LightsManager.class);
Ivailo Karamanolevf773e102020-01-16 16:10:42 +0100416 when(mockLightsManager.getLight(anyInt())).thenReturn(mock(LogicalLight.class));
Julia Reynolds76c096d2017-06-19 08:16:04 -0400417 when(mAudioManager.getRingerModeInternal()).thenReturn(AudioManager.RINGER_MODE_NORMAL);
Julia Reynoldse1816412017-10-24 10:39:11 -0400418 when(mPackageManagerClient.hasSystemFeature(FEATURE_WATCH)).thenReturn(false);
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700419 when(mUgmInternal.newUriPermissionOwner(anyString())).thenReturn(mPermOwner);
Julia Reynolds268647a2018-10-25 16:54:27 -0400420 when(mPackageManager.getPackagesForUid(mUid)).thenReturn(new String[]{PKG});
Julia Reynolds4214da92019-04-10 15:04:06 -0400421 when(mPackageManagerClient.getPackagesForUid(anyInt())).thenReturn(new String[]{PKG});
Julia Reynoldse99db5a2019-04-16 12:50:04 -0400422 mContext.addMockSystemService(AppOpsManager.class, mock(AppOpsManager.class));
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500423
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -0400424 // write to a test file; the system file isn't readable from tests
Julia Reynoldsb852e562017-06-06 16:14:18 -0400425 mFile = new File(mContext.getCacheDir(), "test.xml");
426 mFile.createNewFile();
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -0400427 final String preupgradeXml = "<notification-policy></notification-policy>";
428 mPolicyFile = new AtomicFile(mFile);
429 FileOutputStream fos = mPolicyFile.startWrite();
430 fos.write(preupgradeXml.getBytes());
431 mPolicyFile.finishWrite(fos);
Julia Reynoldsb852e562017-06-06 16:14:18 -0400432
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -0400433 // Setup managed services
434 mListener = mListeners.new ManagedServiceInfo(
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400435 null, new ComponentName(PKG, "test_class"), mUid, true, null, 0);
Jay Aliomer4204f252019-08-26 11:36:53 -0400436 ComponentName defaultComponent = ComponentName.unflattenFromString("config/device");
437 ArraySet<ComponentName> components = new ArraySet<>();
438 components.add(defaultComponent);
439 when(mListeners.getDefaultComponents()).thenReturn(components);
440 when(mConditionProviders.getDefaultPackages())
441 .thenReturn(new ArraySet<>(Arrays.asList("config")));
442 when(mAssistants.getDefaultComponents()).thenReturn(components);
443 when(mAssistants.queryPackageForServices(
444 anyString(), anyInt(), anyInt())).thenReturn(components);
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -0400445 when(mListeners.checkServiceTokenLocked(any())).thenReturn(mListener);
446 ManagedServices.Config listenerConfig = new ManagedServices.Config();
447 listenerConfig.xmlTag = NotificationListeners.TAG_ENABLED_NOTIFICATION_LISTENERS;
448 when(mListeners.getConfig()).thenReturn(listenerConfig);
449 ManagedServices.Config assistantConfig = new ManagedServices.Config();
450 assistantConfig.xmlTag = NotificationAssistants.TAG_ENABLED_NOTIFICATION_ASSISTANTS;
451 when(mAssistants.getConfig()).thenReturn(assistantConfig);
452 ManagedServices.Config dndConfig = new ManagedServices.Config();
453 dndConfig.xmlTag = ConditionProviders.TAG_ENABLED_DND_APPS;
454 when(mConditionProviders.getConfig()).thenReturn(dndConfig);
455
Julia Reynolds418a8ff2019-03-21 10:45:10 -0400456 when(mAssistants.isAdjustmentAllowed(anyString())).thenReturn(true);
457
Julia Reynoldsb317ff72019-11-26 14:20:51 -0500458 mService.init(mService.new WorkerHandler(mTestableLooper.getLooper()),
459 mRankingHandler, mPackageManager, mPackageManagerClient, mockLightsManager,
Julia Reynolds4afe2642019-05-01 08:42:24 -0400460 mListeners, mAssistants, mConditionProviders,
461 mCompanionMgr, mSnoozeHelper, mUsageStats, mPolicyFile, mActivityManager,
Bernardo Rufinoe6cb3102020-03-06 20:33:11 +0000462 mGroupHelper, mAm, mAtm, mAppUsageStats,
Julia Reynolds4afe2642019-05-01 08:42:24 -0400463 mock(DevicePolicyManagerInternal.class), mUgm, mUgmInternal,
Will Brockmanaf25fbd2020-03-26 15:49:47 -0400464 mAppOpsManager, mUm, mHistoryManager, mStatsManager,
465 mock(TelephonyManager.class));
Julia Reynolds4afe2642019-05-01 08:42:24 -0400466 mService.onBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
467
Julia Reynolds503ed942017-10-04 16:04:56 -0400468 mService.setAudioManager(mAudioManager);
Mady Mellor56515c42020-02-18 17:58:36 -0800469
470 mShortcutHelper = mService.getShortcutHelper();
471 mShortcutHelper.setLauncherApps(mLauncherApps);
Julia Reynoldsfa273072020-04-14 15:31:21 -0400472 mShortcutHelper.setShortcutServiceInternal(mShortcutServiceInternal);
Mady Mellor56515c42020-02-18 17:58:36 -0800473
474 // Set the testable bubble extractor
475 RankingHelper rankingHelper = mService.getRankingHelper();
476 BubbleExtractor extractor = rankingHelper.findExtractor(BubbleExtractor.class);
Mady Mellora92268c2020-03-09 17:25:08 -0700477 extractor.setActivityManager(mActivityManager);
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500478
479 // Tests call directly into the Binder.
Julia Reynolds503ed942017-10-04 16:04:56 -0400480 mBinderService = mService.getBinderService();
481 mInternalService = mService.getInternalService();
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -0500482
483 mBinderService.createNotificationChannels(
484 PKG, new ParceledListSlice(Arrays.asList(mTestNotificationChannel)));
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -0400485 assertNotNull(mBinderService.getNotificationChannel(
486 PKG, mContext.getUserId(), PKG, TEST_CHANNEL_ID));
Julia Reynoldsb6c83742019-07-30 18:03:40 -0400487 clearInvocations(mRankingHandler);
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500488 }
489
Julia Reynoldsb852e562017-06-06 16:14:18 -0400490 @After
Will Brockman9918db92020-03-06 16:48:39 -0500491 public void assertNotificationRecordLoggerCallsValid() {
492 for (NotificationRecordLoggerFake.CallRecord call : mNotificationRecordLogger.getCalls()) {
493 if (call.wasLogged) {
494 assertNotNull(call.event);
495 }
496 }
497 }
498
499 @After
Julia Reynoldsb852e562017-06-06 16:14:18 -0400500 public void tearDown() throws Exception {
Julia Reynoldsb681ffe2019-06-19 13:40:46 -0400501 if (mFile != null) mFile.delete();
Tony Mak9a3c1f12019-03-04 16:04:42 +0000502 clearDeviceConfig();
Julia Reynoldsb317ff72019-11-26 14:20:51 -0500503 mService.unregisterDeviceConfigChange();
Stanislav Zholnin872afd42019-03-12 15:57:25 +0000504 InstrumentationRegistry.getInstrumentation()
505 .getUiAutomation().dropShellPermissionIdentity();
Julia Reynoldsb852e562017-06-06 16:14:18 -0400506 }
507
Jay Aliomer4204f252019-08-26 11:36:53 -0400508 private ArrayMap<Boolean, ArrayList<ComponentName>> generateResetComponentValues() {
509 ArrayMap<Boolean, ArrayList<ComponentName>> changed = new ArrayMap<>();
510 changed.put(true, new ArrayList<>());
511 changed.put(false, new ArrayList<>());
512 return changed;
513 }
Julia Reynoldsb681ffe2019-06-19 13:40:46 -0400514 private ApplicationInfo getApplicationInfo(String pkg, int uid) {
515 final ApplicationInfo applicationInfo = new ApplicationInfo();
516 applicationInfo.uid = uid;
517 switch (pkg) {
518 case PKG_N_MR1:
519 applicationInfo.targetSdkVersion = Build.VERSION_CODES.N_MR1;
520 break;
521 case PKG_O:
522 applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
523 break;
524 case PKG_P:
525 applicationInfo.targetSdkVersion = Build.VERSION_CODES.P;
526 break;
527 default:
528 applicationInfo.targetSdkVersion = Build.VERSION_CODES.CUR_DEVELOPMENT;
529 break;
530 }
531 return applicationInfo;
532 }
533
Julia Reynolds7bcb57b2018-01-22 10:37:58 -0500534 public void waitForIdle() {
Geoffrey Pitsch415e4542017-04-10 13:12:58 -0400535 mTestableLooper.processAllMessages();
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500536 }
537
Julia Reynolds12ba4cf2020-01-10 16:01:38 -0500538 private void setUpPrefsForBubbles(String pkg, int uid, boolean globalEnabled,
Mady Mellora92268c2020-03-09 17:25:08 -0700539 int pkgPref, boolean channelEnabled) {
Julia Reynolds12ba4cf2020-01-10 16:01:38 -0500540 Settings.Global.putInt(mContext.getContentResolver(),
541 Settings.Global.NOTIFICATION_BUBBLES, globalEnabled ? 1 : 0);
542 mService.mPreferencesHelper.updateBubblesEnabled();
543 assertEquals(globalEnabled, mService.mPreferencesHelper.bubblesEnabled());
544 try {
Mady Mellora92268c2020-03-09 17:25:08 -0700545 mBinderService.setBubblesAllowed(pkg, uid, pkgPref);
Julia Reynolds12ba4cf2020-01-10 16:01:38 -0500546 } catch (RemoteException e) {
547 e.printStackTrace();
548 }
Mady Mellorc6820342019-05-20 12:04:36 -0700549 mTestNotificationChannel.setAllowBubbles(channelEnabled);
550 }
551
Julia Reynolds7bcb57b2018-01-22 10:37:58 -0500552 private StatusBarNotification generateSbn(String pkg, int uid, long postTime, int userId) {
553 Notification.Builder nb = new Notification.Builder(mContext, "a")
554 .setContentTitle("foo")
555 .setSmallIcon(android.R.drawable.sym_def_app_icon);
Julia Reynoldsb6c83742019-07-30 18:03:40 -0400556 StatusBarNotification sbn = new StatusBarNotification(pkg, pkg, uid,
557 "tag" + System.currentTimeMillis(), uid, 0,
Julia Reynolds7bcb57b2018-01-22 10:37:58 -0500558 nb.build(), new UserHandle(userId), null, postTime);
559 return sbn;
560 }
561
Julia Reynoldsa78cdff2017-04-26 10:19:25 -0400562 private NotificationRecord generateNotificationRecord(NotificationChannel channel, int id,
563 String groupKey, boolean isSummary) {
564 Notification.Builder nb = new Notification.Builder(mContext, channel.getId())
565 .setContentTitle("foo")
566 .setSmallIcon(android.R.drawable.sym_def_app_icon)
567 .setGroup(groupKey)
568 .setGroupSummary(isSummary);
Julia Reynoldsb6c83742019-07-30 18:03:40 -0400569 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, id,
570 "tag" + System.currentTimeMillis(), mUid, 0,
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400571 nb.build(), new UserHandle(mUid), null, 0);
Geoffrey Pitscha22f6442017-05-05 16:47:38 +0000572 return new NotificationRecord(mContext, sbn, channel);
Julia Reynoldsa78cdff2017-04-26 10:19:25 -0400573 }
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400574
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500575 private NotificationRecord generateNotificationRecord(NotificationChannel channel) {
Julia Reynolds5f20e9f2017-01-30 08:54:53 -0500576 return generateNotificationRecord(channel, null);
577 }
578
579 private NotificationRecord generateNotificationRecord(NotificationChannel channel,
580 Notification.TvExtender extender) {
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500581 if (channel == null) {
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -0500582 channel = mTestNotificationChannel;
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500583 }
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500584 Notification.Builder nb = new Notification.Builder(mContext, channel.getId())
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500585 .setContentTitle("foo")
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500586 .setSmallIcon(android.R.drawable.sym_def_app_icon);
Julia Reynolds5f20e9f2017-01-30 08:54:53 -0500587 if (extender != null) {
588 nb.extend(extender);
589 }
Julia Reynoldsb6c83742019-07-30 18:03:40 -0400590 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 8, "tag", mUid, 0,
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400591 nb.build(), new UserHandle(mUid), null, 0);
Geoffrey Pitscha22f6442017-05-05 16:47:38 +0000592 return new NotificationRecord(mContext, sbn, channel);
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -0500593 }
594
Aran Inkfd2bfd32019-10-04 16:30:01 -0400595 private NotificationRecord generateNotificationRecord(NotificationChannel channel, int userId) {
596 if (channel == null) {
597 channel = mTestNotificationChannel;
598 }
599 Notification.Builder nb = new Notification.Builder(mContext, channel.getId())
600 .setContentTitle("foo")
601 .setSmallIcon(android.R.drawable.sym_def_app_icon);
602 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, "tag", mUid, 0,
603 nb.build(), new UserHandle(userId), null, 0);
604 return new NotificationRecord(mContext, sbn, channel);
605 }
606
Mady Mellor9e923e12019-12-17 16:08:46 -0800607 private NotificationRecord generateMessageBubbleNotifRecord(NotificationChannel channel,
608 String tag) {
609 return generateMessageBubbleNotifRecord(true, channel, 1, tag, null, false);
610 }
611
612 private NotificationRecord generateMessageBubbleNotifRecord(boolean addMetadata,
613 NotificationChannel channel, int id, String tag, String groupKey, boolean isSummary) {
614 if (channel == null) {
615 channel = mTestNotificationChannel;
616 }
617 if (tag == null) {
618 tag = "tag";
619 }
620 Notification.Builder nb = getMessageStyleNotifBuilder(addMetadata, groupKey, isSummary);
621 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, id,
622 tag, mUid, 0,
623 nb.build(), new UserHandle(mUid), null, 0);
624 return new NotificationRecord(mContext, sbn, channel);
625 }
626
Julia Reynoldseb3dca72017-07-11 10:39:58 -0400627 private Map<String, Answer> getSignalExtractorSideEffects() {
628 Map<String, Answer> answers = new ArrayMap<>();
629
630 answers.put("override group key", invocationOnMock -> {
631 ((NotificationRecord) invocationOnMock.getArguments()[0])
632 .setOverrideGroupKey("bananas");
633 return null;
634 });
635 answers.put("override people", invocationOnMock -> {
636 ((NotificationRecord) invocationOnMock.getArguments()[0])
637 .setPeopleOverride(new ArrayList<>());
638 return null;
639 });
640 answers.put("snooze criteria", invocationOnMock -> {
641 ((NotificationRecord) invocationOnMock.getArguments()[0])
642 .setSnoozeCriteria(new ArrayList<>());
643 return null;
644 });
645 answers.put("notification channel", invocationOnMock -> {
646 ((NotificationRecord) invocationOnMock.getArguments()[0])
647 .updateNotificationChannel(new NotificationChannel("a", "", IMPORTANCE_LOW));
648 return null;
649 });
650 answers.put("badging", invocationOnMock -> {
651 NotificationRecord r = (NotificationRecord) invocationOnMock.getArguments()[0];
652 r.setShowBadge(!r.canShowBadge());
653 return null;
654 });
Julia Reynolds4509ce72019-01-31 13:12:43 -0500655 answers.put("bubbles", invocationOnMock -> {
656 NotificationRecord r = (NotificationRecord) invocationOnMock.getArguments()[0];
657 r.setAllowBubble(!r.canBubble());
658 return null;
659 });
Julia Reynoldseb3dca72017-07-11 10:39:58 -0400660 answers.put("package visibility", invocationOnMock -> {
661 ((NotificationRecord) invocationOnMock.getArguments()[0]).setPackageVisibilityOverride(
662 Notification.VISIBILITY_SECRET);
663 return null;
664 });
665
666 return answers;
667 }
668
Julia Reynoldsc7dcdc22019-03-25 10:26:14 -0400669 private void clearDeviceConfig() {
670 DeviceConfig.resetToDefaults(
671 Settings.RESET_MODE_PACKAGE_DEFAULTS, DeviceConfig.NAMESPACE_SYSTEMUI);
672 }
673
674 private void setDefaultAssistantInDeviceConfig(String componentName) {
675 DeviceConfig.setProperty(
676 DeviceConfig.NAMESPACE_SYSTEMUI,
677 SystemUiDeviceConfigFlags.NAS_DEFAULT_SERVICE,
678 componentName,
679 false);
680 }
681
Mady Mellor9e923e12019-12-17 16:08:46 -0800682 private Notification.Builder getMessageStyleNotifBuilder(boolean addBubbleMetadata,
683 String groupKey, boolean isSummary) {
684 // Give it a person
685 Person person = new Person.Builder()
686 .setName("bubblebot")
687 .build();
Mady Mellor9e923e12019-12-17 16:08:46 -0800688 RemoteInput remoteInput = new RemoteInput.Builder("reply_key").setLabel("reply").build();
689 PendingIntent inputIntent = PendingIntent.getActivity(mContext, 0, new Intent(), 0);
690 Icon icon = Icon.createWithResource(mContext, android.R.drawable.sym_def_app_icon);
691 Notification.Action replyAction = new Notification.Action.Builder(icon, "Reply",
692 inputIntent).addRemoteInput(remoteInput)
693 .build();
694 // Make it messaging style
695 Notification.Builder nb = new Notification.Builder(mContext,
696 mTestNotificationChannel.getId())
697 .setContentTitle("foo")
698 .setStyle(new Notification.MessagingStyle(person)
699 .setConversationTitle("Bubble Chat")
700 .addMessage("Hello?",
701 SystemClock.currentThreadTimeMillis() - 300000, person)
702 .addMessage("Is it me you're looking for?",
703 SystemClock.currentThreadTimeMillis(), person)
704 )
705 .setActions(replyAction)
706 .setSmallIcon(android.R.drawable.sym_def_app_icon)
707 .setGroupSummary(isSummary);
708 if (groupKey != null) {
709 nb.setGroup(groupKey);
710 }
711 if (addBubbleMetadata) {
Mady Mellora92268c2020-03-09 17:25:08 -0700712 nb.setBubbleMetadata(getBubbleMetadata());
Mady Mellor9e923e12019-12-17 16:08:46 -0800713 }
714 return nb;
715 }
716
Mady Mellora92268c2020-03-09 17:25:08 -0700717 private Notification.BubbleMetadata getBubbleMetadata() {
718 PendingIntent pendingIntent = mock(PendingIntent.class);
719 Intent intent = mock(Intent.class);
720 when(pendingIntent.getIntent()).thenReturn(intent);
721
722 ActivityInfo info = new ActivityInfo();
723 info.resizeMode = RESIZE_MODE_RESIZEABLE;
724 when(intent.resolveActivityInfo(any(), anyInt())).thenReturn(info);
725
726 return new Notification.BubbleMetadata.Builder(
727 pendingIntent,
728 Icon.createWithResource(mContext, android.R.drawable.sym_def_app_icon))
729 .build();
730 }
731
Mady Mellor22f2f072019-04-18 13:26:18 -0700732 private NotificationRecord addGroupWithBubblesAndValidateAdded(boolean summaryAutoCancel)
733 throws RemoteException {
734
Mady Mellor9e923e12019-12-17 16:08:46 -0800735 String groupKey = "BUBBLE_GROUP";
Mady Mellor22f2f072019-04-18 13:26:18 -0700736
Mady Mellor9e923e12019-12-17 16:08:46 -0800737 // Notification that has bubble metadata
738 NotificationRecord nrBubble = generateMessageBubbleNotifRecord(true /* addMetadata */,
739 mTestNotificationChannel, 1 /* id */, "tag", groupKey, false /* isSummary */);
Mady Mellor22f2f072019-04-18 13:26:18 -0700740
Julia Reynolds24edc002020-01-29 16:35:32 -0500741 mBinderService.enqueueNotificationWithTag(PKG, PKG, nrBubble.getSbn().getTag(),
742 nrBubble.getSbn().getId(), nrBubble.getSbn().getNotification(),
743 nrBubble.getSbn().getUserId());
Mady Mellor22f2f072019-04-18 13:26:18 -0700744 waitForIdle();
745
746 // Make sure we are a bubble
747 StatusBarNotification[] notifsAfter = mBinderService.getActiveNotifications(PKG);
748 assertEquals(1, notifsAfter.length);
749 assertTrue((notifsAfter[0].getNotification().flags & FLAG_BUBBLE) != 0);
750
Mady Mellor9e923e12019-12-17 16:08:46 -0800751 // Notification without bubble metadata
752 NotificationRecord nrPlain = generateMessageBubbleNotifRecord(false /* addMetadata */,
753 mTestNotificationChannel, 2 /* id */, "tag", groupKey, false /* isSummary */);
754
Julia Reynolds24edc002020-01-29 16:35:32 -0500755 mBinderService.enqueueNotificationWithTag(PKG, PKG, nrPlain.getSbn().getTag(),
756 nrPlain.getSbn().getId(), nrPlain.getSbn().getNotification(),
757 nrPlain.getSbn().getUserId());
Mady Mellor22f2f072019-04-18 13:26:18 -0700758 waitForIdle();
759
760 notifsAfter = mBinderService.getActiveNotifications(PKG);
761 assertEquals(2, notifsAfter.length);
762
763 // Summary notification for both of those
Mady Mellor9e923e12019-12-17 16:08:46 -0800764 NotificationRecord nrSummary = generateMessageBubbleNotifRecord(false /* addMetadata */,
765 mTestNotificationChannel, 3 /* id */, "tag", groupKey, true /* isSummary */);
766
Mady Mellor22f2f072019-04-18 13:26:18 -0700767 if (summaryAutoCancel) {
768 nrSummary.getNotification().flags |= FLAG_AUTO_CANCEL;
769 }
Julia Reynolds24edc002020-01-29 16:35:32 -0500770 mBinderService.enqueueNotificationWithTag(PKG, PKG, nrSummary.getSbn().getTag(),
771 nrSummary.getSbn().getId(), nrSummary.getSbn().getNotification(),
772 nrSummary.getSbn().getUserId());
Mady Mellor22f2f072019-04-18 13:26:18 -0700773 waitForIdle();
774
775 notifsAfter = mBinderService.getActiveNotifications(PKG);
776 assertEquals(3, notifsAfter.length);
777
778 return nrSummary;
779 }
780
Geoffrey Pitsch16594462017-01-26 14:42:30 -0500781 @Test
Jay Aliomerfea80252019-11-20 18:14:24 -0500782 public void testDefaultAssistant_overrideDefault() {
783 final int userId = 0;
784 final String testComponent = "package/class";
785 final List<UserInfo> userInfos = new ArrayList<>();
786 userInfos.add(new UserInfo(0, "", 0));
787 final ArraySet<ComponentName> validAssistants = new ArraySet<>();
788 validAssistants.add(ComponentName.unflattenFromString(testComponent));
Jay Aliomerfea80252019-11-20 18:14:24 -0500789 when(mActivityManager.isLowRamDevice()).thenReturn(false);
790 when(mAssistants.queryPackageForServices(isNull(), anyInt(), anyInt()))
791 .thenReturn(validAssistants);
Jay Aliomer76e1f2722020-03-05 12:36:38 -0500792 when(mAssistants.getDefaultComponents()).thenReturn(validAssistants);
Jay Aliomerfea80252019-11-20 18:14:24 -0500793 when(mUm.getEnabledProfiles(anyInt())).thenReturn(userInfos);
794
795 mService.setDefaultAssistantForUser(userId);
796
797 verify(mAssistants).setPackageOrComponentEnabled(
798 eq(testComponent), eq(userId), eq(true), eq(true));
Jay Aliomerfea80252019-11-20 18:14:24 -0500799 }
800
801 @Test
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500802 public void testCreateNotificationChannels_SingleChannel() throws Exception {
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500803 final NotificationChannel channel =
Julia Reynolds27c0a962018-12-10 12:37:28 -0500804 new NotificationChannel("id", "name", IMPORTANCE_DEFAULT);
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400805 mBinderService.createNotificationChannels(PKG,
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500806 new ParceledListSlice(Arrays.asList(channel)));
807 final NotificationChannel createdChannel =
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -0400808 mBinderService.getNotificationChannel(PKG, mContext.getUserId(), PKG, "id");
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500809 assertTrue(createdChannel != null);
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500810 }
811
Geoffrey Pitsch16594462017-01-26 14:42:30 -0500812 @Test
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500813 public void testCreateNotificationChannels_NullChannelThrowsException() throws Exception {
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500814 try {
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400815 mBinderService.createNotificationChannels(PKG,
Kristian Monsen05f34792018-04-09 10:27:16 +0200816 new ParceledListSlice(Arrays.asList((Object[])null)));
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -0500817 fail("Exception should be thrown immediately.");
818 } catch (NullPointerException e) {
819 // pass
820 }
821 }
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500822
Geoffrey Pitsch16594462017-01-26 14:42:30 -0500823 @Test
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500824 public void testCreateNotificationChannels_TwoChannels() throws Exception {
825 final NotificationChannel channel1 =
Julia Reynolds27c0a962018-12-10 12:37:28 -0500826 new NotificationChannel("id1", "name", IMPORTANCE_DEFAULT);
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500827 final NotificationChannel channel2 =
Julia Reynolds27c0a962018-12-10 12:37:28 -0500828 new NotificationChannel("id2", "name", IMPORTANCE_DEFAULT);
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400829 mBinderService.createNotificationChannels(PKG,
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500830 new ParceledListSlice(Arrays.asList(channel1, channel2)));
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -0400831 assertTrue(mBinderService.getNotificationChannel(
832 PKG, mContext.getUserId(), PKG, "id1") != null);
833 assertTrue(mBinderService.getNotificationChannel(
834 PKG, mContext.getUserId(), PKG, "id2") != null);
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500835 }
836
Geoffrey Pitsch16594462017-01-26 14:42:30 -0500837 @Test
Geoffrey Pitsch76a3aa02017-07-26 15:07:34 -0400838 public void testCreateNotificationChannels_SecondCreateDoesNotChangeImportance()
839 throws Exception {
840 final NotificationChannel channel =
Julia Reynolds27c0a962018-12-10 12:37:28 -0500841 new NotificationChannel("id", "name", IMPORTANCE_DEFAULT);
Geoffrey Pitsch76a3aa02017-07-26 15:07:34 -0400842 mBinderService.createNotificationChannels(PKG,
843 new ParceledListSlice(Arrays.asList(channel)));
844
845 // Recreating the channel doesn't throw, but ignores importance.
846 final NotificationChannel dupeChannel =
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400847 new NotificationChannel("id", "name", IMPORTANCE_HIGH);
Geoffrey Pitsch76a3aa02017-07-26 15:07:34 -0400848 mBinderService.createNotificationChannels(PKG,
849 new ParceledListSlice(Arrays.asList(dupeChannel)));
850 final NotificationChannel createdChannel =
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -0400851 mBinderService.getNotificationChannel(PKG, mContext.getUserId(), PKG, "id");
Julia Reynolds27c0a962018-12-10 12:37:28 -0500852 assertEquals(IMPORTANCE_DEFAULT, createdChannel.getImportance());
Geoffrey Pitsch76a3aa02017-07-26 15:07:34 -0400853 }
854
855 @Test
856 public void testCreateNotificationChannels_SecondCreateAllowedToDowngradeImportance()
857 throws Exception {
858 final NotificationChannel channel =
Julia Reynolds27c0a962018-12-10 12:37:28 -0500859 new NotificationChannel("id", "name", IMPORTANCE_DEFAULT);
Geoffrey Pitsch76a3aa02017-07-26 15:07:34 -0400860 mBinderService.createNotificationChannels(PKG,
861 new ParceledListSlice(Arrays.asList(channel)));
862
863 // Recreating with a lower importance is allowed to modify the channel.
864 final NotificationChannel dupeChannel =
865 new NotificationChannel("id", "name", NotificationManager.IMPORTANCE_LOW);
866 mBinderService.createNotificationChannels(PKG,
867 new ParceledListSlice(Arrays.asList(dupeChannel)));
868 final NotificationChannel createdChannel =
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -0400869 mBinderService.getNotificationChannel(PKG, mContext.getUserId(), PKG, "id");
Geoffrey Pitsch76a3aa02017-07-26 15:07:34 -0400870 assertEquals(NotificationManager.IMPORTANCE_LOW, createdChannel.getImportance());
871 }
872
873 @Test
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400874 public void testCreateNotificationChannels_CannotDowngradeImportanceIfAlreadyUpdated()
875 throws Exception {
876 final NotificationChannel channel =
Julia Reynolds27c0a962018-12-10 12:37:28 -0500877 new NotificationChannel("id", "name", IMPORTANCE_DEFAULT);
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400878 mBinderService.createNotificationChannels(PKG,
879 new ParceledListSlice(Arrays.asList(channel)));
880
881 // The user modifies importance directly, can no longer be changed by the app.
882 final NotificationChannel updatedChannel =
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400883 new NotificationChannel("id", "name", IMPORTANCE_HIGH);
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400884 mBinderService.updateNotificationChannelForPackage(PKG, mUid, updatedChannel);
885
886 // Recreating with a lower importance leaves channel unchanged.
887 final NotificationChannel dupeChannel =
888 new NotificationChannel("id", "name", NotificationManager.IMPORTANCE_LOW);
889 mBinderService.createNotificationChannels(PKG,
890 new ParceledListSlice(Arrays.asList(dupeChannel)));
891 final NotificationChannel createdChannel =
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -0400892 mBinderService.getNotificationChannel(PKG, mContext.getUserId(), PKG, "id");
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400893 assertEquals(IMPORTANCE_HIGH, createdChannel.getImportance());
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400894 }
895
896 @Test
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500897 public void testCreateNotificationChannels_IdenticalChannelsInListIgnoresSecond()
898 throws Exception {
899 final NotificationChannel channel1 =
Julia Reynolds27c0a962018-12-10 12:37:28 -0500900 new NotificationChannel("id", "name", IMPORTANCE_DEFAULT);
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500901 final NotificationChannel channel2 =
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400902 new NotificationChannel("id", "name", IMPORTANCE_HIGH);
Geoffrey Pitsch07532c32017-07-18 11:44:06 -0400903 mBinderService.createNotificationChannels(PKG,
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500904 new ParceledListSlice(Arrays.asList(channel1, channel2)));
905 final NotificationChannel createdChannel =
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -0400906 mBinderService.getNotificationChannel(PKG, mContext.getUserId(), PKG, "id");
Julia Reynolds27c0a962018-12-10 12:37:28 -0500907 assertEquals(IMPORTANCE_DEFAULT, createdChannel.getImportance());
Geoffrey Pitsch03533712017-01-05 10:30:07 -0500908 }
909
Geoffrey Pitsch16594462017-01-26 14:42:30 -0500910 @Test
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500911 public void testBlockedNotifications_suspended() throws Exception {
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500912 when(mPackageManager.isPackageSuspendedForUser(anyString(), anyInt())).thenReturn(true);
913
914 NotificationChannel channel = new NotificationChannel("id", "name",
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400915 IMPORTANCE_HIGH);
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500916 NotificationRecord r = generateNotificationRecord(channel);
Beverly3c707b42018-09-14 09:49:07 -0400917
918 // isBlocked is only used for user blocking, not app suspension
919 assertFalse(mService.isBlocked(r, mUsageStats));
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500920 }
921
Geoffrey Pitsch16594462017-01-26 14:42:30 -0500922 @Test
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500923 public void testBlockedNotifications_blockedChannel() throws Exception {
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500924 when(mPackageManager.isPackageSuspendedForUser(anyString(), anyInt())).thenReturn(false);
925
926 NotificationChannel channel = new NotificationChannel("id", "name",
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400927 NotificationManager.IMPORTANCE_NONE);
Julia Reynoldsbaff4002016-12-15 11:34:26 -0500928 NotificationRecord r = generateNotificationRecord(channel);
Julia Reynolds503ed942017-10-04 16:04:56 -0400929 assertTrue(mService.isBlocked(r, mUsageStats));
Geoffrey Pitschd5bcf212017-06-01 15:45:35 -0400930 verify(mUsageStats, times(1)).registerBlocked(eq(r));
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400931
932 mBinderService.createNotificationChannels(
933 PKG, new ParceledListSlice(Arrays.asList(channel)));
Julia Reynolds24edc002020-01-29 16:35:32 -0500934 final StatusBarNotification sbn = generateNotificationRecord(channel).getSbn();
Julia Reynoldsb6c83742019-07-30 18:03:40 -0400935 mBinderService.enqueueNotificationWithTag(PKG, PKG,
936 "testBlockedNotifications_blockedChannel",
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400937 sbn.getId(), sbn.getNotification(), sbn.getUserId());
938 waitForIdle();
939 assertEquals(0, mBinderService.getActiveNotifications(sbn.getPackageName()).length);
940 }
941
942 @Test
943 public void testEnqueuedBlockedNotifications_appBlockedChannelForegroundService()
944 throws Exception {
945 when(mPackageManager.isPackageSuspendedForUser(anyString(), anyInt())).thenReturn(false);
946
947 NotificationChannel channel = new NotificationChannel("blocked", "name",
948 NotificationManager.IMPORTANCE_NONE);
949 mBinderService.createNotificationChannels(
950 PKG, new ParceledListSlice(Arrays.asList(channel)));
951
Julia Reynolds24edc002020-01-29 16:35:32 -0500952 final StatusBarNotification sbn = generateNotificationRecord(channel).getSbn();
Julia Reynoldse5c60452018-04-30 14:41:36 -0400953 sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
Julia Reynoldsb6c83742019-07-30 18:03:40 -0400954 mBinderService.enqueueNotificationWithTag(PKG, PKG, sbn.getTag(),
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400955 sbn.getId(), sbn.getNotification(), sbn.getUserId());
956 waitForIdle();
957 assertEquals(1, mBinderService.getActiveNotifications(sbn.getPackageName()).length);
958 assertEquals(IMPORTANCE_LOW,
Julia Reynolds503ed942017-10-04 16:04:56 -0400959 mService.getNotificationRecord(sbn.getKey()).getImportance());
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -0400960 assertEquals(IMPORTANCE_LOW, mBinderService.getNotificationChannel(
961 PKG, mContext.getUserId(), PKG, channel.getId()).getImportance());
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400962 }
963
964 @Test
965 public void testEnqueuedBlockedNotifications_userBlockedChannelForegroundService()
966 throws Exception {
967 when(mPackageManager.isPackageSuspendedForUser(anyString(), anyInt())).thenReturn(false);
968
969 NotificationChannel channel =
970 new NotificationChannel("blockedbyuser", "name", IMPORTANCE_HIGH);
971 mBinderService.createNotificationChannels(
972 PKG, new ParceledListSlice(Arrays.asList(channel)));
973
974 NotificationChannel update =
975 new NotificationChannel("blockedbyuser", "name", IMPORTANCE_NONE);
976 mBinderService.updateNotificationChannelForPackage(PKG, mUid, update);
977 waitForIdle();
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -0400978 assertEquals(IMPORTANCE_NONE, mBinderService.getNotificationChannel(
979 PKG, mContext.getUserId(), PKG, channel.getId()).getImportance());
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400980
Julia Reynolds24edc002020-01-29 16:35:32 -0500981 StatusBarNotification sbn = generateNotificationRecord(channel).getSbn();
Julia Reynoldse5c60452018-04-30 14:41:36 -0400982 sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
Julia Reynoldsb6c83742019-07-30 18:03:40 -0400983 mBinderService.enqueueNotificationWithTag(PKG, PKG, sbn.getTag(),
Julia Reynolds8617e4e2017-09-18 16:52:37 -0400984 sbn.getId(), sbn.getNotification(), sbn.getUserId());
985 waitForIdle();
Dianne Hackborn025d4a52018-04-30 16:23:26 -0700986 // The first time a foreground service notification is shown, we allow the channel
987 // to be updated to allow it to be seen.
988 assertEquals(1, mBinderService.getActiveNotifications(sbn.getPackageName()).length);
989 assertEquals(IMPORTANCE_LOW,
990 mService.getNotificationRecord(sbn.getKey()).getImportance());
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -0400991 assertEquals(IMPORTANCE_LOW, mBinderService.getNotificationChannel(
992 PKG, mContext.getUserId(), PKG, channel.getId()).getImportance());
Julia Reynoldse4a47dd2019-06-07 13:40:59 -0400993 mBinderService.cancelNotificationWithTag(PKG, PKG, "tag", sbn.getId(), sbn.getUserId());
Dianne Hackborn025d4a52018-04-30 16:23:26 -0700994 waitForIdle();
995
996 update = new NotificationChannel("blockedbyuser", "name", IMPORTANCE_NONE);
997 update.setFgServiceShown(true);
998 mBinderService.updateNotificationChannelForPackage(PKG, mUid, update);
999 waitForIdle();
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -04001000 assertEquals(IMPORTANCE_NONE, mBinderService.getNotificationChannel(
1001 PKG, mContext.getUserId(), PKG, channel.getId()).getImportance());
Dianne Hackborn025d4a52018-04-30 16:23:26 -07001002
Julia Reynolds24edc002020-01-29 16:35:32 -05001003 sbn = generateNotificationRecord(channel).getSbn();
Dianne Hackborn025d4a52018-04-30 16:23:26 -07001004 sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001005 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1006 "testEnqueuedBlockedNotifications_userBlockedChannelForegroundService",
Dianne Hackborn025d4a52018-04-30 16:23:26 -07001007 sbn.getId(), sbn.getNotification(), sbn.getUserId());
1008 waitForIdle();
1009 // The second time it is shown, we keep the user's preference.
Julia Reynolds8617e4e2017-09-18 16:52:37 -04001010 assertEquals(0, mBinderService.getActiveNotifications(sbn.getPackageName()).length);
Julia Reynolds503ed942017-10-04 16:04:56 -04001011 assertNull(mService.getNotificationRecord(sbn.getKey()));
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -04001012 assertEquals(IMPORTANCE_NONE, mBinderService.getNotificationChannel(
1013 PKG, mContext.getUserId(), PKG, channel.getId()).getImportance());
Julia Reynoldsbaff4002016-12-15 11:34:26 -05001014 }
1015
Geoffrey Pitsch16594462017-01-26 14:42:30 -05001016 @Test
Julia Reynolds005c8b92017-08-24 10:35:53 -04001017 public void testBlockedNotifications_blockedChannelGroup() throws Exception {
1018 when(mPackageManager.isPackageSuspendedForUser(anyString(), anyInt())).thenReturn(false);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001019 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001020 when(mPreferencesHelper.isGroupBlocked(anyString(), anyInt(), anyString())).
1021 thenReturn(true);
Julia Reynolds005c8b92017-08-24 10:35:53 -04001022
1023 NotificationChannel channel = new NotificationChannel("id", "name",
1024 NotificationManager.IMPORTANCE_HIGH);
1025 channel.setGroup("something");
1026 NotificationRecord r = generateNotificationRecord(channel);
Julia Reynolds503ed942017-10-04 16:04:56 -04001027 assertTrue(mService.isBlocked(r, mUsageStats));
Julia Reynolds005c8b92017-08-24 10:35:53 -04001028 verify(mUsageStats, times(1)).registerBlocked(eq(r));
1029 }
1030
1031 @Test
Julia Reynolds4da79702017-06-01 11:06:10 -04001032 public void testEnqueuedBlockedNotifications_blockedApp() throws Exception {
Julia Reynoldsbaff4002016-12-15 11:34:26 -05001033 when(mPackageManager.isPackageSuspendedForUser(anyString(), anyInt())).thenReturn(false);
1034
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04001035 mBinderService.setNotificationsEnabledForPackage(PKG, mUid, false);
Julia Reynolds4da79702017-06-01 11:06:10 -04001036
Julia Reynolds24edc002020-01-29 16:35:32 -05001037 final StatusBarNotification sbn = generateNotificationRecord(null).getSbn();
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001038 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1039 "testEnqueuedBlockedNotifications_blockedApp",
Julia Reynolds4da79702017-06-01 11:06:10 -04001040 sbn.getId(), sbn.getNotification(), sbn.getUserId());
1041 waitForIdle();
1042 assertEquals(0, mBinderService.getActiveNotifications(sbn.getPackageName()).length);
Julia Reynoldsbaff4002016-12-15 11:34:26 -05001043 }
1044
Geoffrey Pitsch16594462017-01-26 14:42:30 -05001045 @Test
Julia Reynolds8617e4e2017-09-18 16:52:37 -04001046 public void testEnqueuedBlockedNotifications_blockedAppForegroundService() throws Exception {
1047 when(mPackageManager.isPackageSuspendedForUser(anyString(), anyInt())).thenReturn(false);
1048
1049 mBinderService.setNotificationsEnabledForPackage(PKG, mUid, false);
1050
Julia Reynolds24edc002020-01-29 16:35:32 -05001051 final StatusBarNotification sbn = generateNotificationRecord(null).getSbn();
Julia Reynoldse5c60452018-04-30 14:41:36 -04001052 sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001053 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1054 "testEnqueuedBlockedNotifications_blockedAppForegroundService",
Julia Reynolds8617e4e2017-09-18 16:52:37 -04001055 sbn.getId(), sbn.getNotification(), sbn.getUserId());
1056 waitForIdle();
1057 assertEquals(0, mBinderService.getActiveNotifications(sbn.getPackageName()).length);
Julia Reynolds503ed942017-10-04 16:04:56 -04001058 assertNull(mService.getNotificationRecord(sbn.getKey()));
Julia Reynolds8617e4e2017-09-18 16:52:37 -04001059 }
1060
Brad Stenning8c991ea2018-07-31 13:33:01 -07001061 /**
1062 * Confirm the system user on automotive devices can use car categories
1063 */
1064 @Test
1065 public void testEnqueuedRestrictedNotifications_asSystem() throws Exception {
1066 when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE, 0))
1067 .thenReturn(true);
1068 List<String> categories = Arrays.asList(Notification.CATEGORY_CAR_EMERGENCY,
1069 Notification.CATEGORY_CAR_WARNING,
1070 Notification.CATEGORY_CAR_INFORMATION);
1071 int id = 0;
1072 for (String category: categories) {
1073 final StatusBarNotification sbn =
Julia Reynolds24edc002020-01-29 16:35:32 -05001074 generateNotificationRecord(mTestNotificationChannel, ++id, "", false).getSbn();
Brad Stenning8c991ea2018-07-31 13:33:01 -07001075 sbn.getNotification().category = category;
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001076 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1077 "testEnqueuedRestrictedNotifications_asSystem",
Brad Stenning8c991ea2018-07-31 13:33:01 -07001078 sbn.getId(), sbn.getNotification(), sbn.getUserId());
1079 }
1080 waitForIdle();
1081 assertEquals(categories.size(), mBinderService.getActiveNotifications(PKG).length);
1082 }
1083
1084
1085 /**
1086 * Confirm restricted notification categories only apply to automotive.
1087 */
1088 @Test
1089 public void testEnqueuedRestrictedNotifications_notAutomotive() throws Exception {
1090 mService.isSystemUid = false;
1091 when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE, 0))
1092 .thenReturn(false);
1093 List<String> categories = Arrays.asList(Notification.CATEGORY_CAR_EMERGENCY,
1094 Notification.CATEGORY_CAR_WARNING,
1095 Notification.CATEGORY_CAR_INFORMATION);
1096 int id = 0;
1097 for (String category: categories) {
1098 final StatusBarNotification sbn =
Julia Reynolds24edc002020-01-29 16:35:32 -05001099 generateNotificationRecord(mTestNotificationChannel, ++id, "", false).getSbn();
Brad Stenning8c991ea2018-07-31 13:33:01 -07001100 sbn.getNotification().category = category;
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001101 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1102 "testEnqueuedRestrictedNotifications_notAutomotive",
Brad Stenning8c991ea2018-07-31 13:33:01 -07001103 sbn.getId(), sbn.getNotification(), sbn.getUserId());
1104 }
1105 waitForIdle();
1106 assertEquals(categories.size(), mBinderService.getActiveNotifications(PKG).length);
1107 }
1108
1109 /**
1110 * Confirm if a non-system user tries to use the car categories on a automotive device that
1111 * they will get a security exception
1112 */
1113 @Test
1114 public void testEnqueuedRestrictedNotifications_badUser() throws Exception {
1115 mService.isSystemUid = false;
1116 when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE, 0))
1117 .thenReturn(true);
1118 List<String> categories = Arrays.asList(Notification.CATEGORY_CAR_EMERGENCY,
1119 Notification.CATEGORY_CAR_WARNING,
1120 Notification.CATEGORY_CAR_INFORMATION);
1121 for (String category: categories) {
Julia Reynolds24edc002020-01-29 16:35:32 -05001122 final StatusBarNotification sbn = generateNotificationRecord(null).getSbn();
Brad Stenning8c991ea2018-07-31 13:33:01 -07001123 sbn.getNotification().category = category;
1124 try {
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001125 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1126 "testEnqueuedRestrictedNotifications_badUser",
Brad Stenning8c991ea2018-07-31 13:33:01 -07001127 sbn.getId(), sbn.getNotification(), sbn.getUserId());
1128 fail("Calls from non system apps should not allow use of restricted categories");
1129 } catch (SecurityException e) {
1130 // pass
1131 }
1132 }
1133 waitForIdle();
1134 assertEquals(0, mBinderService.getActiveNotifications(PKG).length);
1135 }
1136
Julia Reynolds8617e4e2017-09-18 16:52:37 -04001137 @Test
Julia Reynoldsefcdff42018-08-09 09:42:56 -04001138 public void testBlockedNotifications_blockedByAssistant() throws Exception {
1139 when(mPackageManager.isPackageSuspendedForUser(anyString(), anyInt())).thenReturn(false);
Julia Reynolds27c0a962018-12-10 12:37:28 -05001140 when(mAssistants.isSameUser(any(), anyInt())).thenReturn(true);
Julia Reynoldsefcdff42018-08-09 09:42:56 -04001141
1142 NotificationChannel channel = new NotificationChannel("id", "name",
1143 NotificationManager.IMPORTANCE_HIGH);
1144 NotificationRecord r = generateNotificationRecord(channel);
1145 mService.addEnqueuedNotification(r);
1146
Julia Reynolds27c0a962018-12-10 12:37:28 -05001147 Bundle bundle = new Bundle();
Julia Reynoldsc7dcdc22019-03-25 10:26:14 -04001148 bundle.putInt(KEY_IMPORTANCE, IMPORTANCE_NONE);
Julia Reynolds27c0a962018-12-10 12:37:28 -05001149 Adjustment adjustment = new Adjustment(
Julia Reynolds24edc002020-01-29 16:35:32 -05001150 r.getSbn().getPackageName(), r.getKey(), bundle, "", r.getUser().getIdentifier());
Julia Reynolds27c0a962018-12-10 12:37:28 -05001151 mBinderService.applyEnqueuedAdjustmentFromAssistant(null, adjustment);
Julia Reynoldsefcdff42018-08-09 09:42:56 -04001152
1153 NotificationManagerService.PostNotificationRunnable runnable =
1154 mService.new PostNotificationRunnable(r.getKey());
1155 runnable.run();
1156 waitForIdle();
1157
1158 verify(mUsageStats, never()).registerPostedByApp(any());
1159 }
1160
1161 @Test
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001162 public void testEnqueueNotificationWithTag_PopulatesGetActiveNotifications() throws Exception {
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001163 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1164 "testEnqueueNotificationWithTag_PopulatesGetActiveNotifications", 0,
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001165 generateNotificationRecord(null).getNotification(), 0);
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001166 waitForIdle();
Julia Reynolds080361e2017-07-13 11:23:12 -04001167 StatusBarNotification[] notifs = mBinderService.getActiveNotifications(PKG);
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001168 assertEquals(1, notifs.length);
Julia Reynolds503ed942017-10-04 16:04:56 -04001169 assertEquals(1, mService.getNotificationRecordCount());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001170 }
1171
Geoffrey Pitsch16594462017-01-26 14:42:30 -05001172 @Test
Will Brockmand3d49332020-02-10 19:43:03 -05001173 public void testEnqueueNotificationWithTag_WritesExpectedLogs() throws Exception {
Will Brockman2b6959e2020-01-22 09:59:50 -05001174 final String tag = "testEnqueueNotificationWithTag_WritesExpectedLog";
1175 mBinderService.enqueueNotificationWithTag(PKG, PKG, tag, 0,
1176 generateNotificationRecord(null).getNotification(), 0);
1177 waitForIdle();
Will Brockman9918db92020-03-06 16:48:39 -05001178 assertEquals(1, mNotificationRecordLogger.numCalls());
Will Brockmand3d49332020-02-10 19:43:03 -05001179
Will Brockman2b6959e2020-01-22 09:59:50 -05001180 NotificationRecordLoggerFake.CallRecord call = mNotificationRecordLogger.get(0);
Will Brockman9918db92020-03-06 16:48:39 -05001181 assertTrue(call.wasLogged);
Will Brockman75c60572020-01-31 10:30:27 -05001182 assertEquals(NotificationRecordLogger.NotificationReportedEvent.NOTIFICATION_POSTED,
1183 call.event);
Will Brockman2b6959e2020-01-22 09:59:50 -05001184 assertNotNull(call.r);
1185 assertNull(call.old);
1186 assertEquals(0, call.position);
1187 assertEquals(0, call.buzzBeepBlink);
Julia Reynolds24edc002020-01-29 16:35:32 -05001188 assertEquals(PKG, call.r.getSbn().getPackageName());
1189 assertEquals(0, call.r.getSbn().getId());
1190 assertEquals(tag, call.r.getSbn().getTag());
Will Brockman4f0f9d22020-02-23 21:18:11 -05001191 assertEquals(1, call.getInstanceId()); // Fake instance IDs are assigned in order
Will Brockman2b6959e2020-01-22 09:59:50 -05001192 }
1193
1194 @Test
1195 public void testEnqueueNotificationWithTag_LogsOnMajorUpdates() throws Exception {
1196 final String tag = "testEnqueueNotificationWithTag_LogsOnMajorUpdates";
1197 Notification original = new Notification.Builder(mContext,
1198 mTestNotificationChannel.getId())
1199 .setSmallIcon(android.R.drawable.sym_def_app_icon).build();
1200 mBinderService.enqueueNotificationWithTag(PKG, PKG, tag, 0, original, 0);
1201 Notification update = new Notification.Builder(mContext,
1202 mTestNotificationChannel.getId())
1203 .setSmallIcon(android.R.drawable.sym_def_app_icon)
1204 .setCategory(Notification.CATEGORY_ALARM).build();
1205 mBinderService.enqueueNotificationWithTag(PKG, PKG, tag, 0, update, 0);
1206 waitForIdle();
Will Brockman9918db92020-03-06 16:48:39 -05001207 assertEquals(2, mNotificationRecordLogger.numCalls());
Will Brockmancfd98302020-01-29 15:57:30 -05001208
Will Brockman9918db92020-03-06 16:48:39 -05001209 assertTrue(mNotificationRecordLogger.get(0).wasLogged);
Will Brockman2b6959e2020-01-22 09:59:50 -05001210 assertEquals(
Will Brockman75c60572020-01-31 10:30:27 -05001211 NotificationRecordLogger.NotificationReportedEvent.NOTIFICATION_POSTED,
Will Brockman9918db92020-03-06 16:48:39 -05001212 mNotificationRecordLogger.event(0));
Will Brockman4f0f9d22020-02-23 21:18:11 -05001213 assertEquals(1, mNotificationRecordLogger.get(0).getInstanceId());
Will Brockmancfd98302020-01-29 15:57:30 -05001214
Will Brockman9918db92020-03-06 16:48:39 -05001215 assertTrue(mNotificationRecordLogger.get(1).wasLogged);
Will Brockman2b6959e2020-01-22 09:59:50 -05001216 assertEquals(
Will Brockman75c60572020-01-31 10:30:27 -05001217 NotificationRecordLogger.NotificationReportedEvent.NOTIFICATION_UPDATED,
Will Brockman9918db92020-03-06 16:48:39 -05001218 mNotificationRecordLogger.event(1));
Will Brockmancfd98302020-01-29 15:57:30 -05001219 // Instance ID doesn't change on update of an active notification
Will Brockman4f0f9d22020-02-23 21:18:11 -05001220 assertEquals(1, mNotificationRecordLogger.get(1).getInstanceId());
Will Brockman2b6959e2020-01-22 09:59:50 -05001221 }
1222
1223 @Test
Will Brockmand3d49332020-02-10 19:43:03 -05001224 public void testEnqueueNotificationWithTag_DoesNotLogOnMinorUpdate() throws Exception {
1225 final String tag = "testEnqueueNotificationWithTag_DoesNotLogOnMinorUpdate";
Will Brockman2b6959e2020-01-22 09:59:50 -05001226 mBinderService.enqueueNotificationWithTag(PKG, PKG, tag, 0,
1227 generateNotificationRecord(null).getNotification(), 0);
1228 mBinderService.enqueueNotificationWithTag(PKG, PKG, tag, 0,
1229 generateNotificationRecord(null).getNotification(), 0);
1230 waitForIdle();
Will Brockman9918db92020-03-06 16:48:39 -05001231 assertEquals(2, mNotificationRecordLogger.numCalls());
1232 assertTrue(mNotificationRecordLogger.get(0).wasLogged);
Will Brockmand3d49332020-02-10 19:43:03 -05001233 assertEquals(
1234 NotificationRecordLogger.NotificationReportedEvent.NOTIFICATION_POSTED,
Will Brockman9918db92020-03-06 16:48:39 -05001235 mNotificationRecordLogger.event(0));
1236 assertFalse(mNotificationRecordLogger.get(1).wasLogged);
1237 assertNull(mNotificationRecordLogger.event(1));
Will Brockmand3d49332020-02-10 19:43:03 -05001238 }
1239
1240 @Test
1241 public void testEnqueueNotificationWithTag_DoesNotLogOnTitleUpdate() throws Exception {
1242 final String tag = "testEnqueueNotificationWithTag_DoesNotLogOnTitleUpdate";
1243 mBinderService.enqueueNotificationWithTag(PKG, PKG, tag, 0,
1244 generateNotificationRecord(null).getNotification(),
1245 0);
1246 final Notification notif = generateNotificationRecord(null).getNotification();
1247 notif.extras.putString(Notification.EXTRA_TITLE, "Changed title");
1248 mBinderService.enqueueNotificationWithTag(PKG, PKG, tag, 0, notif, 0);
1249 waitForIdle();
Will Brockman9918db92020-03-06 16:48:39 -05001250 assertEquals(2, mNotificationRecordLogger.numCalls());
Will Brockmand3d49332020-02-10 19:43:03 -05001251 assertEquals(
1252 NotificationRecordLogger.NotificationReportedEvent.NOTIFICATION_POSTED,
Will Brockman9918db92020-03-06 16:48:39 -05001253 mNotificationRecordLogger.event(0));
1254 assertNull(mNotificationRecordLogger.event(1));
Will Brockman2b6959e2020-01-22 09:59:50 -05001255 }
1256
1257 @Test
Will Brockmancfd98302020-01-29 15:57:30 -05001258 public void testEnqueueNotificationWithTag_LogsAgainAfterCancel() throws Exception {
1259 final String tag = "testEnqueueNotificationWithTag_LogsAgainAfterCancel";
1260 Notification notification = new Notification.Builder(mContext,
1261 mTestNotificationChannel.getId())
1262 .setSmallIcon(android.R.drawable.sym_def_app_icon).build();
1263 mBinderService.enqueueNotificationWithTag(PKG, PKG, tag, 0, notification, 0);
1264 waitForIdle();
1265 mBinderService.cancelNotificationWithTag(PKG, PKG, tag, 0, 0);
1266 waitForIdle();
1267 mBinderService.enqueueNotificationWithTag(PKG, PKG, tag, 0, notification, 0);
1268 waitForIdle();
Will Brockman9918db92020-03-06 16:48:39 -05001269 assertEquals(3, mNotificationRecordLogger.numCalls());
Will Brockmancfd98302020-01-29 15:57:30 -05001270
Will Brockmancfd98302020-01-29 15:57:30 -05001271 assertEquals(
Will Brockman75c60572020-01-31 10:30:27 -05001272 NotificationRecordLogger.NotificationReportedEvent.NOTIFICATION_POSTED,
Will Brockman9918db92020-03-06 16:48:39 -05001273 mNotificationRecordLogger.event(0));
1274 assertTrue(mNotificationRecordLogger.get(0).wasLogged);
Will Brockman4f0f9d22020-02-23 21:18:11 -05001275 assertEquals(1, mNotificationRecordLogger.get(0).getInstanceId());
Will Brockmancfd98302020-01-29 15:57:30 -05001276
Will Brockmancfd98302020-01-29 15:57:30 -05001277 assertEquals(
Will Brockman75c60572020-01-31 10:30:27 -05001278 NotificationRecordLogger.NotificationCancelledEvent.NOTIFICATION_CANCEL_APP_CANCEL,
Will Brockman9918db92020-03-06 16:48:39 -05001279 mNotificationRecordLogger.event(1));
Will Brockman4f0f9d22020-02-23 21:18:11 -05001280 assertEquals(1, mNotificationRecordLogger.get(1).getInstanceId());
Will Brockman75c60572020-01-31 10:30:27 -05001281
1282 assertEquals(
1283 NotificationRecordLogger.NotificationReportedEvent.NOTIFICATION_POSTED,
Will Brockman9918db92020-03-06 16:48:39 -05001284 mNotificationRecordLogger.event(2));
1285 assertTrue(mNotificationRecordLogger.get(2).wasLogged);
Will Brockmancfd98302020-01-29 15:57:30 -05001286 // New instance ID because notification was canceled before re-post
Will Brockman4f0f9d22020-02-23 21:18:11 -05001287 assertEquals(2, mNotificationRecordLogger.get(2).getInstanceId());
Will Brockman75c60572020-01-31 10:30:27 -05001288 }
1289
1290 @Test
1291 public void testCancelNonexistentNotification() throws Exception {
1292 mBinderService.cancelNotificationWithTag(PKG, PKG,
1293 "testCancelNonexistentNotification", 0, 0);
1294 waitForIdle();
1295 // The notification record logger doesn't even get called when a nonexistent notification
1296 // is cancelled, because that happens very frequently and is not interesting.
Will Brockman9918db92020-03-06 16:48:39 -05001297 assertEquals(0, mNotificationRecordLogger.numCalls());
Will Brockmancfd98302020-01-29 15:57:30 -05001298 }
1299
1300 @Test
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001301 public void testCancelNotificationImmediatelyAfterEnqueue() throws Exception {
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001302 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1303 "testCancelNotificationImmediatelyAfterEnqueue", 0,
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001304 generateNotificationRecord(null).getNotification(), 0);
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001305 mBinderService.cancelNotificationWithTag(PKG, PKG,
1306 "testCancelNotificationImmediatelyAfterEnqueue", 0, 0);
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001307 waitForIdle();
1308 StatusBarNotification[] notifs =
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -05001309 mBinderService.getActiveNotifications(PKG);
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001310 assertEquals(0, notifs.length);
Julia Reynolds503ed942017-10-04 16:04:56 -04001311 assertEquals(0, mService.getNotificationRecordCount());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001312 }
1313
Geoffrey Pitsch16594462017-01-26 14:42:30 -05001314 @Test
Evan Lairdd04af512020-01-09 11:18:09 -05001315 public void testPostCancelPostNotifiesListeners() throws Exception {
1316 // WHEN a notification is posted
1317 final StatusBarNotification sbn = generateNotificationRecord(null).getSbn();
1318 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag", sbn.getId(),
1319 sbn.getNotification(), sbn.getUserId());
1320 // THEN it is canceled
1321 mBinderService.cancelNotificationWithTag(PKG, PKG, "tag", sbn.getId(), sbn.getUserId());
1322 // THEN it is posted again (before the cancel has a chance to finish)
1323 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag", sbn.getId(),
1324 sbn.getNotification(), sbn.getUserId());
1325 // THEN the later enqueue isn't swallowed by the cancel. I.e., ordering is respected
1326 waitForIdle();
1327
1328 // The final enqueue made it to the listener instead of being canceled
1329 StatusBarNotification[] notifs =
1330 mBinderService.getActiveNotifications(PKG);
1331 assertEquals(1, notifs.length);
1332 assertEquals(1, mService.getNotificationRecordCount());
1333 }
1334
1335 @Test
Geoffrey Pitschccc0b972017-02-15 10:52:26 -05001336 public void testCancelNotificationWhilePostedAndEnqueued() throws Exception {
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001337 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1338 "testCancelNotificationWhilePostedAndEnqueued", 0,
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001339 generateNotificationRecord(null).getNotification(), 0);
Geoffrey Pitschccc0b972017-02-15 10:52:26 -05001340 waitForIdle();
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001341 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1342 "testCancelNotificationWhilePostedAndEnqueued", 0,
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001343 generateNotificationRecord(null).getNotification(), 0);
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001344 mBinderService.cancelNotificationWithTag(PKG, PKG,
1345 "testCancelNotificationWhilePostedAndEnqueued", 0, 0);
Geoffrey Pitschccc0b972017-02-15 10:52:26 -05001346 waitForIdle();
1347 StatusBarNotification[] notifs =
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -05001348 mBinderService.getActiveNotifications(PKG);
Geoffrey Pitschccc0b972017-02-15 10:52:26 -05001349 assertEquals(0, notifs.length);
Julia Reynolds503ed942017-10-04 16:04:56 -04001350 assertEquals(0, mService.getNotificationRecordCount());
1351 ArgumentCaptor<NotificationStats> captor = ArgumentCaptor.forClass(NotificationStats.class);
1352 verify(mListeners, times(1)).notifyRemovedLocked(any(), anyInt(), captor.capture());
1353 assertEquals(NotificationStats.DISMISSAL_OTHER, captor.getValue().getDismissalSurface());
Geoffrey Pitschccc0b972017-02-15 10:52:26 -05001354 }
1355
1356 @Test
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001357 public void testCancelNotificationsFromListenerImmediatelyAfterEnqueue() throws Exception {
Julia Reynolds503ed942017-10-04 16:04:56 -04001358 NotificationRecord r = generateNotificationRecord(null);
Julia Reynolds24edc002020-01-29 16:35:32 -05001359 final StatusBarNotification sbn = r.getSbn();
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001360 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1361 "testCancelNotificationsFromListenerImmediatelyAfterEnqueue",
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001362 sbn.getId(), sbn.getNotification(), sbn.getUserId());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001363 mBinderService.cancelNotificationsFromListener(null, null);
1364 waitForIdle();
1365 StatusBarNotification[] notifs =
1366 mBinderService.getActiveNotifications(sbn.getPackageName());
1367 assertEquals(0, notifs.length);
Julia Reynolds503ed942017-10-04 16:04:56 -04001368 assertEquals(0, mService.getNotificationRecordCount());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001369 }
1370
Geoffrey Pitsch16594462017-01-26 14:42:30 -05001371 @Test
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001372 public void testCancelAllNotificationsImmediatelyAfterEnqueue() throws Exception {
Julia Reynolds24edc002020-01-29 16:35:32 -05001373 final StatusBarNotification sbn = generateNotificationRecord(null).getSbn();
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001374 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1375 "testCancelAllNotificationsImmediatelyAfterEnqueue",
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001376 sbn.getId(), sbn.getNotification(), sbn.getUserId());
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -05001377 mBinderService.cancelAllNotifications(PKG, sbn.getUserId());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001378 waitForIdle();
1379 StatusBarNotification[] notifs =
1380 mBinderService.getActiveNotifications(sbn.getPackageName());
1381 assertEquals(0, notifs.length);
Julia Reynolds503ed942017-10-04 16:04:56 -04001382 assertEquals(0, mService.getNotificationRecordCount());
Julia Reynolds080361e2017-07-13 11:23:12 -04001383 }
1384
1385 @Test
Evan Laird3ceaa9b2019-08-05 17:11:54 -04001386 public void testCancelImmediatelyAfterEnqueueNotifiesListeners_ForegroundServiceFlag()
1387 throws Exception {
Julia Reynolds24edc002020-01-29 16:35:32 -05001388 final StatusBarNotification sbn = generateNotificationRecord(null).getSbn();
Evan Laird3ceaa9b2019-08-05 17:11:54 -04001389 sbn.getNotification().flags =
1390 Notification.FLAG_ONGOING_EVENT | FLAG_FOREGROUND_SERVICE;
1391 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
1392 sbn.getId(), sbn.getNotification(), sbn.getUserId());
1393 mBinderService.cancelNotificationWithTag(PKG, PKG, "tag", sbn.getId(), sbn.getUserId());
1394 waitForIdle();
1395 verify(mListeners, times(1)).notifyPostedLocked(any(), any());
1396 verify(mListeners, times(1)).notifyRemovedLocked(any(), anyInt(), any());
1397 }
1398
1399 @Test
Julia Reynolds080361e2017-07-13 11:23:12 -04001400 public void testUserInitiatedClearAll_noLeak() throws Exception {
1401 final NotificationRecord n = generateNotificationRecord(
1402 mTestNotificationChannel, 1, "group", true);
1403
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001404 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1405 "testUserInitiatedClearAll_noLeak",
Julia Reynolds24edc002020-01-29 16:35:32 -05001406 n.getSbn().getId(), n.getSbn().getNotification(), n.getSbn().getUserId());
Julia Reynolds080361e2017-07-13 11:23:12 -04001407 waitForIdle();
1408
Julia Reynolds503ed942017-10-04 16:04:56 -04001409 mService.mNotificationDelegate.onClearAll(mUid, Binder.getCallingPid(),
Julia Reynolds080361e2017-07-13 11:23:12 -04001410 n.getUserId());
1411 waitForIdle();
1412 StatusBarNotification[] notifs =
Julia Reynolds24edc002020-01-29 16:35:32 -05001413 mBinderService.getActiveNotifications(n.getSbn().getPackageName());
Julia Reynolds080361e2017-07-13 11:23:12 -04001414 assertEquals(0, notifs.length);
Julia Reynolds503ed942017-10-04 16:04:56 -04001415 assertEquals(0, mService.getNotificationRecordCount());
1416 ArgumentCaptor<NotificationStats> captor = ArgumentCaptor.forClass(NotificationStats.class);
1417 verify(mListeners, times(1)).notifyRemovedLocked(any(), anyInt(), captor.capture());
1418 assertEquals(NotificationStats.DISMISSAL_OTHER, captor.getValue().getDismissalSurface());
Julia Reynolds080361e2017-07-13 11:23:12 -04001419 }
1420
1421 @Test
1422 public void testCancelAllNotificationsCancelsChildren() throws Exception {
1423 final NotificationRecord parent = generateNotificationRecord(
1424 mTestNotificationChannel, 1, "group1", true);
1425 final NotificationRecord child = generateNotificationRecord(
1426 mTestNotificationChannel, 2, "group1", false);
1427
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001428 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1429 "testCancelAllNotificationsCancelsChildren",
Julia Reynolds24edc002020-01-29 16:35:32 -05001430 parent.getSbn().getId(), parent.getSbn().getNotification(),
1431 parent.getSbn().getUserId());
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001432 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1433 "testCancelAllNotificationsCancelsChildren",
Julia Reynolds24edc002020-01-29 16:35:32 -05001434 child.getSbn().getId(), child.getSbn().getNotification(),
1435 child.getSbn().getUserId());
Julia Reynolds080361e2017-07-13 11:23:12 -04001436 waitForIdle();
1437
Julia Reynolds24edc002020-01-29 16:35:32 -05001438 mBinderService.cancelAllNotifications(PKG, parent.getSbn().getUserId());
Julia Reynolds080361e2017-07-13 11:23:12 -04001439 waitForIdle();
Julia Reynolds503ed942017-10-04 16:04:56 -04001440 assertEquals(0, mService.getNotificationRecordCount());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001441 }
1442
Geoffrey Pitsch16594462017-01-26 14:42:30 -05001443 @Test
Julia Reynolds0839c022017-06-15 15:24:01 -04001444 public void testCancelAllNotificationsMultipleEnqueuedDoesNotCrash() throws Exception {
Julia Reynolds24edc002020-01-29 16:35:32 -05001445 final StatusBarNotification sbn = generateNotificationRecord(null).getSbn();
Julia Reynolds0839c022017-06-15 15:24:01 -04001446 for (int i = 0; i < 10; i++) {
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001447 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1448 "testCancelAllNotificationsMultipleEnqueuedDoesNotCrash",
Julia Reynolds0839c022017-06-15 15:24:01 -04001449 sbn.getId(), sbn.getNotification(), sbn.getUserId());
1450 }
1451 mBinderService.cancelAllNotifications(PKG, sbn.getUserId());
1452 waitForIdle();
Julia Reynolds080361e2017-07-13 11:23:12 -04001453
Julia Reynolds503ed942017-10-04 16:04:56 -04001454 assertEquals(0, mService.getNotificationRecordCount());
Julia Reynolds0839c022017-06-15 15:24:01 -04001455 }
1456
1457 @Test
1458 public void testCancelGroupSummaryMultipleEnqueuedChildrenDoesNotCrash() throws Exception {
1459 final NotificationRecord parent = generateNotificationRecord(
1460 mTestNotificationChannel, 1, "group1", true);
1461 final NotificationRecord parentAsChild = generateNotificationRecord(
1462 mTestNotificationChannel, 1, "group1", false);
1463 final NotificationRecord child = generateNotificationRecord(
1464 mTestNotificationChannel, 2, "group1", false);
1465
1466 // fully post parent notification
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001467 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1468 "testCancelGroupSummaryMultipleEnqueuedChildrenDoesNotCrash",
Julia Reynolds24edc002020-01-29 16:35:32 -05001469 parent.getSbn().getId(), parent.getSbn().getNotification(),
1470 parent.getSbn().getUserId());
Julia Reynolds0839c022017-06-15 15:24:01 -04001471 waitForIdle();
1472
1473 // enqueue the child several times
1474 for (int i = 0; i < 10; i++) {
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001475 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1476 "testCancelGroupSummaryMultipleEnqueuedChildrenDoesNotCrash",
Julia Reynolds24edc002020-01-29 16:35:32 -05001477 child.getSbn().getId(), child.getSbn().getNotification(),
1478 child.getSbn().getUserId());
Julia Reynolds0839c022017-06-15 15:24:01 -04001479 }
1480 // make the parent a child, which will cancel the child notification
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001481 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1482 "testCancelGroupSummaryMultipleEnqueuedChildrenDoesNotCrash",
Julia Reynolds24edc002020-01-29 16:35:32 -05001483 parentAsChild.getSbn().getId(), parentAsChild.getSbn().getNotification(),
1484 parentAsChild.getSbn().getUserId());
Julia Reynolds0839c022017-06-15 15:24:01 -04001485 waitForIdle();
Julia Reynolds080361e2017-07-13 11:23:12 -04001486
Julia Reynolds503ed942017-10-04 16:04:56 -04001487 assertEquals(0, mService.getNotificationRecordCount());
Julia Reynolds0839c022017-06-15 15:24:01 -04001488 }
1489
1490 @Test
Jay Aliomerefe1c922019-09-19 16:42:16 -04001491 public void testAutobundledSummary_notificationAdded() {
1492 NotificationRecord summary =
1493 generateNotificationRecord(mTestNotificationChannel, 0, "pkg", true);
1494 summary.getNotification().flags |= Notification.FLAG_AUTOGROUP_SUMMARY;
1495 mService.addNotification(summary);
1496 mService.mSummaryByGroupKey.put("pkg", summary);
1497 mService.mAutobundledSummaries.put(0, new ArrayMap<>());
1498 mService.mAutobundledSummaries.get(0).put("pkg", summary.getKey());
Mady Mellor6d775f82019-11-12 16:12:19 -08001499 mService.updateAutobundledSummaryFlags(0, "pkg", true, false);
Jay Aliomerefe1c922019-09-19 16:42:16 -04001500
Julia Reynolds24edc002020-01-29 16:35:32 -05001501 assertTrue(summary.getSbn().isOngoing());
Jay Aliomerefe1c922019-09-19 16:42:16 -04001502 }
1503
1504 @Test
1505 public void testAutobundledSummary_notificationRemoved() {
1506 NotificationRecord summary =
1507 generateNotificationRecord(mTestNotificationChannel, 0, "pkg", true);
1508 summary.getNotification().flags |= Notification.FLAG_AUTOGROUP_SUMMARY;
1509 summary.getNotification().flags |= Notification.FLAG_ONGOING_EVENT;
1510 mService.addNotification(summary);
1511 mService.mAutobundledSummaries.put(0, new ArrayMap<>());
1512 mService.mAutobundledSummaries.get(0).put("pkg", summary.getKey());
1513 mService.mSummaryByGroupKey.put("pkg", summary);
1514
Mady Mellor6d775f82019-11-12 16:12:19 -08001515 mService.updateAutobundledSummaryFlags(0, "pkg", false, false);
Jay Aliomerefe1c922019-09-19 16:42:16 -04001516
Julia Reynolds24edc002020-01-29 16:35:32 -05001517 assertFalse(summary.getSbn().isOngoing());
Jay Aliomerefe1c922019-09-19 16:42:16 -04001518 }
1519
1520 @Test
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001521 public void testCancelAllNotifications_IgnoreForegroundService() throws Exception {
Julia Reynolds24edc002020-01-29 16:35:32 -05001522 final StatusBarNotification sbn = generateNotificationRecord(null).getSbn();
Julia Reynoldse5c60452018-04-30 14:41:36 -04001523 sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001524 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1525 "testCancelAllNotifications_IgnoreForegroundService",
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001526 sbn.getId(), sbn.getNotification(), sbn.getUserId());
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -05001527 mBinderService.cancelAllNotifications(PKG, sbn.getUserId());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001528 waitForIdle();
1529 StatusBarNotification[] notifs =
1530 mBinderService.getActiveNotifications(sbn.getPackageName());
1531 assertEquals(1, notifs.length);
Julia Reynolds503ed942017-10-04 16:04:56 -04001532 assertEquals(1, mService.getNotificationRecordCount());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001533 }
1534
Geoffrey Pitsch16594462017-01-26 14:42:30 -05001535 @Test
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001536 public void testCancelAllNotifications_IgnoreOtherPackages() throws Exception {
Julia Reynolds24edc002020-01-29 16:35:32 -05001537 final StatusBarNotification sbn = generateNotificationRecord(null).getSbn();
Julia Reynoldse5c60452018-04-30 14:41:36 -04001538 sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001539 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1540 "testCancelAllNotifications_IgnoreOtherPackages",
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001541 sbn.getId(), sbn.getNotification(), sbn.getUserId());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001542 mBinderService.cancelAllNotifications("other_pkg_name", sbn.getUserId());
1543 waitForIdle();
1544 StatusBarNotification[] notifs =
1545 mBinderService.getActiveNotifications(sbn.getPackageName());
1546 assertEquals(1, notifs.length);
Julia Reynolds503ed942017-10-04 16:04:56 -04001547 assertEquals(1, mService.getNotificationRecordCount());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001548 }
1549
Geoffrey Pitsch16594462017-01-26 14:42:30 -05001550 @Test
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001551 public void testCancelAllNotifications_NullPkgRemovesAll() throws Exception {
Julia Reynolds24edc002020-01-29 16:35:32 -05001552 final StatusBarNotification sbn = generateNotificationRecord(null).getSbn();
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001553 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1554 "testCancelAllNotifications_NullPkgRemovesAll",
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001555 sbn.getId(), sbn.getNotification(), sbn.getUserId());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001556 mBinderService.cancelAllNotifications(null, sbn.getUserId());
1557 waitForIdle();
1558 StatusBarNotification[] notifs =
1559 mBinderService.getActiveNotifications(sbn.getPackageName());
1560 assertEquals(0, notifs.length);
Julia Reynolds503ed942017-10-04 16:04:56 -04001561 assertEquals(0, mService.getNotificationRecordCount());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001562 }
1563
Geoffrey Pitsch16594462017-01-26 14:42:30 -05001564 @Test
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001565 public void testCancelAllNotifications_NullPkgIgnoresUserAllNotifications() throws Exception {
Julia Reynolds24edc002020-01-29 16:35:32 -05001566 final StatusBarNotification sbn = generateNotificationRecord(null).getSbn();
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001567 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1568 "testCancelAllNotifications_NullPkgIgnoresUserAllNotifications",
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001569 sbn.getId(), sbn.getNotification(), UserHandle.USER_ALL);
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001570 // Null pkg is how we signal a user switch.
1571 mBinderService.cancelAllNotifications(null, sbn.getUserId());
1572 waitForIdle();
1573 StatusBarNotification[] notifs =
1574 mBinderService.getActiveNotifications(sbn.getPackageName());
1575 assertEquals(1, notifs.length);
Julia Reynolds503ed942017-10-04 16:04:56 -04001576 assertEquals(1, mService.getNotificationRecordCount());
Geoffrey Pitsch331a64d2017-01-17 14:00:47 -05001577 }
Julia Reynolds5f20e9f2017-01-30 08:54:53 -05001578
1579 @Test
Beverly40239d92017-07-07 10:20:41 -04001580 public void testAppInitiatedCancelAllNotifications_CancelsNoClearFlag() throws Exception {
Julia Reynolds24edc002020-01-29 16:35:32 -05001581 final StatusBarNotification sbn = generateNotificationRecord(null).getSbn();
Beverly40239d92017-07-07 10:20:41 -04001582 sbn.getNotification().flags |= Notification.FLAG_NO_CLEAR;
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001583 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1584 "testAppInitiatedCancelAllNotifications_CancelsNoClearFlag",
Beverly40239d92017-07-07 10:20:41 -04001585 sbn.getId(), sbn.getNotification(), sbn.getUserId());
1586 mBinderService.cancelAllNotifications(PKG, sbn.getUserId());
1587 waitForIdle();
1588 StatusBarNotification[] notifs =
1589 mBinderService.getActiveNotifications(sbn.getPackageName());
1590 assertEquals(0, notifs.length);
1591 }
1592
1593 @Test
1594 public void testCancelAllNotifications_CancelsNoClearFlag() throws Exception {
1595 final NotificationRecord notif = generateNotificationRecord(
1596 mTestNotificationChannel, 1, "group", true);
1597 notif.getNotification().flags |= Notification.FLAG_NO_CLEAR;
Julia Reynolds503ed942017-10-04 16:04:56 -04001598 mService.addNotification(notif);
1599 mService.cancelAllNotificationsInt(mUid, 0, PKG, null, 0, 0, true,
Beverly40239d92017-07-07 10:20:41 -04001600 notif.getUserId(), 0, null);
1601 waitForIdle();
1602 StatusBarNotification[] notifs =
Julia Reynolds24edc002020-01-29 16:35:32 -05001603 mBinderService.getActiveNotifications(notif.getSbn().getPackageName());
Beverly40239d92017-07-07 10:20:41 -04001604 assertEquals(0, notifs.length);
1605 }
1606
1607 @Test
1608 public void testUserInitiatedCancelAllOnClearAll_NoClearFlag() throws Exception {
1609 final NotificationRecord notif = generateNotificationRecord(
1610 mTestNotificationChannel, 1, "group", true);
1611 notif.getNotification().flags |= Notification.FLAG_NO_CLEAR;
Julia Reynolds503ed942017-10-04 16:04:56 -04001612 mService.addNotification(notif);
Beverly40239d92017-07-07 10:20:41 -04001613
Julia Reynolds503ed942017-10-04 16:04:56 -04001614 mService.mNotificationDelegate.onClearAll(mUid, Binder.getCallingPid(),
Beverly40239d92017-07-07 10:20:41 -04001615 notif.getUserId());
1616 waitForIdle();
1617 StatusBarNotification[] notifs =
Julia Reynolds24edc002020-01-29 16:35:32 -05001618 mBinderService.getActiveNotifications(notif.getSbn().getPackageName());
Beverly40239d92017-07-07 10:20:41 -04001619 assertEquals(1, notifs.length);
1620 }
1621
1622 @Test
1623 public void testCancelAllCancelNotificationsFromListener_NoClearFlag() throws Exception {
1624 final NotificationRecord parent = generateNotificationRecord(
1625 mTestNotificationChannel, 1, "group", true);
1626 final NotificationRecord child = generateNotificationRecord(
1627 mTestNotificationChannel, 2, "group", false);
1628 final NotificationRecord child2 = generateNotificationRecord(
1629 mTestNotificationChannel, 3, "group", false);
1630 child2.getNotification().flags |= Notification.FLAG_NO_CLEAR;
1631 final NotificationRecord newGroup = generateNotificationRecord(
1632 mTestNotificationChannel, 4, "group2", false);
Julia Reynolds503ed942017-10-04 16:04:56 -04001633 mService.addNotification(parent);
1634 mService.addNotification(child);
1635 mService.addNotification(child2);
1636 mService.addNotification(newGroup);
1637 mService.getBinderService().cancelNotificationsFromListener(null, null);
Beverly40239d92017-07-07 10:20:41 -04001638 waitForIdle();
1639 StatusBarNotification[] notifs =
Julia Reynolds24edc002020-01-29 16:35:32 -05001640 mBinderService.getActiveNotifications(parent.getSbn().getPackageName());
Beverly40239d92017-07-07 10:20:41 -04001641 assertEquals(1, notifs.length);
1642 }
1643
1644 @Test
1645 public void testUserInitiatedCancelAllWithGroup_NoClearFlag() throws Exception {
1646 final NotificationRecord parent = generateNotificationRecord(
1647 mTestNotificationChannel, 1, "group", true);
1648 final NotificationRecord child = generateNotificationRecord(
1649 mTestNotificationChannel, 2, "group", false);
1650 final NotificationRecord child2 = generateNotificationRecord(
1651 mTestNotificationChannel, 3, "group", false);
1652 child2.getNotification().flags |= Notification.FLAG_NO_CLEAR;
1653 final NotificationRecord newGroup = generateNotificationRecord(
1654 mTestNotificationChannel, 4, "group2", false);
Julia Reynolds503ed942017-10-04 16:04:56 -04001655 mService.addNotification(parent);
1656 mService.addNotification(child);
1657 mService.addNotification(child2);
1658 mService.addNotification(newGroup);
1659 mService.mNotificationDelegate.onClearAll(mUid, Binder.getCallingPid(),
Beverly40239d92017-07-07 10:20:41 -04001660 parent.getUserId());
1661 waitForIdle();
1662 StatusBarNotification[] notifs =
Julia Reynolds24edc002020-01-29 16:35:32 -05001663 mBinderService.getActiveNotifications(parent.getSbn().getPackageName());
Beverly40239d92017-07-07 10:20:41 -04001664 assertEquals(1, notifs.length);
1665 }
1666
1667 @Test
Geoffrey Pitsch415e4542017-04-10 13:12:58 -04001668 public void testRemoveForegroundServiceFlag_ImmediatelyAfterEnqueue() throws Exception {
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001669 Notification n =
1670 new Notification.Builder(mContext, mTestNotificationChannel.getId())
1671 .setSmallIcon(android.R.drawable.sym_def_app_icon)
1672 .build();
1673 StatusBarNotification sbn = new StatusBarNotification("a", "a", 0, null, mUid, 0,
1674 n, new UserHandle(mUid), null, 0);
Julia Reynoldse5c60452018-04-30 14:41:36 -04001675 sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04001676 mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001677 sbn.getId(), sbn.getNotification(), sbn.getUserId());
Geoffrey Pitsch415e4542017-04-10 13:12:58 -04001678 mInternalService.removeForegroundServiceFlagFromNotification(PKG, sbn.getId(),
1679 sbn.getUserId());
1680 waitForIdle();
1681 StatusBarNotification[] notifs =
1682 mBinderService.getActiveNotifications(sbn.getPackageName());
Julia Reynoldse5c60452018-04-30 14:41:36 -04001683 assertEquals(0, notifs[0].getNotification().flags & FLAG_FOREGROUND_SERVICE);
Geoffrey Pitsch415e4542017-04-10 13:12:58 -04001684 }
1685
1686 @Test
Geoffrey Pitsch27684152017-05-02 11:41:31 -04001687 public void testCancelAfterSecondEnqueueDoesNotSpecifyForegroundFlag() throws Exception {
Julia Reynolds24edc002020-01-29 16:35:32 -05001688 final StatusBarNotification sbn = generateNotificationRecord(null).getSbn();
Geoffrey Pitsch27684152017-05-02 11:41:31 -04001689 sbn.getNotification().flags =
Julia Reynoldse5c60452018-04-30 14:41:36 -04001690 Notification.FLAG_ONGOING_EVENT | FLAG_FOREGROUND_SERVICE;
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001691 mBinderService.enqueueNotificationWithTag(PKG, PKG, sbn.getTag(),
Geoffrey Pitsch27684152017-05-02 11:41:31 -04001692 sbn.getId(), sbn.getNotification(), sbn.getUserId());
1693 sbn.getNotification().flags = Notification.FLAG_ONGOING_EVENT;
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001694 mBinderService.enqueueNotificationWithTag(PKG, PKG, sbn.getTag(),
Geoffrey Pitsch27684152017-05-02 11:41:31 -04001695 sbn.getId(), sbn.getNotification(), sbn.getUserId());
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001696 mBinderService.cancelNotificationWithTag(PKG, PKG, sbn.getTag(), sbn.getId(),
1697 sbn.getUserId());
Geoffrey Pitsch27684152017-05-02 11:41:31 -04001698 waitForIdle();
1699 assertEquals(0, mBinderService.getActiveNotifications(sbn.getPackageName()).length);
Julia Reynolds503ed942017-10-04 16:04:56 -04001700 assertEquals(0, mService.getNotificationRecordCount());
Geoffrey Pitsch27684152017-05-02 11:41:31 -04001701 }
1702
1703 @Test
Julia Reynolds40f00d72017-12-12 10:47:32 -05001704 public void testCancelAllCancelNotificationsFromListener_ForegroundServiceFlag()
1705 throws Exception {
1706 final NotificationRecord parent = generateNotificationRecord(
1707 mTestNotificationChannel, 1, "group", true);
1708 final NotificationRecord child = generateNotificationRecord(
1709 mTestNotificationChannel, 2, "group", false);
1710 final NotificationRecord child2 = generateNotificationRecord(
1711 mTestNotificationChannel, 3, "group", false);
Julia Reynoldse5c60452018-04-30 14:41:36 -04001712 child2.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
Julia Reynolds40f00d72017-12-12 10:47:32 -05001713 final NotificationRecord newGroup = generateNotificationRecord(
1714 mTestNotificationChannel, 4, "group2", false);
1715 mService.addNotification(parent);
1716 mService.addNotification(child);
1717 mService.addNotification(child2);
1718 mService.addNotification(newGroup);
1719 mService.getBinderService().cancelNotificationsFromListener(null, null);
1720 waitForIdle();
1721 StatusBarNotification[] notifs =
Julia Reynolds24edc002020-01-29 16:35:32 -05001722 mBinderService.getActiveNotifications(parent.getSbn().getPackageName());
Julia Reynolds40f00d72017-12-12 10:47:32 -05001723 assertEquals(0, notifs.length);
1724 }
1725
1726 @Test
1727 public void testCancelAllCancelNotificationsFromListener_ForegroundServiceFlagWithParameter()
1728 throws Exception {
1729 final NotificationRecord parent = generateNotificationRecord(
1730 mTestNotificationChannel, 1, "group", true);
1731 final NotificationRecord child = generateNotificationRecord(
1732 mTestNotificationChannel, 2, "group", false);
1733 final NotificationRecord child2 = generateNotificationRecord(
1734 mTestNotificationChannel, 3, "group", false);
Julia Reynoldse5c60452018-04-30 14:41:36 -04001735 child2.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
Julia Reynolds40f00d72017-12-12 10:47:32 -05001736 final NotificationRecord newGroup = generateNotificationRecord(
1737 mTestNotificationChannel, 4, "group2", false);
1738 mService.addNotification(parent);
1739 mService.addNotification(child);
1740 mService.addNotification(child2);
1741 mService.addNotification(newGroup);
Julia Reynolds24edc002020-01-29 16:35:32 -05001742 String[] keys = {parent.getSbn().getKey(), child.getSbn().getKey(),
1743 child2.getSbn().getKey(), newGroup.getSbn().getKey()};
Julia Reynolds40f00d72017-12-12 10:47:32 -05001744 mService.getBinderService().cancelNotificationsFromListener(null, keys);
1745 waitForIdle();
1746 StatusBarNotification[] notifs =
Julia Reynolds24edc002020-01-29 16:35:32 -05001747 mBinderService.getActiveNotifications(parent.getSbn().getPackageName());
Julia Reynolds40f00d72017-12-12 10:47:32 -05001748 assertEquals(1, notifs.length);
1749 }
1750
1751 @Test
1752 public void testUserInitiatedCancelAllWithGroup_ForegroundServiceFlag() throws Exception {
1753 final NotificationRecord parent = generateNotificationRecord(
1754 mTestNotificationChannel, 1, "group", true);
1755 final NotificationRecord child = generateNotificationRecord(
1756 mTestNotificationChannel, 2, "group", false);
1757 final NotificationRecord child2 = generateNotificationRecord(
1758 mTestNotificationChannel, 3, "group", false);
Julia Reynoldse5c60452018-04-30 14:41:36 -04001759 child2.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
Julia Reynolds40f00d72017-12-12 10:47:32 -05001760 final NotificationRecord newGroup = generateNotificationRecord(
1761 mTestNotificationChannel, 4, "group2", false);
1762 mService.addNotification(parent);
1763 mService.addNotification(child);
1764 mService.addNotification(child2);
1765 mService.addNotification(newGroup);
1766 mService.mNotificationDelegate.onClearAll(mUid, Binder.getCallingPid(),
1767 parent.getUserId());
1768 waitForIdle();
1769 StatusBarNotification[] notifs =
Julia Reynolds24edc002020-01-29 16:35:32 -05001770 mBinderService.getActiveNotifications(parent.getSbn().getPackageName());
Julia Reynolds40f00d72017-12-12 10:47:32 -05001771 assertEquals(0, notifs.length);
1772 }
1773
1774 @Test
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04001775 public void testFindGroupNotificationsLocked() throws Exception {
1776 // make sure the same notification can be found in both lists and returned
1777 final NotificationRecord group1 = generateNotificationRecord(
1778 mTestNotificationChannel, 1, "group1", true);
Julia Reynolds503ed942017-10-04 16:04:56 -04001779 mService.addEnqueuedNotification(group1);
1780 mService.addNotification(group1);
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04001781
1782 // should not be returned
1783 final NotificationRecord group2 = generateNotificationRecord(
1784 mTestNotificationChannel, 2, "group2", true);
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001785 mBinderService.enqueueNotificationWithTag(PKG, PKG, "testFindGroupNotificationsLocked",
Julia Reynolds24edc002020-01-29 16:35:32 -05001786 group2.getSbn().getId(), group2.getSbn().getNotification(),
1787 group2.getSbn().getUserId());
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04001788 waitForIdle();
1789
1790 // should not be returned
1791 final NotificationRecord nonGroup = generateNotificationRecord(
1792 mTestNotificationChannel, 3, null, false);
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001793 mBinderService.enqueueNotificationWithTag(PKG, PKG, "testFindGroupNotificationsLocked",
Julia Reynolds24edc002020-01-29 16:35:32 -05001794 nonGroup.getSbn().getId(), nonGroup.getSbn().getNotification(),
1795 nonGroup.getSbn().getUserId());
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04001796 waitForIdle();
1797
1798 // same group, child, should be returned
1799 final NotificationRecord group1Child = generateNotificationRecord(
1800 mTestNotificationChannel, 4, "group1", false);
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001801 mBinderService.enqueueNotificationWithTag(PKG, PKG, "testFindGroupNotificationsLocked",
Julia Reynolds24edc002020-01-29 16:35:32 -05001802 group1Child.getSbn().getId(),
1803 group1Child.getSbn().getNotification(), group1Child.getSbn().getUserId());
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04001804 waitForIdle();
1805
1806 List<NotificationRecord> inGroup1 =
Julia Reynolds503ed942017-10-04 16:04:56 -04001807 mService.findGroupNotificationsLocked(PKG, group1.getGroupKey(),
Julia Reynolds24edc002020-01-29 16:35:32 -05001808 group1.getSbn().getUserId());
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04001809 assertEquals(3, inGroup1.size());
1810 for (NotificationRecord record : inGroup1) {
1811 assertTrue(record.getGroupKey().equals(group1.getGroupKey()));
Julia Reynolds24edc002020-01-29 16:35:32 -05001812 assertTrue(record.getSbn().getId() == 1 || record.getSbn().getId() == 4);
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04001813 }
1814 }
1815
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04001816 @Test
Julia Reynolds40f00d72017-12-12 10:47:32 -05001817 public void testCancelAllNotifications_CancelsNoClearFlagOnGoing() throws Exception {
1818 final NotificationRecord notif = generateNotificationRecord(
1819 mTestNotificationChannel, 1, "group", true);
1820 notif.getNotification().flags |= Notification.FLAG_NO_CLEAR;
1821 mService.addNotification(notif);
1822 mService.cancelAllNotificationsInt(mUid, 0, PKG, null, 0,
1823 Notification.FLAG_ONGOING_EVENT, true, notif.getUserId(), 0, null);
1824 waitForIdle();
1825 StatusBarNotification[] notifs =
Julia Reynolds24edc002020-01-29 16:35:32 -05001826 mBinderService.getActiveNotifications(notif.getSbn().getPackageName());
Julia Reynolds40f00d72017-12-12 10:47:32 -05001827 assertEquals(0, notifs.length);
1828 }
1829
1830 @Test
1831 public void testCancelAllCancelNotificationsFromListener_NoClearFlagWithParameter()
1832 throws Exception {
1833 final NotificationRecord parent = generateNotificationRecord(
1834 mTestNotificationChannel, 1, "group", true);
1835 final NotificationRecord child = generateNotificationRecord(
1836 mTestNotificationChannel, 2, "group", false);
1837 final NotificationRecord child2 = generateNotificationRecord(
1838 mTestNotificationChannel, 3, "group", false);
1839 child2.getNotification().flags |= Notification.FLAG_NO_CLEAR;
1840 final NotificationRecord newGroup = generateNotificationRecord(
1841 mTestNotificationChannel, 4, "group2", false);
1842 mService.addNotification(parent);
1843 mService.addNotification(child);
1844 mService.addNotification(child2);
1845 mService.addNotification(newGroup);
Julia Reynolds24edc002020-01-29 16:35:32 -05001846 String[] keys = {parent.getSbn().getKey(), child.getSbn().getKey(),
1847 child2.getSbn().getKey(), newGroup.getSbn().getKey()};
Julia Reynolds40f00d72017-12-12 10:47:32 -05001848 mService.getBinderService().cancelNotificationsFromListener(null, keys);
1849 waitForIdle();
1850 StatusBarNotification[] notifs =
Julia Reynolds24edc002020-01-29 16:35:32 -05001851 mBinderService.getActiveNotifications(parent.getSbn().getPackageName());
Julia Reynolds40f00d72017-12-12 10:47:32 -05001852 assertEquals(0, notifs.length);
1853 }
1854
1855 @Test
1856 public void testAppInitiatedCancelAllNotifications_CancelsOnGoingFlag() throws Exception {
Julia Reynolds24edc002020-01-29 16:35:32 -05001857 final StatusBarNotification sbn = generateNotificationRecord(null).getSbn();
Julia Reynolds40f00d72017-12-12 10:47:32 -05001858 sbn.getNotification().flags |= Notification.FLAG_ONGOING_EVENT;
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001859 mBinderService.enqueueNotificationWithTag(PKG, PKG,
1860 "testAppInitiatedCancelAllNotifications_CancelsOnGoingFlag",
Julia Reynolds40f00d72017-12-12 10:47:32 -05001861 sbn.getId(), sbn.getNotification(), sbn.getUserId());
1862 mBinderService.cancelAllNotifications(PKG, sbn.getUserId());
1863 waitForIdle();
1864 StatusBarNotification[] notifs =
1865 mBinderService.getActiveNotifications(sbn.getPackageName());
1866 assertEquals(0, notifs.length);
1867 }
1868
1869 @Test
1870 public void testCancelAllNotifications_CancelsOnGoingFlag() throws Exception {
1871 final NotificationRecord notif = generateNotificationRecord(
1872 mTestNotificationChannel, 1, "group", true);
1873 notif.getNotification().flags |= Notification.FLAG_ONGOING_EVENT;
1874 mService.addNotification(notif);
1875 mService.cancelAllNotificationsInt(mUid, 0, PKG, null, 0, 0, true,
1876 notif.getUserId(), 0, null);
1877 waitForIdle();
1878 StatusBarNotification[] notifs =
Julia Reynolds24edc002020-01-29 16:35:32 -05001879 mBinderService.getActiveNotifications(notif.getSbn().getPackageName());
Julia Reynolds40f00d72017-12-12 10:47:32 -05001880 assertEquals(0, notifs.length);
1881 }
1882
1883 @Test
1884 public void testUserInitiatedCancelAllOnClearAll_OnGoingFlag() throws Exception {
1885 final NotificationRecord notif = generateNotificationRecord(
1886 mTestNotificationChannel, 1, "group", true);
1887 notif.getNotification().flags |= Notification.FLAG_ONGOING_EVENT;
1888 mService.addNotification(notif);
1889
1890 mService.mNotificationDelegate.onClearAll(mUid, Binder.getCallingPid(),
1891 notif.getUserId());
1892 waitForIdle();
1893 StatusBarNotification[] notifs =
Julia Reynolds24edc002020-01-29 16:35:32 -05001894 mBinderService.getActiveNotifications(notif.getSbn().getPackageName());
Julia Reynolds40f00d72017-12-12 10:47:32 -05001895 assertEquals(1, notifs.length);
1896 }
1897
1898 @Test
1899 public void testCancelAllCancelNotificationsFromListener_OnGoingFlag() throws Exception {
1900 final NotificationRecord parent = generateNotificationRecord(
1901 mTestNotificationChannel, 1, "group", true);
1902 final NotificationRecord child = generateNotificationRecord(
1903 mTestNotificationChannel, 2, "group", false);
1904 final NotificationRecord child2 = generateNotificationRecord(
1905 mTestNotificationChannel, 3, "group", false);
1906 child2.getNotification().flags |= Notification.FLAG_ONGOING_EVENT;
1907 final NotificationRecord newGroup = generateNotificationRecord(
1908 mTestNotificationChannel, 4, "group2", false);
1909 mService.addNotification(parent);
1910 mService.addNotification(child);
1911 mService.addNotification(child2);
1912 mService.addNotification(newGroup);
1913 mService.getBinderService().cancelNotificationsFromListener(null, null);
1914 waitForIdle();
1915 StatusBarNotification[] notifs =
Julia Reynolds24edc002020-01-29 16:35:32 -05001916 mBinderService.getActiveNotifications(parent.getSbn().getPackageName());
Julia Reynolds40f00d72017-12-12 10:47:32 -05001917 assertEquals(1, notifs.length);
1918 }
1919
1920 @Test
1921 public void testCancelAllCancelNotificationsFromListener_OnGoingFlagWithParameter()
1922 throws Exception {
1923 final NotificationRecord parent = generateNotificationRecord(
1924 mTestNotificationChannel, 1, "group", true);
1925 final NotificationRecord child = generateNotificationRecord(
1926 mTestNotificationChannel, 2, "group", false);
1927 final NotificationRecord child2 = generateNotificationRecord(
1928 mTestNotificationChannel, 3, "group", false);
1929 child2.getNotification().flags |= Notification.FLAG_ONGOING_EVENT;
1930 final NotificationRecord newGroup = generateNotificationRecord(
1931 mTestNotificationChannel, 4, "group2", false);
1932 mService.addNotification(parent);
1933 mService.addNotification(child);
1934 mService.addNotification(child2);
1935 mService.addNotification(newGroup);
Julia Reynolds24edc002020-01-29 16:35:32 -05001936 String[] keys = {parent.getSbn().getKey(), child.getSbn().getKey(),
1937 child2.getSbn().getKey(), newGroup.getSbn().getKey()};
Julia Reynolds40f00d72017-12-12 10:47:32 -05001938 mService.getBinderService().cancelNotificationsFromListener(null, keys);
1939 waitForIdle();
1940 StatusBarNotification[] notifs =
Julia Reynolds24edc002020-01-29 16:35:32 -05001941 mBinderService.getActiveNotifications(parent.getSbn().getPackageName());
Julia Reynolds40f00d72017-12-12 10:47:32 -05001942 assertEquals(0, notifs.length);
1943 }
1944
1945 @Test
1946 public void testUserInitiatedCancelAllWithGroup_OnGoingFlag() throws Exception {
1947 final NotificationRecord parent = generateNotificationRecord(
1948 mTestNotificationChannel, 1, "group", true);
1949 final NotificationRecord child = generateNotificationRecord(
1950 mTestNotificationChannel, 2, "group", false);
1951 final NotificationRecord child2 = generateNotificationRecord(
1952 mTestNotificationChannel, 3, "group", false);
1953 child2.getNotification().flags |= Notification.FLAG_ONGOING_EVENT;
1954 final NotificationRecord newGroup = generateNotificationRecord(
1955 mTestNotificationChannel, 4, "group2", false);
1956 mService.addNotification(parent);
1957 mService.addNotification(child);
1958 mService.addNotification(child2);
1959 mService.addNotification(newGroup);
1960 mService.mNotificationDelegate.onClearAll(mUid, Binder.getCallingPid(),
1961 parent.getUserId());
1962 waitForIdle();
1963 StatusBarNotification[] notifs =
Julia Reynolds24edc002020-01-29 16:35:32 -05001964 mBinderService.getActiveNotifications(parent.getSbn().getPackageName());
Julia Reynolds40f00d72017-12-12 10:47:32 -05001965 assertEquals(1, notifs.length);
1966 }
1967
1968 @Test
Julia Reynolds5f20e9f2017-01-30 08:54:53 -05001969 public void testTvExtenderChannelOverride_onTv() throws Exception {
Julia Reynolds503ed942017-10-04 16:04:56 -04001970 mService.setIsTelevision(true);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001971 mService.setPreferencesHelper(mPreferencesHelper);
1972 when(mPreferencesHelper.getNotificationChannel(
Julia Reynolds5f20e9f2017-01-30 08:54:53 -05001973 anyString(), anyInt(), eq("foo"), anyBoolean())).thenReturn(
Julia Reynolds8617e4e2017-09-18 16:52:37 -04001974 new NotificationChannel("foo", "foo", IMPORTANCE_HIGH));
Julia Reynolds5f20e9f2017-01-30 08:54:53 -05001975
Julia Reynoldsbad42972017-04-25 13:52:49 -04001976 Notification.TvExtender tv = new Notification.TvExtender().setChannelId("foo");
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001977 mBinderService.enqueueNotificationWithTag(PKG, PKG, "testTvExtenderChannelOverride_onTv", 0,
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001978 generateNotificationRecord(null, tv).getNotification(), 0);
Julia Reynolds12ba4cf2020-01-10 16:01:38 -05001979 verify(mPreferencesHelper, times(1)).getConversationNotificationChannel(
1980 anyString(), anyInt(), eq("foo"), eq(null), anyBoolean(), anyBoolean());
Julia Reynolds5f20e9f2017-01-30 08:54:53 -05001981 }
1982
1983 @Test
Julia Reynolds5f20e9f2017-01-30 08:54:53 -05001984 public void testTvExtenderChannelOverride_notOnTv() throws Exception {
Julia Reynolds503ed942017-10-04 16:04:56 -04001985 mService.setIsTelevision(false);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001986 mService.setPreferencesHelper(mPreferencesHelper);
1987 when(mPreferencesHelper.getNotificationChannel(
Julia Reynolds5f20e9f2017-01-30 08:54:53 -05001988 anyString(), anyInt(), anyString(), anyBoolean())).thenReturn(
Geoffrey Pitsch1f17e022017-01-03 16:44:20 -05001989 mTestNotificationChannel);
Julia Reynolds5f20e9f2017-01-30 08:54:53 -05001990
Julia Reynoldsbad42972017-04-25 13:52:49 -04001991 Notification.TvExtender tv = new Notification.TvExtender().setChannelId("foo");
Julia Reynoldsb6c83742019-07-30 18:03:40 -04001992 mBinderService.enqueueNotificationWithTag(PKG, PKG, "testTvExtenderChannelOverride_notOnTv",
1993 0, generateNotificationRecord(null, tv).getNotification(), 0);
Julia Reynolds12ba4cf2020-01-10 16:01:38 -05001994 verify(mPreferencesHelper, times(1)).getConversationNotificationChannel(
Julia Reynolds0f767342019-12-18 09:11:55 -05001995 anyString(), anyInt(), eq(mTestNotificationChannel.getId()), eq(null),
Julia Reynolds12ba4cf2020-01-10 16:01:38 -05001996 anyBoolean(), anyBoolean());
Julia Reynolds5f20e9f2017-01-30 08:54:53 -05001997 }
Julia Reynolds73ed76b2017-04-04 17:04:38 -04001998
1999 @Test
Julia Reynoldsfc9767b2018-01-22 17:45:16 -05002000 public void testUpdateAppNotifyCreatorBlock() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002001 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynoldsfc9767b2018-01-22 17:45:16 -05002002
Julia Reynoldsc4c6e9f2019-06-03 12:48:49 -04002003 mBinderService.setNotificationsEnabledForPackage(PKG, 0, true);
Julia Reynoldsfc9767b2018-01-22 17:45:16 -05002004 ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
2005 verify(mContext, times(1)).sendBroadcastAsUser(captor.capture(), any(), eq(null));
2006
2007 assertEquals(NotificationManager.ACTION_APP_BLOCK_STATE_CHANGED,
2008 captor.getValue().getAction());
2009 assertEquals(PKG, captor.getValue().getPackage());
Julia Reynoldsc4c6e9f2019-06-03 12:48:49 -04002010 assertFalse(captor.getValue().getBooleanExtra(EXTRA_BLOCKED_STATE, true));
2011 }
2012
2013 @Test
2014 public void testUpdateAppNotifyCreatorBlock_notIfMatchesExistingSetting() throws Exception {
2015 mService.setPreferencesHelper(mPreferencesHelper);
2016
2017 mBinderService.setNotificationsEnabledForPackage(PKG, 0, false);
2018 verify(mContext, never()).sendBroadcastAsUser(any(), any(), eq(null));
Julia Reynoldsfc9767b2018-01-22 17:45:16 -05002019 }
2020
2021 @Test
2022 public void testUpdateAppNotifyCreatorUnblock() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002023 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynoldsfc9767b2018-01-22 17:45:16 -05002024
2025 mBinderService.setNotificationsEnabledForPackage(PKG, 0, true);
2026 ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
2027 verify(mContext, times(1)).sendBroadcastAsUser(captor.capture(), any(), eq(null));
2028
2029 assertEquals(NotificationManager.ACTION_APP_BLOCK_STATE_CHANGED,
2030 captor.getValue().getAction());
2031 assertEquals(PKG, captor.getValue().getPackage());
2032 assertFalse(captor.getValue().getBooleanExtra(EXTRA_BLOCKED_STATE, true));
2033 }
2034
2035 @Test
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05002036 public void testUpdateChannelNotifyCreatorBlock() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002037 mService.setPreferencesHelper(mPreferencesHelper);
2038 when(mPreferencesHelper.getNotificationChannel(eq(PKG), anyInt(),
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05002039 eq(mTestNotificationChannel.getId()), anyBoolean()))
2040 .thenReturn(mTestNotificationChannel);
2041
2042 NotificationChannel updatedChannel =
2043 new NotificationChannel(mTestNotificationChannel.getId(),
2044 mTestNotificationChannel.getName(), IMPORTANCE_NONE);
2045
2046 mBinderService.updateNotificationChannelForPackage(PKG, 0, updatedChannel);
2047 ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
2048 verify(mContext, times(1)).sendBroadcastAsUser(captor.capture(), any(), eq(null));
2049
2050 assertEquals(NotificationManager.ACTION_NOTIFICATION_CHANNEL_BLOCK_STATE_CHANGED,
2051 captor.getValue().getAction());
2052 assertEquals(PKG, captor.getValue().getPackage());
2053 assertEquals(mTestNotificationChannel.getId(), captor.getValue().getStringExtra(
Julia Reynolds44ff7c92018-02-05 10:02:30 -05002054 NotificationManager.EXTRA_NOTIFICATION_CHANNEL_ID));
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05002055 assertTrue(captor.getValue().getBooleanExtra(EXTRA_BLOCKED_STATE, false));
2056 }
2057
2058 @Test
2059 public void testUpdateChannelNotifyCreatorUnblock() throws Exception {
2060 NotificationChannel existingChannel =
2061 new NotificationChannel(mTestNotificationChannel.getId(),
2062 mTestNotificationChannel.getName(), IMPORTANCE_NONE);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002063 mService.setPreferencesHelper(mPreferencesHelper);
2064 when(mPreferencesHelper.getNotificationChannel(eq(PKG), anyInt(),
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05002065 eq(mTestNotificationChannel.getId()), anyBoolean()))
2066 .thenReturn(existingChannel);
2067
2068 mBinderService.updateNotificationChannelForPackage(PKG, 0, mTestNotificationChannel);
2069 ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
2070 verify(mContext, times(1)).sendBroadcastAsUser(captor.capture(), any(), eq(null));
2071
2072 assertEquals(NotificationManager.ACTION_NOTIFICATION_CHANNEL_BLOCK_STATE_CHANGED,
2073 captor.getValue().getAction());
2074 assertEquals(PKG, captor.getValue().getPackage());
2075 assertEquals(mTestNotificationChannel.getId(), captor.getValue().getStringExtra(
Julia Reynolds44ff7c92018-02-05 10:02:30 -05002076 NotificationManager.EXTRA_NOTIFICATION_CHANNEL_ID));
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05002077 assertFalse(captor.getValue().getBooleanExtra(EXTRA_BLOCKED_STATE, false));
2078 }
2079
2080 @Test
2081 public void testUpdateChannelNoNotifyCreatorOtherChanges() throws Exception {
2082 NotificationChannel existingChannel =
2083 new NotificationChannel(mTestNotificationChannel.getId(),
2084 mTestNotificationChannel.getName(), IMPORTANCE_MAX);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002085 mService.setPreferencesHelper(mPreferencesHelper);
2086 when(mPreferencesHelper.getNotificationChannel(eq(PKG), anyInt(),
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05002087 eq(mTestNotificationChannel.getId()), anyBoolean()))
2088 .thenReturn(existingChannel);
2089
2090 mBinderService.updateNotificationChannelForPackage(PKG, 0, mTestNotificationChannel);
2091 verify(mContext, never()).sendBroadcastAsUser(any(), any(), eq(null));
2092 }
2093
2094 @Test
2095 public void testUpdateGroupNotifyCreatorBlock() throws Exception {
2096 NotificationChannelGroup existing = new NotificationChannelGroup("id", "name");
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002097 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynolds24edc002020-01-29 16:35:32 -05002098 when(mPreferencesHelper.getNotificationChannelGroup(eq(existing.getId()),
2099 eq(PKG), anyInt()))
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05002100 .thenReturn(existing);
2101
2102 NotificationChannelGroup updated = new NotificationChannelGroup("id", "name");
2103 updated.setBlocked(true);
2104
2105 mBinderService.updateNotificationChannelGroupForPackage(PKG, 0, updated);
2106 ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
2107 verify(mContext, times(1)).sendBroadcastAsUser(captor.capture(), any(), eq(null));
2108
2109 assertEquals(NotificationManager.ACTION_NOTIFICATION_CHANNEL_GROUP_BLOCK_STATE_CHANGED,
2110 captor.getValue().getAction());
2111 assertEquals(PKG, captor.getValue().getPackage());
2112 assertEquals(existing.getId(), captor.getValue().getStringExtra(
Julia Reynolds44ff7c92018-02-05 10:02:30 -05002113 NotificationManager.EXTRA_NOTIFICATION_CHANNEL_GROUP_ID));
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05002114 assertTrue(captor.getValue().getBooleanExtra(EXTRA_BLOCKED_STATE, false));
2115 }
2116
2117 @Test
2118 public void testUpdateGroupNotifyCreatorUnblock() throws Exception {
2119 NotificationChannelGroup existing = new NotificationChannelGroup("id", "name");
2120 existing.setBlocked(true);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002121 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynolds24edc002020-01-29 16:35:32 -05002122 when(mPreferencesHelper.getNotificationChannelGroup(eq(existing.getId()),
2123 eq(PKG), anyInt()))
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05002124 .thenReturn(existing);
2125
2126 mBinderService.updateNotificationChannelGroupForPackage(
2127 PKG, 0, new NotificationChannelGroup("id", "name"));
2128 ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
2129 verify(mContext, times(1)).sendBroadcastAsUser(captor.capture(), any(), eq(null));
2130
2131 assertEquals(NotificationManager.ACTION_NOTIFICATION_CHANNEL_GROUP_BLOCK_STATE_CHANGED,
2132 captor.getValue().getAction());
2133 assertEquals(PKG, captor.getValue().getPackage());
2134 assertEquals(existing.getId(), captor.getValue().getStringExtra(
Julia Reynolds44ff7c92018-02-05 10:02:30 -05002135 NotificationManager.EXTRA_NOTIFICATION_CHANNEL_GROUP_ID));
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05002136 assertFalse(captor.getValue().getBooleanExtra(EXTRA_BLOCKED_STATE, false));
2137 }
2138
2139 @Test
2140 public void testUpdateGroupNoNotifyCreatorOtherChanges() throws Exception {
2141 NotificationChannelGroup existing = new NotificationChannelGroup("id", "name");
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002142 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynolds24edc002020-01-29 16:35:32 -05002143 when(mPreferencesHelper.getNotificationChannelGroup(
2144 eq(existing.getId()), eq(PKG), anyInt()))
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05002145 .thenReturn(existing);
2146
2147 mBinderService.updateNotificationChannelGroupForPackage(
2148 PKG, 0, new NotificationChannelGroup("id", "new name"));
2149 verify(mContext, never()).sendBroadcastAsUser(any(), any(), eq(null));
2150 }
2151
2152 @Test
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002153 public void testCreateChannelNotifyListener() throws Exception {
2154 List<String> associations = new ArrayList<>();
2155 associations.add("a");
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04002156 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002157 mService.setPreferencesHelper(mPreferencesHelper);
2158 when(mPreferencesHelper.getNotificationChannel(eq(PKG), anyInt(),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002159 eq(mTestNotificationChannel.getId()), anyBoolean()))
2160 .thenReturn(mTestNotificationChannel);
2161 NotificationChannel channel2 = new NotificationChannel("a", "b", IMPORTANCE_LOW);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002162 when(mPreferencesHelper.getNotificationChannel(eq(PKG), anyInt(),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002163 eq(channel2.getId()), anyBoolean()))
2164 .thenReturn(channel2);
Julia Reynoldsdafd3a42019-05-24 13:33:28 -04002165 when(mPreferencesHelper.createNotificationChannel(eq(PKG), anyInt(),
2166 eq(channel2), anyBoolean(), anyBoolean()))
2167 .thenReturn(true);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002168
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002169 reset(mListeners);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002170 mBinderService.createNotificationChannels(PKG,
2171 new ParceledListSlice(Arrays.asList(mTestNotificationChannel, channel2)));
Julia Reynoldsdafd3a42019-05-24 13:33:28 -04002172 verify(mListeners, never()).notifyNotificationChannelChanged(eq(PKG),
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002173 eq(Process.myUserHandle()), eq(mTestNotificationChannel),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002174 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_ADDED));
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002175 verify(mListeners, times(1)).notifyNotificationChannelChanged(eq(PKG),
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002176 eq(Process.myUserHandle()), eq(channel2),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002177 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_ADDED));
2178 }
2179
2180 @Test
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002181 public void testCreateChannelGroupNotifyListener() throws Exception {
2182 List<String> associations = new ArrayList<>();
2183 associations.add("a");
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04002184 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002185 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002186 NotificationChannelGroup group1 = new NotificationChannelGroup("a", "b");
2187 NotificationChannelGroup group2 = new NotificationChannelGroup("n", "m");
2188
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002189 reset(mListeners);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002190 mBinderService.createNotificationChannelGroups(PKG,
2191 new ParceledListSlice(Arrays.asList(group1, group2)));
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002192 verify(mListeners, times(1)).notifyNotificationChannelGroupChanged(eq(PKG),
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002193 eq(Process.myUserHandle()), eq(group1),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002194 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_ADDED));
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002195 verify(mListeners, times(1)).notifyNotificationChannelGroupChanged(eq(PKG),
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002196 eq(Process.myUserHandle()), eq(group2),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002197 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_ADDED));
2198 }
2199
2200 @Test
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002201 public void testUpdateChannelNotifyListener() throws Exception {
2202 List<String> associations = new ArrayList<>();
2203 associations.add("a");
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04002204 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002205 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002206 mTestNotificationChannel.setLightColor(Color.CYAN);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002207 when(mPreferencesHelper.getNotificationChannel(eq(PKG), anyInt(),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002208 eq(mTestNotificationChannel.getId()), anyBoolean()))
2209 .thenReturn(mTestNotificationChannel);
2210
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002211 reset(mListeners);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002212 mBinderService.updateNotificationChannelForPackage(PKG, 0, mTestNotificationChannel);
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002213 verify(mListeners, times(1)).notifyNotificationChannelChanged(eq(PKG),
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002214 eq(Process.myUserHandle()), eq(mTestNotificationChannel),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002215 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_UPDATED));
2216 }
2217
2218 @Test
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002219 public void testDeleteChannelNotifyListener() throws Exception {
2220 List<String> associations = new ArrayList<>();
2221 associations.add("a");
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04002222 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002223 mService.setPreferencesHelper(mPreferencesHelper);
2224 when(mPreferencesHelper.getNotificationChannel(eq(PKG), anyInt(),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002225 eq(mTestNotificationChannel.getId()), anyBoolean()))
2226 .thenReturn(mTestNotificationChannel);
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002227 reset(mListeners);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002228 mBinderService.deleteNotificationChannel(PKG, mTestNotificationChannel.getId());
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002229 verify(mListeners, times(1)).notifyNotificationChannelChanged(eq(PKG),
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002230 eq(Process.myUserHandle()), eq(mTestNotificationChannel),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002231 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_DELETED));
2232 }
2233
2234 @Test
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002235 public void testDeleteChannelGroupNotifyListener() throws Exception {
2236 List<String> associations = new ArrayList<>();
2237 associations.add("a");
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04002238 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002239 NotificationChannelGroup ncg = new NotificationChannelGroup("a", "b/c");
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002240 mService.setPreferencesHelper(mPreferencesHelper);
2241 when(mPreferencesHelper.getNotificationChannelGroup(eq(ncg.getId()), eq(PKG), anyInt()))
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002242 .thenReturn(ncg);
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002243 reset(mListeners);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002244 mBinderService.deleteNotificationChannelGroup(PKG, ncg.getId());
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002245 verify(mListeners, times(1)).notifyNotificationChannelGroupChanged(eq(PKG),
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002246 eq(Process.myUserHandle()), eq(ncg),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002247 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_DELETED));
2248 }
2249
2250 @Test
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002251 public void testUpdateNotificationChannelFromPrivilegedListener_success() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002252 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002253 List<String> associations = new ArrayList<>();
2254 associations.add("a");
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04002255 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002256 when(mPreferencesHelper.getNotificationChannel(eq(PKG), anyInt(),
Julia Reynolds3eb3ffd2017-11-16 10:11:32 -05002257 eq(mTestNotificationChannel.getId()), anyBoolean()))
2258 .thenReturn(mTestNotificationChannel);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002259
2260 mBinderService.updateNotificationChannelFromPrivilegedListener(
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002261 null, PKG, Process.myUserHandle(), mTestNotificationChannel);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002262
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002263 verify(mPreferencesHelper, times(1)).updateNotificationChannel(
Julia Reynolds8617e4e2017-09-18 16:52:37 -04002264 anyString(), anyInt(), any(), anyBoolean());
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002265
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002266 verify(mListeners, never()).notifyNotificationChannelChanged(eq(PKG),
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002267 eq(Process.myUserHandle()), eq(mTestNotificationChannel),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002268 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_UPDATED));
2269 }
2270
2271 @Test
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002272 public void testUpdateNotificationChannelFromPrivilegedListener_noAccess() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002273 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002274 List<String> associations = new ArrayList<>();
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04002275 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002276
2277 try {
2278 mBinderService.updateNotificationChannelFromPrivilegedListener(
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002279 null, PKG, Process.myUserHandle(), mTestNotificationChannel);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002280 fail("listeners that don't have a companion device shouldn't be able to call this");
2281 } catch (SecurityException e) {
2282 // pass
2283 }
2284
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002285 verify(mPreferencesHelper, never()).updateNotificationChannel(
Julia Reynolds8617e4e2017-09-18 16:52:37 -04002286 anyString(), anyInt(), any(), anyBoolean());
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002287
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002288 verify(mListeners, never()).notifyNotificationChannelChanged(eq(PKG),
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002289 eq(Process.myUserHandle()), eq(mTestNotificationChannel),
2290 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_UPDATED));
2291 }
2292
2293 @Test
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002294 public void testUpdateNotificationChannelFromPrivilegedListener_badUser() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002295 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002296 List<String> associations = new ArrayList<>();
2297 associations.add("a");
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04002298 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002299 mListener = mock(ManagedServices.ManagedServiceInfo.class);
Julia Reynolds4da79702017-06-01 11:06:10 -04002300 mListener.component = new ComponentName(PKG, PKG);
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002301 when(mListener.enabledAndUserMatches(anyInt())).thenReturn(false);
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002302 when(mListeners.checkServiceTokenLocked(any())).thenReturn(mListener);
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002303
2304 try {
2305 mBinderService.updateNotificationChannelFromPrivilegedListener(
2306 null, PKG, UserHandle.ALL, mTestNotificationChannel);
2307 fail("incorrectly allowed a change to a user listener cannot see");
2308 } catch (SecurityException e) {
2309 // pass
2310 }
2311
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002312 verify(mPreferencesHelper, never()).updateNotificationChannel(
Julia Reynolds8617e4e2017-09-18 16:52:37 -04002313 anyString(), anyInt(), any(), anyBoolean());
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002314
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002315 verify(mListeners, never()).notifyNotificationChannelChanged(eq(PKG),
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002316 eq(Process.myUserHandle()), eq(mTestNotificationChannel),
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002317 eq(NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_UPDATED));
2318 }
2319
2320 @Test
Julia Reynolds48a6ed92018-10-22 12:52:03 -04002321 public void testGetNotificationChannelFromPrivilegedListener_cdm_success() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002322 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002323 List<String> associations = new ArrayList<>();
2324 associations.add("a");
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04002325 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002326
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002327 mBinderService.getNotificationChannelsFromPrivilegedListener(
2328 null, PKG, Process.myUserHandle());
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002329
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002330 verify(mPreferencesHelper, times(1)).getNotificationChannels(
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002331 anyString(), anyInt(), anyBoolean());
2332 }
2333
2334 @Test
Julia Reynolds48a6ed92018-10-22 12:52:03 -04002335 public void testGetNotificationChannelFromPrivilegedListener_cdm_noAccess() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002336 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002337 List<String> associations = new ArrayList<>();
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04002338 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002339
2340 try {
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002341 mBinderService.getNotificationChannelsFromPrivilegedListener(
2342 null, PKG, Process.myUserHandle());
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002343 fail("listeners that don't have a companion device shouldn't be able to call this");
2344 } catch (SecurityException e) {
2345 // pass
2346 }
2347
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002348 verify(mPreferencesHelper, never()).getNotificationChannels(
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002349 anyString(), anyInt(), anyBoolean());
2350 }
2351
2352 @Test
Julia Reynolds48a6ed92018-10-22 12:52:03 -04002353 public void testGetNotificationChannelFromPrivilegedListener_assistant_success()
2354 throws Exception {
2355 mService.setPreferencesHelper(mPreferencesHelper);
2356 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(new ArrayList<>());
2357 when(mAssistants.isServiceTokenValidLocked(any())).thenReturn(true);
2358
2359 mBinderService.getNotificationChannelsFromPrivilegedListener(
2360 null, PKG, Process.myUserHandle());
2361
2362 verify(mPreferencesHelper, times(1)).getNotificationChannels(
2363 anyString(), anyInt(), anyBoolean());
2364 }
2365
2366 @Test
Julia Reynolds268647a2018-10-25 16:54:27 -04002367 public void testGetNotificationChannelFromPrivilegedListener_assistant_noAccess()
2368 throws Exception {
Julia Reynolds48a6ed92018-10-22 12:52:03 -04002369 mService.setPreferencesHelper(mPreferencesHelper);
2370 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(new ArrayList<>());
2371 when(mAssistants.isServiceTokenValidLocked(any())).thenReturn(false);
2372
2373 try {
2374 mBinderService.getNotificationChannelsFromPrivilegedListener(
2375 null, PKG, Process.myUserHandle());
2376 fail("listeners that don't have a companion device shouldn't be able to call this");
2377 } catch (SecurityException e) {
2378 // pass
2379 }
2380
2381 verify(mPreferencesHelper, never()).getNotificationChannels(
2382 anyString(), anyInt(), anyBoolean());
2383 }
2384
2385 @Test
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002386 public void testGetNotificationChannelFromPrivilegedListener_badUser() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002387 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002388 List<String> associations = new ArrayList<>();
2389 associations.add("a");
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04002390 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002391 mListener = mock(ManagedServices.ManagedServiceInfo.class);
2392 when(mListener.enabledAndUserMatches(anyInt())).thenReturn(false);
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002393 when(mListeners.checkServiceTokenLocked(any())).thenReturn(mListener);
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002394
2395 try {
2396 mBinderService.getNotificationChannelsFromPrivilegedListener(
2397 null, PKG, Process.myUserHandle());
2398 fail("listener getting channels from a user they cannot see");
2399 } catch (SecurityException e) {
2400 // pass
2401 }
2402
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002403 verify(mPreferencesHelper, never()).getNotificationChannels(
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002404 anyString(), anyInt(), anyBoolean());
2405 }
2406
2407 @Test
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002408 public void testGetNotificationChannelGroupsFromPrivilegedListener_success() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002409 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002410 List<String> associations = new ArrayList<>();
2411 associations.add("a");
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04002412 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002413
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002414 mBinderService.getNotificationChannelGroupsFromPrivilegedListener(
2415 null, PKG, Process.myUserHandle());
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002416
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002417 verify(mPreferencesHelper, times(1)).getNotificationChannelGroups(anyString(), anyInt());
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002418 }
2419
2420 @Test
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002421 public void testGetNotificationChannelGroupsFromPrivilegedListener_noAccess() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002422 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002423 List<String> associations = new ArrayList<>();
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04002424 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002425
2426 try {
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002427 mBinderService.getNotificationChannelGroupsFromPrivilegedListener(
2428 null, PKG, Process.myUserHandle());
2429 fail("listeners that don't have a companion device shouldn't be able to call this");
2430 } catch (SecurityException e) {
2431 // pass
2432 }
2433
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002434 verify(mPreferencesHelper, never()).getNotificationChannelGroups(anyString(), anyInt());
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002435 }
2436
2437 @Test
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002438 public void testGetNotificationChannelGroupsFromPrivilegedListener_badUser() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002439 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002440 List<String> associations = new ArrayList<>();
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04002441 when(mCompanionMgr.getAssociations(PKG, mUid)).thenReturn(associations);
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002442 mListener = mock(ManagedServices.ManagedServiceInfo.class);
2443 when(mListener.enabledAndUserMatches(anyInt())).thenReturn(false);
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002444 when(mListeners.checkServiceTokenLocked(any())).thenReturn(mListener);
Julia Reynolds27c0a962018-12-10 12:37:28 -05002445 try {
Julia Reynoldsf27d6b22017-04-13 15:48:16 -04002446 mBinderService.getNotificationChannelGroupsFromPrivilegedListener(
2447 null, PKG, Process.myUserHandle());
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002448 fail("listeners that don't have a companion device shouldn't be able to call this");
2449 } catch (SecurityException e) {
2450 // pass
2451 }
2452
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04002453 verify(mPreferencesHelper, never()).getNotificationChannelGroups(anyString(), anyInt());
Julia Reynolds73ed76b2017-04-04 17:04:38 -04002454 }
Julia Reynoldsda781472017-04-12 09:41:16 -04002455
2456 @Test
Julia Reynoldsda781472017-04-12 09:41:16 -04002457 public void testHasCompanionDevice_failure() throws Exception {
2458 when(mCompanionMgr.getAssociations(anyString(), anyInt())).thenThrow(
2459 new IllegalArgumentException());
Julia Reynolds503ed942017-10-04 16:04:56 -04002460 mService.hasCompanionDevice(mListener);
Julia Reynoldsda781472017-04-12 09:41:16 -04002461 }
Julia Reynolds727a7282017-04-13 10:54:01 -04002462
2463 @Test
Julia Reynolds0c245002019-03-27 16:10:11 -04002464 public void testHasCompanionDevice_noService() {
Will Brockmancfd98302020-01-29 15:57:30 -05002465 mService = new TestableNotificationManagerService(mContext, mNotificationRecordLogger,
2466 mNotificationInstanceIdSequence);
Julia Reynolds727a7282017-04-13 10:54:01 -04002467
Julia Reynolds503ed942017-10-04 16:04:56 -04002468 assertFalse(mService.hasCompanionDevice(mListener));
Julia Reynolds727a7282017-04-13 10:54:01 -04002469 }
2470
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002471 @Test
Jay Aliomer24642da2019-07-30 09:57:41 -04002472 public void testSnoozeRunnable_reSnoozeASingleSnoozedNotification() throws Exception {
2473 final NotificationRecord notification = generateNotificationRecord(
2474 mTestNotificationChannel, 1, null, true);
2475 mService.addNotification(notification);
2476 when(mSnoozeHelper.getNotification(any())).thenReturn(notification);
2477
2478 NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
2479 mService.new SnoozeNotificationRunnable(
2480 notification.getKey(), 100, null);
2481 snoozeNotificationRunnable.run();
2482 NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable2 =
2483 mService.new SnoozeNotificationRunnable(
2484 notification.getKey(), 100, null);
2485 snoozeNotificationRunnable.run();
2486
2487 // snooze twice
2488 verify(mSnoozeHelper, times(2)).snooze(any(NotificationRecord.class), anyLong());
2489 }
2490
2491 @Test
2492 public void testSnoozeRunnable_reSnoozeASnoozedNotificationWithGroupKey() throws Exception {
2493 final NotificationRecord notification = generateNotificationRecord(
2494 mTestNotificationChannel, 1, "group", true);
2495 mService.addNotification(notification);
2496 when(mSnoozeHelper.getNotification(any())).thenReturn(notification);
2497
2498 NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
2499 mService.new SnoozeNotificationRunnable(
2500 notification.getKey(), 100, null);
2501 snoozeNotificationRunnable.run();
2502 NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable2 =
2503 mService.new SnoozeNotificationRunnable(
2504 notification.getKey(), 100, null);
2505 snoozeNotificationRunnable.run();
2506
2507 // snooze twice
2508 verify(mSnoozeHelper, times(2)).snooze(any(NotificationRecord.class), anyLong());
2509 }
2510
2511 @Test
2512 public void testSnoozeRunnable_reSnoozeMultipleNotificationsWithGroupKey() throws Exception {
2513 final NotificationRecord notification = generateNotificationRecord(
2514 mTestNotificationChannel, 1, "group", true);
2515 final NotificationRecord notification2 = generateNotificationRecord(
2516 mTestNotificationChannel, 2, "group", true);
2517 mService.addNotification(notification);
2518 mService.addNotification(notification2);
2519 when(mSnoozeHelper.getNotification(any())).thenReturn(notification);
2520 when(mSnoozeHelper.getNotifications(
2521 anyString(), anyString(), anyInt())).thenReturn(new ArrayList<>());
2522
2523 NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
2524 mService.new SnoozeNotificationRunnable(
2525 notification.getKey(), 100, null);
2526 snoozeNotificationRunnable.run();
2527 when(mSnoozeHelper.getNotifications(anyString(), anyString(), anyInt()))
2528 .thenReturn(new ArrayList<>(Arrays.asList(notification, notification2)));
2529 NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable2 =
2530 mService.new SnoozeNotificationRunnable(
2531 notification.getKey(), 100, null);
2532 snoozeNotificationRunnable.run();
2533
2534 // snooze twice
2535 verify(mSnoozeHelper, times(4)).snooze(any(NotificationRecord.class), anyLong());
2536 }
2537
2538 @Test
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002539 public void testSnoozeRunnable_snoozeNonGrouped() throws Exception {
2540 final NotificationRecord nonGrouped = generateNotificationRecord(
2541 mTestNotificationChannel, 1, null, false);
2542 final NotificationRecord grouped = generateNotificationRecord(
2543 mTestNotificationChannel, 2, "group", false);
Julia Reynolds503ed942017-10-04 16:04:56 -04002544 mService.addNotification(grouped);
2545 mService.addNotification(nonGrouped);
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002546
2547 NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
Julia Reynolds503ed942017-10-04 16:04:56 -04002548 mService.new SnoozeNotificationRunnable(
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002549 nonGrouped.getKey(), 100, null);
2550 snoozeNotificationRunnable.run();
2551
2552 // only snooze the one notification
2553 verify(mSnoozeHelper, times(1)).snooze(any(NotificationRecord.class), anyLong());
Julia Reynolds503ed942017-10-04 16:04:56 -04002554 assertTrue(nonGrouped.getStats().hasSnoozed());
Will Brockman9918db92020-03-06 16:48:39 -05002555
2556 assertEquals(2, mNotificationRecordLogger.numCalls());
2557 assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_SNOOZED,
2558 mNotificationRecordLogger.event(0));
2559 assertEquals(
2560 NotificationRecordLogger.NotificationCancelledEvent.NOTIFICATION_CANCEL_SNOOZED,
2561 mNotificationRecordLogger.event(1));
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002562 }
2563
2564 @Test
2565 public void testSnoozeRunnable_snoozeSummary_withChildren() throws Exception {
2566 final NotificationRecord parent = generateNotificationRecord(
2567 mTestNotificationChannel, 1, "group", true);
2568 final NotificationRecord child = generateNotificationRecord(
2569 mTestNotificationChannel, 2, "group", false);
2570 final NotificationRecord child2 = generateNotificationRecord(
2571 mTestNotificationChannel, 3, "group", false);
Julia Reynolds503ed942017-10-04 16:04:56 -04002572 mService.addNotification(parent);
2573 mService.addNotification(child);
2574 mService.addNotification(child2);
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002575
2576 NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
Julia Reynolds503ed942017-10-04 16:04:56 -04002577 mService.new SnoozeNotificationRunnable(
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002578 parent.getKey(), 100, null);
2579 snoozeNotificationRunnable.run();
2580
2581 // snooze parent and children
2582 verify(mSnoozeHelper, times(3)).snooze(any(NotificationRecord.class), anyLong());
2583 }
2584
2585 @Test
2586 public void testSnoozeRunnable_snoozeGroupChild_fellowChildren() throws Exception {
2587 final NotificationRecord parent = generateNotificationRecord(
2588 mTestNotificationChannel, 1, "group", true);
2589 final NotificationRecord child = generateNotificationRecord(
2590 mTestNotificationChannel, 2, "group", false);
2591 final NotificationRecord child2 = generateNotificationRecord(
2592 mTestNotificationChannel, 3, "group", false);
Julia Reynolds503ed942017-10-04 16:04:56 -04002593 mService.addNotification(parent);
2594 mService.addNotification(child);
2595 mService.addNotification(child2);
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002596
2597 NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
Julia Reynolds503ed942017-10-04 16:04:56 -04002598 mService.new SnoozeNotificationRunnable(
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002599 child2.getKey(), 100, null);
2600 snoozeNotificationRunnable.run();
2601
2602 // only snooze the one child
2603 verify(mSnoozeHelper, times(1)).snooze(any(NotificationRecord.class), anyLong());
Will Brockman9918db92020-03-06 16:48:39 -05002604
2605 assertEquals(2, mNotificationRecordLogger.numCalls());
2606 assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_SNOOZED,
2607 mNotificationRecordLogger.event(0));
2608 assertEquals(NotificationRecordLogger.NotificationCancelledEvent
2609 .NOTIFICATION_CANCEL_SNOOZED, mNotificationRecordLogger.event(1));
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002610 }
2611
2612 @Test
2613 public void testSnoozeRunnable_snoozeGroupChild_onlyChildOfSummary() throws Exception {
2614 final NotificationRecord parent = generateNotificationRecord(
2615 mTestNotificationChannel, 1, "group", true);
Julia Reynolds24edc002020-01-29 16:35:32 -05002616 assertTrue(parent.getSbn().getNotification().isGroupSummary());
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002617 final NotificationRecord child = generateNotificationRecord(
2618 mTestNotificationChannel, 2, "group", false);
Julia Reynolds503ed942017-10-04 16:04:56 -04002619 mService.addNotification(parent);
2620 mService.addNotification(child);
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002621
2622 NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
Julia Reynolds503ed942017-10-04 16:04:56 -04002623 mService.new SnoozeNotificationRunnable(
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002624 child.getKey(), 100, null);
2625 snoozeNotificationRunnable.run();
2626
2627 // snooze child and summary
2628 verify(mSnoozeHelper, times(2)).snooze(any(NotificationRecord.class), anyLong());
Will Brockman9918db92020-03-06 16:48:39 -05002629
2630 assertEquals(4, mNotificationRecordLogger.numCalls());
2631 assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_SNOOZED,
2632 mNotificationRecordLogger.event(0));
2633 assertEquals(
2634 NotificationRecordLogger.NotificationCancelledEvent.NOTIFICATION_CANCEL_SNOOZED,
2635 mNotificationRecordLogger.event(1));
2636 assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_SNOOZED,
2637 mNotificationRecordLogger.event(2));
2638 assertEquals(
2639 NotificationRecordLogger.NotificationCancelledEvent.NOTIFICATION_CANCEL_SNOOZED,
2640 mNotificationRecordLogger.event(3));
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002641 }
2642
2643 @Test
2644 public void testSnoozeRunnable_snoozeGroupChild_noOthersInGroup() throws Exception {
2645 final NotificationRecord child = generateNotificationRecord(
2646 mTestNotificationChannel, 2, "group", false);
Julia Reynolds503ed942017-10-04 16:04:56 -04002647 mService.addNotification(child);
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002648
2649 NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
Julia Reynolds503ed942017-10-04 16:04:56 -04002650 mService.new SnoozeNotificationRunnable(
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002651 child.getKey(), 100, null);
2652 snoozeNotificationRunnable.run();
2653
2654 // snooze child only
2655 verify(mSnoozeHelper, times(1)).snooze(any(NotificationRecord.class), anyLong());
Will Brockman9918db92020-03-06 16:48:39 -05002656
2657 assertEquals(2, mNotificationRecordLogger.numCalls());
2658 assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_SNOOZED,
2659 mNotificationRecordLogger.event(0));
2660 assertEquals(
2661 NotificationRecordLogger.NotificationCancelledEvent.NOTIFICATION_CANCEL_SNOOZED,
2662 mNotificationRecordLogger.event(1));
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002663 }
2664
2665 @Test
2666 public void testPostGroupChild_unsnoozeParent() throws Exception {
2667 final NotificationRecord child = generateNotificationRecord(
2668 mTestNotificationChannel, 2, "group", false);
2669
Julia Reynoldsb6c83742019-07-30 18:03:40 -04002670 mBinderService.enqueueNotificationWithTag(PKG, PKG, "testPostNonGroup_noUnsnoozing",
Julia Reynolds24edc002020-01-29 16:35:32 -05002671 child.getSbn().getId(), child.getSbn().getNotification(),
2672 child.getSbn().getUserId());
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002673 waitForIdle();
2674
2675 verify(mSnoozeHelper, times(1)).repostGroupSummary(
2676 anyString(), anyInt(), eq(child.getGroupKey()));
2677 }
2678
2679 @Test
2680 public void testPostNonGroup_noUnsnoozing() throws Exception {
2681 final NotificationRecord record = generateNotificationRecord(
2682 mTestNotificationChannel, 2, null, false);
2683
Julia Reynoldsb6c83742019-07-30 18:03:40 -04002684 mBinderService.enqueueNotificationWithTag(PKG, PKG, "testPostNonGroup_noUnsnoozing",
Julia Reynolds24edc002020-01-29 16:35:32 -05002685 record.getSbn().getId(), record.getSbn().getNotification(),
2686 record.getSbn().getUserId());
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002687 waitForIdle();
2688
2689 verify(mSnoozeHelper, never()).repostGroupSummary(anyString(), anyInt(), anyString());
2690 }
2691
2692 @Test
2693 public void testPostGroupSummary_noUnsnoozing() throws Exception {
2694 final NotificationRecord parent = generateNotificationRecord(
2695 mTestNotificationChannel, 2, "group", true);
2696
Julia Reynoldsb6c83742019-07-30 18:03:40 -04002697 mBinderService.enqueueNotificationWithTag(PKG, PKG, "testPostGroupSummary_noUnsnoozing",
Julia Reynolds24edc002020-01-29 16:35:32 -05002698 parent.getSbn().getId(), parent.getSbn().getNotification(),
2699 parent.getSbn().getUserId());
Julia Reynoldsa78cdff2017-04-26 10:19:25 -04002700 waitForIdle();
2701
2702 verify(mSnoozeHelper, never()).repostGroupSummary(anyString(), anyInt(), anyString());
2703 }
Julia Reynoldsb852e562017-06-06 16:14:18 -04002704
2705 @Test
Julia Reynolds0d073782020-02-13 16:07:52 -05002706 public void testSystemNotificationListenerCanUnsnooze() throws Exception {
2707 final NotificationRecord nr = generateNotificationRecord(
2708 mTestNotificationChannel, 2, "group", false);
2709
2710 mBinderService.enqueueNotificationWithTag(PKG, PKG,
2711 "testSystemNotificationListenerCanUnsnooze",
2712 nr.getSbn().getId(), nr.getSbn().getNotification(),
2713 nr.getSbn().getUserId());
2714 waitForIdle();
2715 NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
2716 mService.new SnoozeNotificationRunnable(
2717 nr.getKey(), 100, null);
2718 snoozeNotificationRunnable.run();
2719
2720 ManagedServices.ManagedServiceInfo listener = mListeners.new ManagedServiceInfo(
2721 null, new ComponentName(PKG, "test_class"), mUid, true, null, 0);
2722 listener.isSystem = true;
2723 when(mListeners.checkServiceTokenLocked(any())).thenReturn(listener);
2724
2725 mBinderService.unsnoozeNotificationFromSystemListener(null, nr.getKey());
2726 waitForIdle();
2727 StatusBarNotification[] notifs = mBinderService.getActiveNotifications(PKG);
2728 assertEquals(1, notifs.length);
2729 assertNotNull(notifs[0].getKey());//mService.getNotificationRecord(nr.getSbn().getKey()));
2730 }
2731
2732 @Test
Julia Reynolds92febc32017-10-26 11:30:31 -04002733 public void testSetListenerAccessForUser() throws Exception {
2734 UserHandle user = UserHandle.of(10);
2735 ComponentName c = ComponentName.unflattenFromString("package/Component");
Julia Reynolds4afe2642019-05-01 08:42:24 -04002736 mBinderService.setNotificationListenerAccessGrantedForUser(c, user.getIdentifier(), true);
2737
Julia Reynolds92febc32017-10-26 11:30:31 -04002738
2739 verify(mContext, times(1)).sendBroadcastAsUser(any(), eq(user), any());
2740 verify(mListeners, times(1)).setPackageOrComponentEnabled(
2741 c.flattenToString(), user.getIdentifier(), true, true);
2742 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2743 c.flattenToString(), user.getIdentifier(), false, true);
2744 verify(mAssistants, never()).setPackageOrComponentEnabled(
2745 any(), anyInt(), anyBoolean(), anyBoolean());
2746 }
2747
2748 @Test
2749 public void testSetAssistantAccessForUser() throws Exception {
2750 UserHandle user = UserHandle.of(10);
Julia Reynolds4afe2642019-05-01 08:42:24 -04002751 List<UserInfo> uis = new ArrayList<>();
2752 UserInfo ui = new UserInfo();
2753 ui.id = 10;
2754 uis.add(ui);
Julia Reynolds92febc32017-10-26 11:30:31 -04002755 ComponentName c = ComponentName.unflattenFromString("package/Component");
Julia Reynolds4afe2642019-05-01 08:42:24 -04002756 when(mUm.getEnabledProfiles(10)).thenReturn(uis);
2757
2758 mBinderService.setNotificationAssistantAccessGrantedForUser(c, user.getIdentifier(), true);
Julia Reynolds92febc32017-10-26 11:30:31 -04002759
2760 verify(mContext, times(1)).sendBroadcastAsUser(any(), eq(user), any());
2761 verify(mAssistants, times(1)).setPackageOrComponentEnabled(
2762 c.flattenToString(), user.getIdentifier(), true, true);
Tony Mak9a3c1f12019-03-04 16:04:42 +00002763 verify(mAssistants).setUserSet(10, true);
Julia Reynolds92febc32017-10-26 11:30:31 -04002764 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2765 c.flattenToString(), user.getIdentifier(), false, true);
2766 verify(mListeners, never()).setPackageOrComponentEnabled(
2767 any(), anyInt(), anyBoolean(), anyBoolean());
2768 }
2769
2770 @Test
Fabian Kozynskid9425662019-01-29 13:08:30 -05002771 public void testGetAssistantAllowedForUser() throws Exception {
2772 UserHandle user = UserHandle.of(10);
2773 try {
2774 mBinderService.getAllowedNotificationAssistantForUser(user.getIdentifier());
2775 } catch (IllegalStateException e) {
2776 if (!e.getMessage().contains("At most one NotificationAssistant")) {
2777 throw e;
2778 }
2779 }
2780 verify(mAssistants, times(1)).getAllowedComponents(user.getIdentifier());
2781 }
2782
2783 @Test
2784 public void testGetAssistantAllowed() throws Exception {
2785 try {
2786 mBinderService.getAllowedNotificationAssistant();
2787 } catch (IllegalStateException e) {
2788 if (!e.getMessage().contains("At most one NotificationAssistant")) {
2789 throw e;
2790 }
2791 }
2792 verify(mAssistants, times(1)).getAllowedComponents(0);
2793 }
2794
2795 @Test
Julia Reynolds92febc32017-10-26 11:30:31 -04002796 public void testSetDndAccessForUser() throws Exception {
2797 UserHandle user = UserHandle.of(10);
2798 ComponentName c = ComponentName.unflattenFromString("package/Component");
Julia Reynolds4afe2642019-05-01 08:42:24 -04002799 mBinderService.setNotificationPolicyAccessGrantedForUser(
2800 c.getPackageName(), user.getIdentifier(), true);
Julia Reynolds92febc32017-10-26 11:30:31 -04002801
2802 verify(mContext, times(1)).sendBroadcastAsUser(any(), eq(user), any());
2803 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2804 c.getPackageName(), user.getIdentifier(), true, true);
2805 verify(mAssistants, never()).setPackageOrComponentEnabled(
2806 any(), anyInt(), anyBoolean(), anyBoolean());
2807 verify(mListeners, never()).setPackageOrComponentEnabled(
2808 any(), anyInt(), anyBoolean(), anyBoolean());
2809 }
2810
2811 @Test
Julia Reynoldsb852e562017-06-06 16:14:18 -04002812 public void testSetListenerAccess() throws Exception {
2813 ComponentName c = ComponentName.unflattenFromString("package/Component");
Julia Reynolds4afe2642019-05-01 08:42:24 -04002814 mBinderService.setNotificationListenerAccessGranted(c, true);
Julia Reynoldsb852e562017-06-06 16:14:18 -04002815
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002816 verify(mListeners, times(1)).setPackageOrComponentEnabled(
Julia Reynoldsb852e562017-06-06 16:14:18 -04002817 c.flattenToString(), 0, true, true);
2818 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2819 c.flattenToString(), 0, false, true);
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002820 verify(mAssistants, never()).setPackageOrComponentEnabled(
Julia Reynoldsb852e562017-06-06 16:14:18 -04002821 any(), anyInt(), anyBoolean(), anyBoolean());
2822 }
2823
2824 @Test
2825 public void testSetAssistantAccess() throws Exception {
Julia Reynolds4afe2642019-05-01 08:42:24 -04002826 List<UserInfo> uis = new ArrayList<>();
2827 UserInfo ui = new UserInfo();
2828 ui.id = 0;
2829 uis.add(ui);
2830 when(mUm.getEnabledProfiles(ui.id)).thenReturn(uis);
Julia Reynoldsb852e562017-06-06 16:14:18 -04002831 ComponentName c = ComponentName.unflattenFromString("package/Component");
Julia Reynolds4afe2642019-05-01 08:42:24 -04002832
2833 mBinderService.setNotificationAssistantAccessGranted(c, true);
Julia Reynoldsb852e562017-06-06 16:14:18 -04002834
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002835 verify(mAssistants, times(1)).setPackageOrComponentEnabled(
Julia Reynoldsb852e562017-06-06 16:14:18 -04002836 c.flattenToString(), 0, true, true);
2837 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2838 c.flattenToString(), 0, false, true);
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002839 verify(mListeners, never()).setPackageOrComponentEnabled(
Julia Reynoldsb852e562017-06-06 16:14:18 -04002840 any(), anyInt(), anyBoolean(), anyBoolean());
2841 }
2842
2843 @Test
Julia Reynolds4afe2642019-05-01 08:42:24 -04002844 public void testSetAssistantAccess_multiProfile() throws Exception {
2845 List<UserInfo> uis = new ArrayList<>();
2846 UserInfo ui = new UserInfo();
2847 ui.id = 0;
2848 uis.add(ui);
2849 UserInfo ui10 = new UserInfo();
2850 ui10.id = 10;
2851 uis.add(ui10);
2852 when(mUm.getEnabledProfiles(ui.id)).thenReturn(uis);
2853 ComponentName c = ComponentName.unflattenFromString("package/Component");
2854
2855 mBinderService.setNotificationAssistantAccessGranted(c, true);
2856
2857 verify(mAssistants, times(1)).setPackageOrComponentEnabled(
2858 c.flattenToString(), 0, true, true);
2859 verify(mAssistants, times(1)).setPackageOrComponentEnabled(
2860 c.flattenToString(), 10, true, true);
2861 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2862 c.flattenToString(), 0, false, true);
2863 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2864 c.flattenToString(), 10, false, true);
2865 verify(mListeners, never()).setPackageOrComponentEnabled(
2866 any(), anyInt(), anyBoolean(), anyBoolean());
2867 }
2868
2869 @Test
Fabian Kozynskid9425662019-01-29 13:08:30 -05002870 public void testSetAssistantAccess_nullWithAllowedAssistant() throws Exception {
2871 ArrayList<ComponentName> componentList = new ArrayList<>();
2872 ComponentName c = ComponentName.unflattenFromString("package/Component");
2873 componentList.add(c);
2874 when(mAssistants.getAllowedComponents(anyInt())).thenReturn(componentList);
Julia Reynolds4afe2642019-05-01 08:42:24 -04002875 List<UserInfo> uis = new ArrayList<>();
2876 UserInfo ui = new UserInfo();
2877 ui.id = 0;
2878 uis.add(ui);
2879 when(mUm.getEnabledProfiles(ui.id)).thenReturn(uis);
Fabian Kozynskid9425662019-01-29 13:08:30 -05002880
Julia Reynolds4afe2642019-05-01 08:42:24 -04002881 mBinderService.setNotificationAssistantAccessGranted(null, true);
Fabian Kozynskid9425662019-01-29 13:08:30 -05002882
2883 verify(mAssistants, times(1)).setPackageOrComponentEnabled(
2884 c.flattenToString(), 0, true, false);
2885 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2886 c.flattenToString(), 0, false, false);
2887 verify(mListeners, never()).setPackageOrComponentEnabled(
2888 any(), anyInt(), anyBoolean(), anyBoolean());
2889 }
2890
2891 @Test
2892 public void testSetAssistantAccessForUser_nullWithAllowedAssistant() throws Exception {
Julia Reynolds4afe2642019-05-01 08:42:24 -04002893 List<UserInfo> uis = new ArrayList<>();
2894 UserInfo ui = new UserInfo();
2895 ui.id = 10;
2896 uis.add(ui);
2897 UserHandle user = ui.getUserHandle();
Fabian Kozynskid9425662019-01-29 13:08:30 -05002898 ArrayList<ComponentName> componentList = new ArrayList<>();
2899 ComponentName c = ComponentName.unflattenFromString("package/Component");
2900 componentList.add(c);
2901 when(mAssistants.getAllowedComponents(anyInt())).thenReturn(componentList);
Julia Reynolds4afe2642019-05-01 08:42:24 -04002902 when(mUm.getEnabledProfiles(10)).thenReturn(uis);
Fabian Kozynskid9425662019-01-29 13:08:30 -05002903
Julia Reynolds4afe2642019-05-01 08:42:24 -04002904 mBinderService.setNotificationAssistantAccessGrantedForUser(
2905 null, user.getIdentifier(), true);
Fabian Kozynskid9425662019-01-29 13:08:30 -05002906
2907 verify(mAssistants, times(1)).setPackageOrComponentEnabled(
2908 c.flattenToString(), user.getIdentifier(), true, false);
Julia Reynolds4afe2642019-05-01 08:42:24 -04002909 verify(mAssistants).setUserSet(10, true);
Fabian Kozynskid9425662019-01-29 13:08:30 -05002910 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2911 c.flattenToString(), user.getIdentifier(), false, false);
2912 verify(mListeners, never()).setPackageOrComponentEnabled(
2913 any(), anyInt(), anyBoolean(), anyBoolean());
2914 }
2915
2916 @Test
Julia Reynolds4afe2642019-05-01 08:42:24 -04002917 public void testSetAssistantAccessForUser_workProfile_nullWithAllowedAssistant()
2918 throws Exception {
2919 List<UserInfo> uis = new ArrayList<>();
2920 UserInfo ui = new UserInfo();
2921 ui.id = 0;
2922 uis.add(ui);
2923 UserInfo ui10 = new UserInfo();
2924 ui10.id = 10;
2925 uis.add(ui10);
2926 UserHandle user = ui.getUserHandle();
2927 ArrayList<ComponentName> componentList = new ArrayList<>();
2928 ComponentName c = ComponentName.unflattenFromString("package/Component");
2929 componentList.add(c);
2930 when(mAssistants.getAllowedComponents(anyInt())).thenReturn(componentList);
2931 when(mUm.getEnabledProfiles(ui.id)).thenReturn(uis);
2932
2933 mBinderService.setNotificationAssistantAccessGrantedForUser(
2934 null, user.getIdentifier(), true);
2935
2936 verify(mAssistants, times(1)).setPackageOrComponentEnabled(
2937 c.flattenToString(), user.getIdentifier(), true, false);
2938 verify(mAssistants, times(1)).setPackageOrComponentEnabled(
2939 c.flattenToString(), ui10.id, true, false);
2940 verify(mAssistants).setUserSet(0, true);
2941 verify(mAssistants).setUserSet(10, true);
2942 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2943 c.flattenToString(), user.getIdentifier(), false, false);
2944 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2945 c.flattenToString(), ui10.id, false, false);
2946 verify(mListeners, never()).setPackageOrComponentEnabled(
2947 any(), anyInt(), anyBoolean(), anyBoolean());
2948 }
2949
2950 @Test
Julia Reynoldsb852e562017-06-06 16:14:18 -04002951 public void testSetDndAccess() throws Exception {
2952 ComponentName c = ComponentName.unflattenFromString("package/Component");
Julia Reynolds4afe2642019-05-01 08:42:24 -04002953
2954 mBinderService.setNotificationPolicyAccessGranted(c.getPackageName(), true);
Julia Reynoldsb852e562017-06-06 16:14:18 -04002955
2956 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
2957 c.getPackageName(), 0, true, true);
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002958 verify(mAssistants, never()).setPackageOrComponentEnabled(
Julia Reynoldsb852e562017-06-06 16:14:18 -04002959 any(), anyInt(), anyBoolean(), anyBoolean());
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04002960 verify(mListeners, never()).setPackageOrComponentEnabled(
Julia Reynoldsb852e562017-06-06 16:14:18 -04002961 any(), anyInt(), anyBoolean(), anyBoolean());
2962 }
Julia Reynolds68263d12017-06-21 14:21:19 -04002963
2964 @Test
Rajeev Kumarbc79dcd2020-02-04 19:54:30 -08002965 public void testSetListenerAccess_onLowRam() throws Exception {
Julia Reynolds68263d12017-06-21 14:21:19 -04002966 when(mActivityManager.isLowRamDevice()).thenReturn(true);
2967 ComponentName c = ComponentName.unflattenFromString("package/Component");
2968 mBinderService.setNotificationListenerAccessGranted(c, true);
2969
Rajeev Kumarbc79dcd2020-02-04 19:54:30 -08002970 verify(mListeners).setPackageOrComponentEnabled(
Julia Reynoldse1816412017-10-24 10:39:11 -04002971 anyString(), anyInt(), anyBoolean(), anyBoolean());
Rajeev Kumarbc79dcd2020-02-04 19:54:30 -08002972 verify(mConditionProviders).setPackageOrComponentEnabled(
Julia Reynoldse1816412017-10-24 10:39:11 -04002973 anyString(), anyInt(), anyBoolean(), anyBoolean());
Rajeev Kumarbc79dcd2020-02-04 19:54:30 -08002974 verify(mAssistants).migrateToXml();
2975 verify(mAssistants).resetDefaultAssistantsIfNecessary();
Julia Reynolds68263d12017-06-21 14:21:19 -04002976 }
2977
2978 @Test
Rajeev Kumarbc79dcd2020-02-04 19:54:30 -08002979 public void testSetAssistantAccess_onLowRam() throws Exception {
Julia Reynolds68263d12017-06-21 14:21:19 -04002980 when(mActivityManager.isLowRamDevice()).thenReturn(true);
2981 ComponentName c = ComponentName.unflattenFromString("package/Component");
Julia Reynolds4afe2642019-05-01 08:42:24 -04002982 List<UserInfo> uis = new ArrayList<>();
2983 UserInfo ui = new UserInfo();
2984 ui.id = 0;
2985 uis.add(ui);
2986 when(mUm.getEnabledProfiles(ui.id)).thenReturn(uis);
2987
Julia Reynolds68263d12017-06-21 14:21:19 -04002988 mBinderService.setNotificationAssistantAccessGranted(c, true);
2989
Rajeev Kumarbc79dcd2020-02-04 19:54:30 -08002990 verify(mListeners).migrateToXml();
2991 verify(mListeners).notifyNotificationChannelChanged(anyString(), any(), any(),
2992 anyInt());
2993 verify(mConditionProviders).setPackageOrComponentEnabled(
Julia Reynoldse1816412017-10-24 10:39:11 -04002994 anyString(), anyInt(), anyBoolean(), anyBoolean());
Rajeev Kumarbc79dcd2020-02-04 19:54:30 -08002995 verify(mAssistants).migrateToXml();
2996 verify(mAssistants).resetDefaultAssistantsIfNecessary();
Julia Reynolds68263d12017-06-21 14:21:19 -04002997 }
2998
2999 @Test
Rajeev Kumarbc79dcd2020-02-04 19:54:30 -08003000 public void testSetDndAccess_onLowRam() throws Exception {
Julia Reynolds68263d12017-06-21 14:21:19 -04003001 when(mActivityManager.isLowRamDevice()).thenReturn(true);
3002 ComponentName c = ComponentName.unflattenFromString("package/Component");
3003 mBinderService.setNotificationPolicyAccessGranted(c.getPackageName(), true);
3004
Rajeev Kumarbc79dcd2020-02-04 19:54:30 -08003005 verify(mListeners).migrateToXml();
3006 verify(mListeners).notifyNotificationChannelChanged(anyString(), any(), any(),
3007 anyInt());
3008 verify(mConditionProviders).setPackageOrComponentEnabled(
Julia Reynoldse1816412017-10-24 10:39:11 -04003009 anyString(), anyInt(), anyBoolean(), anyBoolean());
Rajeev Kumarbc79dcd2020-02-04 19:54:30 -08003010 verify(mAssistants).migrateToXml();
3011 verify(mAssistants).resetDefaultAssistantsIfNecessary();
Julia Reynoldse1816412017-10-24 10:39:11 -04003012 }
3013
3014 @Test
3015 public void testSetListenerAccess_doesNothingOnLowRam_exceptWatch() throws Exception {
3016 when(mPackageManagerClient.hasSystemFeature(FEATURE_WATCH)).thenReturn(true);
3017 when(mActivityManager.isLowRamDevice()).thenReturn(true);
3018 ComponentName c = ComponentName.unflattenFromString("package/Component");
Julia Reynolds4afe2642019-05-01 08:42:24 -04003019
3020 mBinderService.setNotificationListenerAccessGranted(c, true);
Julia Reynoldse1816412017-10-24 10:39:11 -04003021
3022 verify(mListeners, times(1)).setPackageOrComponentEnabled(
3023 c.flattenToString(), 0, true, true);
3024 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
Julia Reynolds68263d12017-06-21 14:21:19 -04003025 c.flattenToString(), 0, false, true);
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04003026 verify(mAssistants, never()).setPackageOrComponentEnabled(
Julia Reynolds68263d12017-06-21 14:21:19 -04003027 any(), anyInt(), anyBoolean(), anyBoolean());
3028 }
Julia Reynolds8aebf352017-06-26 11:35:33 -04003029
3030 @Test
Julia Reynoldse1816412017-10-24 10:39:11 -04003031 public void testSetAssistantAccess_doesNothingOnLowRam_exceptWatch() throws Exception {
3032 when(mPackageManagerClient.hasSystemFeature(FEATURE_WATCH)).thenReturn(true);
3033 when(mActivityManager.isLowRamDevice()).thenReturn(true);
3034 ComponentName c = ComponentName.unflattenFromString("package/Component");
Julia Reynolds4afe2642019-05-01 08:42:24 -04003035 List<UserInfo> uis = new ArrayList<>();
3036 UserInfo ui = new UserInfo();
3037 ui.id = 0;
3038 uis.add(ui);
3039 when(mUm.getEnabledProfiles(ui.id)).thenReturn(uis);
3040
3041 mBinderService.setNotificationAssistantAccessGranted(c, true);
Julia Reynoldse1816412017-10-24 10:39:11 -04003042
3043 verify(mListeners, never()).setPackageOrComponentEnabled(
3044 anyString(), anyInt(), anyBoolean(), anyBoolean());
3045 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
3046 c.flattenToString(), 0, false, true);
3047 verify(mAssistants, times(1)).setPackageOrComponentEnabled(
3048 c.flattenToString(), 0, true, true);
3049 }
3050
3051 @Test
3052 public void testSetDndAccess_doesNothingOnLowRam_exceptWatch() throws Exception {
3053 when(mPackageManagerClient.hasSystemFeature(FEATURE_WATCH)).thenReturn(true);
3054 when(mActivityManager.isLowRamDevice()).thenReturn(true);
3055 ComponentName c = ComponentName.unflattenFromString("package/Component");
Julia Reynolds4afe2642019-05-01 08:42:24 -04003056
3057 mBinderService.setNotificationPolicyAccessGranted(c.getPackageName(), true);
Julia Reynoldse1816412017-10-24 10:39:11 -04003058
3059 verify(mListeners, never()).setPackageOrComponentEnabled(
3060 anyString(), anyInt(), anyBoolean(), anyBoolean());
3061 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
3062 c.getPackageName(), 0, true, true);
3063 verify(mAssistants, never()).setPackageOrComponentEnabled(
3064 any(), anyInt(), anyBoolean(), anyBoolean());
3065 }
3066
3067 @Test
Julia Reynolds8aebf352017-06-26 11:35:33 -04003068 public void testOnlyAutogroupIfGroupChanged_noPriorNoti_autogroups() throws Exception {
3069 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel, 0, null, false);
Julia Reynolds503ed942017-10-04 16:04:56 -04003070 mService.addEnqueuedNotification(r);
Julia Reynolds8aebf352017-06-26 11:35:33 -04003071 NotificationManagerService.PostNotificationRunnable runnable =
Julia Reynolds503ed942017-10-04 16:04:56 -04003072 mService.new PostNotificationRunnable(r.getKey());
Julia Reynolds8aebf352017-06-26 11:35:33 -04003073 runnable.run();
3074 waitForIdle();
3075
Julia Reynoldsa13b3e22017-08-10 16:58:54 -04003076 verify(mGroupHelper, times(1)).onNotificationPosted(any(), anyBoolean());
Julia Reynolds8aebf352017-06-26 11:35:33 -04003077 }
3078
3079 @Test
3080 public void testOnlyAutogroupIfGroupChanged_groupChanged_autogroups()
3081 throws Exception {
Julia Reynolds8617e4e2017-09-18 16:52:37 -04003082 NotificationRecord r =
3083 generateNotificationRecord(mTestNotificationChannel, 0, "group", false);
Julia Reynolds503ed942017-10-04 16:04:56 -04003084 mService.addNotification(r);
Julia Reynolds8aebf352017-06-26 11:35:33 -04003085
3086 r = generateNotificationRecord(mTestNotificationChannel, 0, null, false);
Julia Reynolds503ed942017-10-04 16:04:56 -04003087 mService.addEnqueuedNotification(r);
Julia Reynolds8aebf352017-06-26 11:35:33 -04003088 NotificationManagerService.PostNotificationRunnable runnable =
Julia Reynolds503ed942017-10-04 16:04:56 -04003089 mService.new PostNotificationRunnable(r.getKey());
Julia Reynolds8aebf352017-06-26 11:35:33 -04003090 runnable.run();
3091 waitForIdle();
3092
Julia Reynoldsa13b3e22017-08-10 16:58:54 -04003093 verify(mGroupHelper, times(1)).onNotificationPosted(any(), anyBoolean());
Julia Reynolds8aebf352017-06-26 11:35:33 -04003094 }
3095
3096 @Test
3097 public void testOnlyAutogroupIfGroupChanged_noGroupChanged_autogroups()
3098 throws Exception {
Julia Reynolds4db59552017-06-30 13:34:01 -04003099 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel, 0, "group",
3100 false);
Julia Reynolds503ed942017-10-04 16:04:56 -04003101 mService.addNotification(r);
3102 mService.addEnqueuedNotification(r);
Julia Reynolds8aebf352017-06-26 11:35:33 -04003103
3104 NotificationManagerService.PostNotificationRunnable runnable =
Julia Reynolds503ed942017-10-04 16:04:56 -04003105 mService.new PostNotificationRunnable(r.getKey());
Julia Reynolds8aebf352017-06-26 11:35:33 -04003106 runnable.run();
3107 waitForIdle();
3108
Julia Reynoldsa13b3e22017-08-10 16:58:54 -04003109 verify(mGroupHelper, never()).onNotificationPosted(any(), anyBoolean());
Julia Reynolds8aebf352017-06-26 11:35:33 -04003110 }
Beverly40239d92017-07-07 10:20:41 -04003111
Julia Reynolds4db59552017-06-30 13:34:01 -04003112 @Test
Brad Stenningd2e7a972018-10-01 09:08:42 -07003113 public void testDontAutogroupIfCritical() throws Exception {
3114 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel, 0, null, false);
3115 r.setCriticality(CriticalNotificationExtractor.CRITICAL_LOW);
3116 mService.addEnqueuedNotification(r);
3117 NotificationManagerService.PostNotificationRunnable runnable =
3118 mService.new PostNotificationRunnable(r.getKey());
3119 runnable.run();
3120
3121 r = generateNotificationRecord(mTestNotificationChannel, 1, null, false);
3122 r.setCriticality(CriticalNotificationExtractor.CRITICAL);
3123 runnable = mService.new PostNotificationRunnable(r.getKey());
3124 mService.addEnqueuedNotification(r);
3125
3126 runnable.run();
3127 waitForIdle();
3128
3129 verify(mGroupHelper, never()).onNotificationPosted(any(), anyBoolean());
3130 }
3131
3132 @Test
Julia Reynolds4db59552017-06-30 13:34:01 -04003133 public void testNoFakeColorizedPermission() throws Exception {
3134 when(mPackageManagerClient.checkPermission(any(), any())).thenReturn(PERMISSION_DENIED);
3135 Notification.Builder nb = new Notification.Builder(mContext,
3136 mTestNotificationChannel.getId())
3137 .setContentTitle("foo")
3138 .setColorized(true)
3139 .setFlag(Notification.FLAG_CAN_COLORIZE, true)
3140 .setSmallIcon(android.R.drawable.sym_def_app_icon);
Julia Reynoldsb6c83742019-07-30 18:03:40 -04003141 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1,
3142 "testNoFakeColorizedPermission", mUid, 0,
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04003143 nb.build(), new UserHandle(mUid), null, 0);
Julia Reynolds4db59552017-06-30 13:34:01 -04003144 NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
3145
Julia Reynoldsb6c83742019-07-30 18:03:40 -04003146 mBinderService.enqueueNotificationWithTag(PKG, PKG, sbn.getTag(),
Julia Reynolds24edc002020-01-29 16:35:32 -05003147 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
Julia Reynolds4db59552017-06-30 13:34:01 -04003148 waitForIdle();
3149
Julia Reynolds503ed942017-10-04 16:04:56 -04003150 NotificationRecord posted = mService.findNotificationLocked(
Julia Reynolds24edc002020-01-29 16:35:32 -05003151 PKG, nr.getSbn().getTag(), nr.getSbn().getId(), nr.getSbn().getUserId());
Julia Reynolds4db59552017-06-30 13:34:01 -04003152
3153 assertFalse(posted.getNotification().isColorized());
3154 }
Julia Reynolds6ad0aec2017-07-05 08:47:03 -04003155
3156 @Test
Julia Reynoldsb6c83742019-07-30 18:03:40 -04003157 public void testGetNotificationCountLocked() {
3158 String sampleTagToExclude = null;
3159 int sampleIdToExclude = 0;
Julia Reynolds6ad0aec2017-07-05 08:47:03 -04003160 for (int i = 0; i < 20; i++) {
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04003161 NotificationRecord r =
3162 generateNotificationRecord(mTestNotificationChannel, i, null, false);
Julia Reynolds503ed942017-10-04 16:04:56 -04003163 mService.addEnqueuedNotification(r);
Julia Reynoldsb6c83742019-07-30 18:03:40 -04003164
Julia Reynolds6ad0aec2017-07-05 08:47:03 -04003165 }
3166 for (int i = 0; i < 20; i++) {
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04003167 NotificationRecord r =
3168 generateNotificationRecord(mTestNotificationChannel, i, null, false);
Julia Reynolds503ed942017-10-04 16:04:56 -04003169 mService.addNotification(r);
Julia Reynolds24edc002020-01-29 16:35:32 -05003170 sampleTagToExclude = r.getSbn().getTag();
Julia Reynoldsb6c83742019-07-30 18:03:40 -04003171 sampleIdToExclude = i;
Julia Reynolds6ad0aec2017-07-05 08:47:03 -04003172 }
3173
3174 // another package
3175 Notification n =
3176 new Notification.Builder(mContext, mTestNotificationChannel.getId())
3177 .setSmallIcon(android.R.drawable.sym_def_app_icon)
3178 .build();
3179
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04003180 StatusBarNotification sbn = new StatusBarNotification("a", "a", 0, "tag", mUid, 0,
3181 n, new UserHandle(mUid), null, 0);
Julia Reynolds6ad0aec2017-07-05 08:47:03 -04003182 NotificationRecord otherPackage =
3183 new NotificationRecord(mContext, sbn, mTestNotificationChannel);
Julia Reynolds503ed942017-10-04 16:04:56 -04003184 mService.addEnqueuedNotification(otherPackage);
3185 mService.addNotification(otherPackage);
Julia Reynolds6ad0aec2017-07-05 08:47:03 -04003186
3187 // Same notifications are enqueued as posted, everything counts b/c id and tag don't match
Julia Reynoldsb6c83742019-07-30 18:03:40 -04003188 // anything that's currently enqueued or posted
Geoffrey Pitsch07532c32017-07-18 11:44:06 -04003189 int userId = new UserHandle(mUid).getIdentifier();
Julia Reynolds8617e4e2017-09-18 16:52:37 -04003190 assertEquals(40,
Julia Reynolds503ed942017-10-04 16:04:56 -04003191 mService.getNotificationCountLocked(PKG, userId, 0, null));
Julia Reynolds8617e4e2017-09-18 16:52:37 -04003192 assertEquals(40,
Julia Reynolds503ed942017-10-04 16:04:56 -04003193 mService.getNotificationCountLocked(PKG, userId, 0, "tag2"));
Julia Reynoldsb6c83742019-07-30 18:03:40 -04003194
3195 // return all for package "a" - "banana" tag isn't used
Julia Reynolds8617e4e2017-09-18 16:52:37 -04003196 assertEquals(2,
Julia Reynolds503ed942017-10-04 16:04:56 -04003197 mService.getNotificationCountLocked("a", userId, 0, "banana"));
Julia Reynolds6ad0aec2017-07-05 08:47:03 -04003198
3199 // exclude a known notification - it's excluded from only the posted list, not enqueued
Julia Reynoldsb6c83742019-07-30 18:03:40 -04003200 assertEquals(39, mService.getNotificationCountLocked(
3201 PKG, userId, sampleIdToExclude, sampleTagToExclude));
Julia Reynoldseb3dca72017-07-11 10:39:58 -04003202 }
3203
3204 @Test
Julia Reynolds51710712017-07-19 13:48:07 -04003205 public void testAddAutogroup_requestsSort() throws Exception {
Julia Reynoldseb3dca72017-07-11 10:39:58 -04003206 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
Julia Reynolds503ed942017-10-04 16:04:56 -04003207 mService.addNotification(r);
3208 mService.addAutogroupKeyLocked(r.getKey());
Julia Reynolds51710712017-07-19 13:48:07 -04003209
Julia Reynoldsb6c83742019-07-30 18:03:40 -04003210 verify(mRankingHandler, times(1)).requestSort();
Julia Reynolds51710712017-07-19 13:48:07 -04003211 }
3212
3213 @Test
3214 public void testRemoveAutogroup_requestsSort() throws Exception {
Julia Reynolds51710712017-07-19 13:48:07 -04003215 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
3216 r.setOverrideGroupKey("TEST");
Julia Reynolds503ed942017-10-04 16:04:56 -04003217 mService.addNotification(r);
3218 mService.removeAutogroupKeyLocked(r.getKey());
Julia Reynoldseb3dca72017-07-11 10:39:58 -04003219
Julia Reynoldsb6c83742019-07-30 18:03:40 -04003220 verify(mRankingHandler, times(1)).requestSort();
Julia Reynolds51710712017-07-19 13:48:07 -04003221 }
3222
3223 @Test
3224 public void testReaddAutogroup_noSort() throws Exception {
Julia Reynolds51710712017-07-19 13:48:07 -04003225 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
3226 r.setOverrideGroupKey("TEST");
Julia Reynolds503ed942017-10-04 16:04:56 -04003227 mService.addNotification(r);
3228 mService.addAutogroupKeyLocked(r.getKey());
Julia Reynolds51710712017-07-19 13:48:07 -04003229
Julia Reynoldsb6c83742019-07-30 18:03:40 -04003230 verify(mRankingHandler, never()).requestSort();
Julia Reynoldseb3dca72017-07-11 10:39:58 -04003231 }
3232
3233 @Test
3234 public void testHandleRankingSort_sendsUpdateOnSignalExtractorChange() throws Exception {
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04003235 mService.setPreferencesHelper(mPreferencesHelper);
Julia Reynoldseb3dca72017-07-11 10:39:58 -04003236 NotificationManagerService.WorkerHandler handler = mock(
3237 NotificationManagerService.WorkerHandler.class);
Julia Reynolds503ed942017-10-04 16:04:56 -04003238 mService.setHandler(handler);
Julia Reynoldseb3dca72017-07-11 10:39:58 -04003239
3240 Map<String, Answer> answers = getSignalExtractorSideEffects();
3241 for (String message : answers.keySet()) {
Julia Reynolds503ed942017-10-04 16:04:56 -04003242 mService.clearNotifications();
Julia Reynoldseb3dca72017-07-11 10:39:58 -04003243 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
Julia Reynolds503ed942017-10-04 16:04:56 -04003244 mService.addNotification(r);
Julia Reynoldseb3dca72017-07-11 10:39:58 -04003245
3246 doAnswer(answers.get(message)).when(mRankingHelper).extractSignals(r);
3247
Julia Reynolds503ed942017-10-04 16:04:56 -04003248 mService.handleRankingSort();
Julia Reynoldseb3dca72017-07-11 10:39:58 -04003249 }
3250 verify(handler, times(answers.size())).scheduleSendRankingUpdate();
3251 }
3252
3253 @Test
3254 public void testHandleRankingSort_noUpdateWhenNoSignalChange() throws Exception {
Julia Reynolds503ed942017-10-04 16:04:56 -04003255 mService.setRankingHelper(mRankingHelper);
Julia Reynoldseb3dca72017-07-11 10:39:58 -04003256 NotificationManagerService.WorkerHandler handler = mock(
3257 NotificationManagerService.WorkerHandler.class);
Julia Reynolds503ed942017-10-04 16:04:56 -04003258 mService.setHandler(handler);
Julia Reynoldseb3dca72017-07-11 10:39:58 -04003259
3260 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
Julia Reynolds503ed942017-10-04 16:04:56 -04003261 mService.addNotification(r);
Julia Reynoldseb3dca72017-07-11 10:39:58 -04003262
Julia Reynolds503ed942017-10-04 16:04:56 -04003263 mService.handleRankingSort();
Julia Reynoldseb3dca72017-07-11 10:39:58 -04003264 verify(handler, never()).scheduleSendRankingUpdate();
Julia Reynolds6ad0aec2017-07-05 08:47:03 -04003265 }
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04003266
3267 @Test
3268 public void testReadPolicyXml_readApprovedServicesFromXml() throws Exception {
Julia Reynoldsd6d5a592018-04-02 11:03:32 -04003269 final String upgradeXml = "<notification-policy version=\"1\">"
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04003270 + "<ranking></ranking>"
3271 + "<enabled_listeners>"
3272 + "<service_listing approved=\"test\" user=\"0\" primary=\"true\" />"
3273 + "</enabled_listeners>"
3274 + "<enabled_assistants>"
3275 + "<service_listing approved=\"test\" user=\"0\" primary=\"true\" />"
3276 + "</enabled_assistants>"
3277 + "<dnd_apps>"
3278 + "<service_listing approved=\"test\" user=\"0\" primary=\"true\" />"
3279 + "</dnd_apps>"
3280 + "</notification-policy>";
Julia Reynolds503ed942017-10-04 16:04:56 -04003281 mService.readPolicyXml(
Annie Meng8b646fd2019-02-01 18:46:42 +00003282 new BufferedInputStream(new ByteArrayInputStream(upgradeXml.getBytes())),
3283 false,
3284 UserHandle.USER_ALL);
3285 verify(mListeners, times(1)).readXml(any(), any(), anyBoolean(), anyInt());
3286 verify(mConditionProviders, times(1)).readXml(any(), any(), anyBoolean(), anyInt());
3287 verify(mAssistants, times(1)).readXml(any(), any(), anyBoolean(), anyInt());
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04003288
3289 // numbers are inflated for setup
3290 verify(mListeners, times(1)).migrateToXml();
3291 verify(mConditionProviders, times(1)).migrateToXml();
3292 verify(mAssistants, times(1)).migrateToXml();
Tony Mak9a3c1f12019-03-04 16:04:42 +00003293 verify(mAssistants, times(2)).resetDefaultAssistantsIfNecessary();
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04003294 }
3295
3296 @Test
Jay Aliomer4dc508d2019-08-06 17:36:31 -04003297 public void testReadPolicyXml_readSnoozedNotificationsFromXml() throws Exception {
3298 final String upgradeXml = "<notification-policy version=\"1\">"
3299 + "<snoozed-notifications>></snoozed-notifications>"
3300 + "</notification-policy>";
3301 mService.readPolicyXml(
3302 new BufferedInputStream(new ByteArrayInputStream(upgradeXml.getBytes())),
3303 false,
3304 UserHandle.USER_ALL);
Julia Reynolds9050d9a2020-02-20 09:38:05 -05003305 verify(mSnoozeHelper, times(1)).readXml(any(XmlPullParser.class), anyLong());
Jay Aliomer4dc508d2019-08-06 17:36:31 -04003306 }
3307
3308 @Test
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04003309 public void testReadPolicyXml_readApprovedServicesFromSettings() throws Exception {
3310 final String preupgradeXml = "<notification-policy version=\"1\">"
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04003311 + "<ranking></ranking>"
3312 + "</notification-policy>";
Julia Reynolds503ed942017-10-04 16:04:56 -04003313 mService.readPolicyXml(
Annie Meng8b646fd2019-02-01 18:46:42 +00003314 new BufferedInputStream(new ByteArrayInputStream(preupgradeXml.getBytes())),
3315 false,
3316 UserHandle.USER_ALL);
3317 verify(mListeners, never()).readXml(any(), any(), anyBoolean(), anyInt());
3318 verify(mConditionProviders, never()).readXml(any(), any(), anyBoolean(), anyInt());
3319 verify(mAssistants, never()).readXml(any(), any(), anyBoolean(), anyInt());
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04003320
3321 // numbers are inflated for setup
3322 verify(mListeners, times(2)).migrateToXml();
3323 verify(mConditionProviders, times(2)).migrateToXml();
3324 verify(mAssistants, times(2)).migrateToXml();
Tony Mak9a3c1f12019-03-04 16:04:42 +00003325 verify(mAssistants, times(2)).resetDefaultAssistantsIfNecessary();
Julia Reynoldsd1bf5f02017-07-11 10:39:58 -04003326 }
3327
Annie Meng8b646fd2019-02-01 18:46:42 +00003328 @Test
3329 public void testReadPolicyXml_doesNotRestoreManagedServicesForManagedUser() throws Exception {
3330 final String policyXml = "<notification-policy version=\"1\">"
3331 + "<ranking></ranking>"
3332 + "<enabled_listeners>"
3333 + "<service_listing approved=\"test\" user=\"10\" primary=\"true\" />"
3334 + "</enabled_listeners>"
3335 + "<enabled_assistants>"
3336 + "<service_listing approved=\"test\" user=\"10\" primary=\"true\" />"
3337 + "</enabled_assistants>"
3338 + "<dnd_apps>"
3339 + "<service_listing approved=\"test\" user=\"10\" primary=\"true\" />"
3340 + "</dnd_apps>"
3341 + "</notification-policy>";
Julia Reynolds0c245002019-03-27 16:10:11 -04003342 when(mUm.isManagedProfile(10)).thenReturn(true);
Annie Meng8b646fd2019-02-01 18:46:42 +00003343 mService.readPolicyXml(
3344 new BufferedInputStream(new ByteArrayInputStream(policyXml.getBytes())),
3345 true,
3346 10);
3347 verify(mListeners, never()).readXml(any(), any(), eq(true), eq(10));
3348 verify(mConditionProviders, never()).readXml(any(), any(), eq(true), eq(10));
3349 verify(mAssistants, never()).readXml(any(), any(), eq(true), eq(10));
3350 }
3351
3352 @Test
3353 public void testReadPolicyXml_restoresManagedServicesForNonManagedUser() throws Exception {
3354 final String policyXml = "<notification-policy version=\"1\">"
3355 + "<ranking></ranking>"
3356 + "<enabled_listeners>"
3357 + "<service_listing approved=\"test\" user=\"10\" primary=\"true\" />"
3358 + "</enabled_listeners>"
3359 + "<enabled_assistants>"
3360 + "<service_listing approved=\"test\" user=\"10\" primary=\"true\" />"
3361 + "</enabled_assistants>"
3362 + "<dnd_apps>"
3363 + "<service_listing approved=\"test\" user=\"10\" primary=\"true\" />"
3364 + "</dnd_apps>"
3365 + "</notification-policy>";
Julia Reynolds0c245002019-03-27 16:10:11 -04003366 when(mUm.isManagedProfile(10)).thenReturn(false);
Annie Meng8b646fd2019-02-01 18:46:42 +00003367 mService.readPolicyXml(
3368 new BufferedInputStream(new ByteArrayInputStream(policyXml.getBytes())),
3369 true,
3370 10);
3371 verify(mListeners, times(1)).readXml(any(), any(), eq(true), eq(10));
3372 verify(mConditionProviders, times(1)).readXml(any(), any(), eq(true), eq(10));
3373 verify(mAssistants, times(1)).readXml(any(), any(), eq(true), eq(10));
3374 }
Beverlyd4f96492017-08-02 13:36:11 -04003375
3376 @Test
3377 public void testLocaleChangedCallsUpdateDefaultZenModeRules() throws Exception {
3378 ZenModeHelper mZenModeHelper = mock(ZenModeHelper.class);
Julia Reynolds503ed942017-10-04 16:04:56 -04003379 mService.mZenModeHelper = mZenModeHelper;
3380 mService.mLocaleChangeReceiver.onReceive(mContext,
Beverlyd4f96492017-08-02 13:36:11 -04003381 new Intent(Intent.ACTION_LOCALE_CHANGED));
3382
3383 verify(mZenModeHelper, times(1)).updateDefaultZenRules();
3384 }
Julia Reynolds8617e4e2017-09-18 16:52:37 -04003385
3386 @Test
3387 public void testBumpFGImportance_noChannelChangePreOApp() throws Exception {
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003388 String preOPkg = PKG_N_MR1;
Julia Reynolds8617e4e2017-09-18 16:52:37 -04003389 final ApplicationInfo legacy = new ApplicationInfo();
3390 legacy.targetSdkVersion = Build.VERSION_CODES.N_MR1;
3391 when(mPackageManagerClient.getApplicationInfoAsUser(eq(preOPkg), anyInt(), anyInt()))
3392 .thenReturn(legacy);
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04003393 when(mPackageManagerClient.getPackageUidAsUser(eq(preOPkg), anyInt()))
3394 .thenReturn(Binder.getCallingUid());
Julia Reynolds8617e4e2017-09-18 16:52:37 -04003395 getContext().setMockPackageManager(mPackageManagerClient);
3396
3397 Notification.Builder nb = new Notification.Builder(mContext,
3398 NotificationChannel.DEFAULT_CHANNEL_ID)
3399 .setContentTitle("foo")
3400 .setSmallIcon(android.R.drawable.sym_def_app_icon)
Julia Reynoldse5c60452018-04-30 14:41:36 -04003401 .setFlag(FLAG_FOREGROUND_SERVICE, true)
Julia Reynolds8617e4e2017-09-18 16:52:37 -04003402 .setPriority(Notification.PRIORITY_MIN);
3403
Julia Reynoldsb6c83742019-07-30 18:03:40 -04003404 StatusBarNotification sbn = new StatusBarNotification(preOPkg, preOPkg, 9,
3405 "testBumpFGImportance_noChannelChangePreOApp",
Julia Reynolds24edc002020-01-29 16:35:32 -05003406 Binder.getCallingUid(), 0, nb.build(), new UserHandle(Binder.getCallingUid()), null,
3407 0);
Julia Reynolds8617e4e2017-09-18 16:52:37 -04003408
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04003409 mBinderService.enqueueNotificationWithTag(sbn.getPackageName(), sbn.getOpPkg(),
3410 sbn.getTag(), sbn.getId(), sbn.getNotification(), sbn.getUserId());
Julia Reynolds8617e4e2017-09-18 16:52:37 -04003411 waitForIdle();
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04003412
Julia Reynolds8617e4e2017-09-18 16:52:37 -04003413 assertEquals(IMPORTANCE_LOW,
Julia Reynolds503ed942017-10-04 16:04:56 -04003414 mService.getNotificationRecord(sbn.getKey()).getImportance());
Julia Reynolds8617e4e2017-09-18 16:52:37 -04003415
3416 nb = new Notification.Builder(mContext)
3417 .setContentTitle("foo")
3418 .setSmallIcon(android.R.drawable.sym_def_app_icon)
Julia Reynoldse5c60452018-04-30 14:41:36 -04003419 .setFlag(FLAG_FOREGROUND_SERVICE, true)
Julia Reynolds8617e4e2017-09-18 16:52:37 -04003420 .setPriority(Notification.PRIORITY_MIN);
3421
Julia Reynoldsb6c83742019-07-30 18:03:40 -04003422 sbn = new StatusBarNotification(preOPkg, preOPkg, 9,
3423 "testBumpFGImportance_noChannelChangePreOApp", Binder.getCallingUid(),
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04003424 0, nb.build(), new UserHandle(Binder.getCallingUid()), null, 0);
Julia Reynolds8617e4e2017-09-18 16:52:37 -04003425
Julia Reynoldsb6c83742019-07-30 18:03:40 -04003426 mBinderService.enqueueNotificationWithTag(preOPkg, preOPkg,
3427 "testBumpFGImportance_noChannelChangePreOApp",
Julia Reynolds8617e4e2017-09-18 16:52:37 -04003428 sbn.getId(), sbn.getNotification(), sbn.getUserId());
3429 waitForIdle();
3430 assertEquals(IMPORTANCE_LOW,
Julia Reynolds503ed942017-10-04 16:04:56 -04003431 mService.getNotificationRecord(sbn.getKey()).getImportance());
Julia Reynolds8617e4e2017-09-18 16:52:37 -04003432
3433 NotificationChannel defaultChannel = mBinderService.getNotificationChannel(
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -04003434 preOPkg, mContext.getUserId(), preOPkg, NotificationChannel.DEFAULT_CHANNEL_ID);
Julia Reynolds8617e4e2017-09-18 16:52:37 -04003435 assertEquals(IMPORTANCE_UNSPECIFIED, defaultChannel.getImportance());
3436 }
Julia Reynolds503ed942017-10-04 16:04:56 -04003437
3438 @Test
3439 public void testStats_updatedOnDirectReply() throws Exception {
3440 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
3441 mService.addNotification(r);
3442
3443 mService.mNotificationDelegate.onNotificationDirectReplied(r.getKey());
3444 assertTrue(mService.getNotificationRecord(r.getKey()).getStats().hasDirectReplied());
Julia Reynolds24edc002020-01-29 16:35:32 -05003445 verify(mAssistants).notifyAssistantNotificationDirectReplyLocked(eq(r.getSbn()));
Will Brockman9918db92020-03-06 16:48:39 -05003446
3447 assertEquals(1, mNotificationRecordLogger.numCalls());
3448 assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_DIRECT_REPLIED,
3449 mNotificationRecordLogger.event(0));
Julia Reynolds503ed942017-10-04 16:04:56 -04003450 }
3451
3452 @Test
Julia Reynolds84dc96b2017-11-14 09:51:01 -05003453 public void testStats_updatedOnUserExpansion() throws Exception {
3454 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
Julia Reynolds503ed942017-10-04 16:04:56 -04003455 mService.addNotification(r);
3456
Gustav Senntona8e38aa2019-01-22 14:55:39 +00003457 mService.mNotificationDelegate.onNotificationExpansionChanged(r.getKey(), true, true,
3458 NOTIFICATION_LOCATION_UNKNOWN);
Julia Reynolds24edc002020-01-29 16:35:32 -05003459 verify(mAssistants).notifyAssistantExpansionChangedLocked(eq(r.getSbn()), eq(true),
3460 eq((true)));
Julia Reynolds503ed942017-10-04 16:04:56 -04003461 assertTrue(mService.getNotificationRecord(r.getKey()).getStats().hasExpanded());
Tony Makeda84a72018-11-19 17:01:32 +00003462
Gustav Senntona8e38aa2019-01-22 14:55:39 +00003463 mService.mNotificationDelegate.onNotificationExpansionChanged(r.getKey(), true, false,
3464 NOTIFICATION_LOCATION_UNKNOWN);
Julia Reynolds24edc002020-01-29 16:35:32 -05003465 verify(mAssistants).notifyAssistantExpansionChangedLocked(eq(r.getSbn()), eq(true),
3466 eq((false)));
Julia Reynolds503ed942017-10-04 16:04:56 -04003467 assertTrue(mService.getNotificationRecord(r.getKey()).getStats().hasExpanded());
Will Brockman9918db92020-03-06 16:48:39 -05003468
3469 assertEquals(2, mNotificationRecordLogger.numCalls());
3470 assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_DETAIL_OPEN_USER,
3471 mNotificationRecordLogger.event(0));
3472 assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_DETAIL_CLOSE_USER,
3473 mNotificationRecordLogger.event(1));
Julia Reynolds503ed942017-10-04 16:04:56 -04003474 }
3475
3476 @Test
Julia Reynolds84dc96b2017-11-14 09:51:01 -05003477 public void testStats_notUpdatedOnAutoExpansion() throws Exception {
3478 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
3479 mService.addNotification(r);
3480
Gustav Senntona8e38aa2019-01-22 14:55:39 +00003481 mService.mNotificationDelegate.onNotificationExpansionChanged(r.getKey(), false, true,
3482 NOTIFICATION_LOCATION_UNKNOWN);
Julia Reynolds84dc96b2017-11-14 09:51:01 -05003483 assertFalse(mService.getNotificationRecord(r.getKey()).getStats().hasExpanded());
Julia Reynolds24edc002020-01-29 16:35:32 -05003484 verify(mAssistants).notifyAssistantExpansionChangedLocked(eq(r.getSbn()), eq(false),
3485 eq((true)));
Tony Makeda84a72018-11-19 17:01:32 +00003486
Gustav Senntona8e38aa2019-01-22 14:55:39 +00003487 mService.mNotificationDelegate.onNotificationExpansionChanged(r.getKey(), false, false,
3488 NOTIFICATION_LOCATION_UNKNOWN);
Julia Reynolds84dc96b2017-11-14 09:51:01 -05003489 assertFalse(mService.getNotificationRecord(r.getKey()).getStats().hasExpanded());
Tony Makeda84a72018-11-19 17:01:32 +00003490 verify(mAssistants).notifyAssistantExpansionChangedLocked(
Julia Reynolds24edc002020-01-29 16:35:32 -05003491 eq(r.getSbn()), eq(false), eq((false)));
Julia Reynolds84dc96b2017-11-14 09:51:01 -05003492 }
3493
3494 @Test
Julia Reynolds503ed942017-10-04 16:04:56 -04003495 public void testStats_updatedOnViewSettings() throws Exception {
3496 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
3497 mService.addNotification(r);
3498
3499 mService.mNotificationDelegate.onNotificationSettingsViewed(r.getKey());
3500 assertTrue(mService.getNotificationRecord(r.getKey()).getStats().hasViewedSettings());
3501 }
3502
3503 @Test
3504 public void testStats_updatedOnVisibilityChanged() throws Exception {
3505 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
3506 mService.addNotification(r);
3507
Dieter Hsud39f0d52018-04-14 02:08:30 +08003508 final NotificationVisibility nv = NotificationVisibility.obtain(r.getKey(), 1, 2, true);
Julia Reynolds503ed942017-10-04 16:04:56 -04003509 mService.mNotificationDelegate.onNotificationVisibilityChanged(
3510 new NotificationVisibility[] {nv}, new NotificationVisibility[]{});
Julia Reynolds24edc002020-01-29 16:35:32 -05003511 verify(mAssistants).notifyAssistantVisibilityChangedLocked(eq(r.getSbn()), eq(true));
Julia Reynolds503ed942017-10-04 16:04:56 -04003512 assertTrue(mService.getNotificationRecord(r.getKey()).getStats().hasSeen());
3513 mService.mNotificationDelegate.onNotificationVisibilityChanged(
3514 new NotificationVisibility[] {}, new NotificationVisibility[]{nv});
Julia Reynolds24edc002020-01-29 16:35:32 -05003515 verify(mAssistants).notifyAssistantVisibilityChangedLocked(eq(r.getSbn()), eq(false));
Julia Reynolds503ed942017-10-04 16:04:56 -04003516 assertTrue(mService.getNotificationRecord(r.getKey()).getStats().hasSeen());
3517 }
3518
3519 @Test
3520 public void testStats_dismissalSurface() throws Exception {
3521 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
Will Brockman4f0f9d22020-02-23 21:18:11 -05003522 r.getSbn().setInstanceId(mNotificationInstanceIdSequence.newInstanceId());
Julia Reynolds503ed942017-10-04 16:04:56 -04003523 mService.addNotification(r);
3524
Dieter Hsud39f0d52018-04-14 02:08:30 +08003525 final NotificationVisibility nv = NotificationVisibility.obtain(r.getKey(), 0, 1, true);
Julia Reynolds24edc002020-01-29 16:35:32 -05003526 mService.mNotificationDelegate.onNotificationClear(mUid, 0, PKG, r.getSbn().getTag(),
3527 r.getSbn().getId(), r.getUserId(), r.getKey(), NotificationStats.DISMISSAL_AOD,
Julia Reynoldsfd4099d2018-08-21 11:06:06 -04003528 NotificationStats.DISMISS_SENTIMENT_POSITIVE, nv);
Julia Reynolds503ed942017-10-04 16:04:56 -04003529 waitForIdle();
3530
3531 assertEquals(NotificationStats.DISMISSAL_AOD, r.getStats().getDismissalSurface());
Will Brockman75c60572020-01-31 10:30:27 -05003532
3533 // Using mService.addNotification() does not generate a NotificationRecordLogger log,
3534 // so we only get the cancel notification.
Will Brockman9918db92020-03-06 16:48:39 -05003535 assertEquals(1, mNotificationRecordLogger.numCalls());
Will Brockman75c60572020-01-31 10:30:27 -05003536
Will Brockman75c60572020-01-31 10:30:27 -05003537 assertEquals(
3538 NotificationRecordLogger.NotificationCancelledEvent.NOTIFICATION_CANCEL_USER_AOD,
Will Brockman9918db92020-03-06 16:48:39 -05003539 mNotificationRecordLogger.event(0));
Will Brockman4f0f9d22020-02-23 21:18:11 -05003540 assertEquals(1, mNotificationRecordLogger.get(0).getInstanceId());
Julia Reynolds503ed942017-10-04 16:04:56 -04003541 }
3542
3543 @Test
Julia Reynoldsfd4099d2018-08-21 11:06:06 -04003544 public void testStats_dismissalSentiment() throws Exception {
3545 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
3546 mService.addNotification(r);
3547
3548 final NotificationVisibility nv = NotificationVisibility.obtain(r.getKey(), 0, 1, true);
Julia Reynolds24edc002020-01-29 16:35:32 -05003549 mService.mNotificationDelegate.onNotificationClear(mUid, 0, PKG, r.getSbn().getTag(),
3550 r.getSbn().getId(), r.getUserId(), r.getKey(), NotificationStats.DISMISSAL_AOD,
Julia Reynoldsfd4099d2018-08-21 11:06:06 -04003551 NotificationStats.DISMISS_SENTIMENT_NEGATIVE, nv);
3552 waitForIdle();
3553
3554 assertEquals(NotificationStats.DISMISS_SENTIMENT_NEGATIVE,
3555 r.getStats().getDismissalSentiment());
3556 }
3557
3558 @Test
Julia Reynolds70aaea72018-07-13 13:38:34 -04003559 public void testApplyAdjustmentMultiUser() throws Exception {
Julia Reynolds503ed942017-10-04 16:04:56 -04003560 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
3561 mService.addNotification(r);
3562 NotificationManagerService.WorkerHandler handler = mock(
3563 NotificationManagerService.WorkerHandler.class);
3564 mService.setHandler(handler);
3565
Julia Reynolds70aaea72018-07-13 13:38:34 -04003566 when(mAssistants.isSameUser(eq(null), anyInt())).thenReturn(false);
3567
Julia Reynolds503ed942017-10-04 16:04:56 -04003568 Bundle signals = new Bundle();
3569 signals.putInt(Adjustment.KEY_USER_SENTIMENT,
Julia Reynolds70aaea72018-07-13 13:38:34 -04003570 USER_SENTIMENT_NEGATIVE);
3571 Adjustment adjustment = new Adjustment(
Julia Reynolds24edc002020-01-29 16:35:32 -05003572 r.getSbn().getPackageName(), r.getKey(), signals, "", r.getUser().getIdentifier());
Julia Reynolds70aaea72018-07-13 13:38:34 -04003573 mBinderService.applyAdjustmentFromAssistant(null, adjustment);
3574
3575 waitForIdle();
3576
3577 verify(handler, timeout(300).times(0)).scheduleSendRankingUpdate();
3578 }
3579
3580 @Test
Julia Reynolds27c0a962018-12-10 12:37:28 -05003581 public void testAssistantBlockingTriggersCancel() throws Exception {
Julia Reynoldsefcdff42018-08-09 09:42:56 -04003582 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
3583 mService.addNotification(r);
3584 NotificationManagerService.WorkerHandler handler = mock(
3585 NotificationManagerService.WorkerHandler.class);
3586 mService.setHandler(handler);
3587
3588 Bundle signals = new Bundle();
Julia Reynoldsc7dcdc22019-03-25 10:26:14 -04003589 signals.putInt(KEY_IMPORTANCE, IMPORTANCE_NONE);
Julia Reynoldsefcdff42018-08-09 09:42:56 -04003590 Adjustment adjustment = new Adjustment(
Julia Reynolds24edc002020-01-29 16:35:32 -05003591 r.getSbn().getPackageName(), r.getKey(), signals, "", r.getUser().getIdentifier());
Julia Reynoldsefcdff42018-08-09 09:42:56 -04003592 when(mAssistants.isSameUser(any(), anyInt())).thenReturn(true);
3593 mBinderService.applyAdjustmentFromAssistant(null, adjustment);
3594
3595 waitForIdle();
3596
3597 verify(handler, timeout(300).times(0)).scheduleSendRankingUpdate();
3598 verify(handler, times(1)).scheduleCancelNotification(any());
3599 }
3600
3601 @Test
Julia Reynolds70aaea72018-07-13 13:38:34 -04003602 public void testApplyEnqueuedAdjustmentFromAssistant_singleUser() throws Exception {
3603 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
3604 mService.addEnqueuedNotification(r);
3605 NotificationManagerService.WorkerHandler handler = mock(
3606 NotificationManagerService.WorkerHandler.class);
3607 mService.setHandler(handler);
3608 when(mAssistants.isSameUser(eq(null), anyInt())).thenReturn(true);
3609
3610 Bundle signals = new Bundle();
3611 signals.putInt(Adjustment.KEY_USER_SENTIMENT,
3612 USER_SENTIMENT_NEGATIVE);
3613 Adjustment adjustment = new Adjustment(
Julia Reynolds24edc002020-01-29 16:35:32 -05003614 r.getSbn().getPackageName(), r.getKey(), signals, "", r.getUser().getIdentifier());
Julia Reynolds70aaea72018-07-13 13:38:34 -04003615 mBinderService.applyEnqueuedAdjustmentFromAssistant(null, adjustment);
3616
3617 assertEquals(USER_SENTIMENT_NEGATIVE, r.getUserSentiment());
3618 }
3619
3620 @Test
Julia Reynoldsdc6adc62019-04-08 10:35:40 -04003621 public void testApplyEnqueuedAdjustmentFromAssistant_importance() throws Exception {
Julia Reynolds27c0a962018-12-10 12:37:28 -05003622 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
3623 mService.addEnqueuedNotification(r);
3624 NotificationManagerService.WorkerHandler handler = mock(
3625 NotificationManagerService.WorkerHandler.class);
3626 mService.setHandler(handler);
3627 when(mAssistants.isSameUser(eq(null), anyInt())).thenReturn(true);
3628
3629 Bundle signals = new Bundle();
Julia Reynoldsc7dcdc22019-03-25 10:26:14 -04003630 signals.putInt(KEY_IMPORTANCE, IMPORTANCE_LOW);
Julia Reynolds27c0a962018-12-10 12:37:28 -05003631 Adjustment adjustment = new Adjustment(
Julia Reynolds24edc002020-01-29 16:35:32 -05003632 r.getSbn().getPackageName(), r.getKey(), signals, "", r.getUser().getIdentifier());
Julia Reynolds27c0a962018-12-10 12:37:28 -05003633 mBinderService.applyEnqueuedAdjustmentFromAssistant(null, adjustment);
3634
3635 assertEquals(IMPORTANCE_LOW, r.getImportance());
3636 }
3637
3638 @Test
Julia Reynolds70aaea72018-07-13 13:38:34 -04003639 public void testApplyEnqueuedAdjustmentFromAssistant_crossUser() throws Exception {
3640 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
3641 mService.addEnqueuedNotification(r);
3642 NotificationManagerService.WorkerHandler handler = mock(
3643 NotificationManagerService.WorkerHandler.class);
3644 mService.setHandler(handler);
3645 when(mAssistants.isSameUser(eq(null), anyInt())).thenReturn(false);
3646
3647 Bundle signals = new Bundle();
3648 signals.putInt(Adjustment.KEY_USER_SENTIMENT,
3649 USER_SENTIMENT_NEGATIVE);
3650 Adjustment adjustment = new Adjustment(
Julia Reynolds24edc002020-01-29 16:35:32 -05003651 r.getSbn().getPackageName(), r.getKey(), signals, "", r.getUser().getIdentifier());
Julia Reynolds70aaea72018-07-13 13:38:34 -04003652 mBinderService.applyEnqueuedAdjustmentFromAssistant(null, adjustment);
3653
3654 assertEquals(USER_SENTIMENT_NEUTRAL, r.getUserSentiment());
3655
3656 waitForIdle();
3657
3658 verify(handler, timeout(300).times(0)).scheduleSendRankingUpdate();
3659 }
3660
3661 @Test
3662 public void testUserSentimentChangeTriggersUpdate() throws Exception {
3663 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
3664 mService.addNotification(r);
Julia Reynolds70aaea72018-07-13 13:38:34 -04003665 when(mAssistants.isSameUser(eq(null), anyInt())).thenReturn(true);
3666
3667 Bundle signals = new Bundle();
3668 signals.putInt(Adjustment.KEY_USER_SENTIMENT,
3669 USER_SENTIMENT_NEGATIVE);
Julia Reynolds503ed942017-10-04 16:04:56 -04003670 Adjustment adjustment = new Adjustment(
Julia Reynolds24edc002020-01-29 16:35:32 -05003671 r.getSbn().getPackageName(), r.getKey(), signals, "", r.getUser().getIdentifier());
Julia Reynolds503ed942017-10-04 16:04:56 -04003672 mBinderService.applyAdjustmentFromAssistant(null, adjustment);
3673
3674 waitForIdle();
3675
Julia Reynoldsb6c83742019-07-30 18:03:40 -04003676 verify(mRankingHandler, timeout(300).times(1)).requestSort();
Julia Reynolds503ed942017-10-04 16:04:56 -04003677 }
Julia Reynolds7bcb57b2018-01-22 10:37:58 -05003678
3679 @Test
Julia Reynolds666ccf02018-06-18 10:19:20 -04003680 public void testTooLateAdjustmentTriggersUpdate() throws Exception {
3681 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
3682 mService.addNotification(r);
Julia Reynolds70aaea72018-07-13 13:38:34 -04003683 when(mAssistants.isSameUser(eq(null), anyInt())).thenReturn(true);
Julia Reynolds666ccf02018-06-18 10:19:20 -04003684
3685 Bundle signals = new Bundle();
3686 signals.putInt(Adjustment.KEY_USER_SENTIMENT,
Julia Reynolds70aaea72018-07-13 13:38:34 -04003687 USER_SENTIMENT_NEGATIVE);
Julia Reynolds666ccf02018-06-18 10:19:20 -04003688 Adjustment adjustment = new Adjustment(
Julia Reynolds24edc002020-01-29 16:35:32 -05003689 r.getSbn().getPackageName(), r.getKey(), signals, "", r.getUser().getIdentifier());
Julia Reynolds666ccf02018-06-18 10:19:20 -04003690 mBinderService.applyEnqueuedAdjustmentFromAssistant(null, adjustment);
3691
3692 waitForIdle();
3693
Julia Reynoldsb6c83742019-07-30 18:03:40 -04003694 verify(mRankingHandler, times(1)).requestSort();
Julia Reynolds666ccf02018-06-18 10:19:20 -04003695 }
3696
3697 @Test
3698 public void testEnqueuedAdjustmentAppliesAdjustments() throws Exception {
3699 final NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
3700 mService.addEnqueuedNotification(r);
Julia Reynolds70aaea72018-07-13 13:38:34 -04003701 when(mAssistants.isSameUser(eq(null), anyInt())).thenReturn(true);
Julia Reynolds666ccf02018-06-18 10:19:20 -04003702
3703 Bundle signals = new Bundle();
3704 signals.putInt(Adjustment.KEY_USER_SENTIMENT,
Julia Reynolds70aaea72018-07-13 13:38:34 -04003705 USER_SENTIMENT_NEGATIVE);
Julia Reynolds666ccf02018-06-18 10:19:20 -04003706 Adjustment adjustment = new Adjustment(
Julia Reynolds24edc002020-01-29 16:35:32 -05003707 r.getSbn().getPackageName(), r.getKey(), signals, "", r.getUser().getIdentifier());
Julia Reynolds666ccf02018-06-18 10:19:20 -04003708 mBinderService.applyEnqueuedAdjustmentFromAssistant(null, adjustment);
3709
Julia Reynoldsb6c83742019-07-30 18:03:40 -04003710 assertEquals(USER_SENTIMENT_NEGATIVE, r.getUserSentiment());
Julia Reynolds666ccf02018-06-18 10:19:20 -04003711 }
3712
3713 @Test
Julia Reynoldsd78263d2018-01-30 10:40:41 -05003714 public void testRestore() throws Exception {
3715 int systemChecks = mService.countSystemChecks;
Julia Reynolds57a974b2019-10-07 11:51:47 -04003716 mBinderService.applyRestore(null, USER_SYSTEM);
Julia Reynoldsd78263d2018-01-30 10:40:41 -05003717 assertEquals(1, mService.countSystemChecks - systemChecks);
3718 }
3719
3720 @Test
Julia Reynolds469144c2019-06-21 14:30:28 -04003721 public void testBackupEmptySound() throws Exception {
3722 NotificationChannel channel = new NotificationChannel("a", "ab", IMPORTANCE_DEFAULT);
3723 channel.setSound(Uri.EMPTY, null);
3724
3725 XmlSerializer serializer = new FastXmlSerializer();
3726 ByteArrayOutputStream baos = new ByteArrayOutputStream();
3727 serializer.setOutput(new BufferedOutputStream(baos), "utf-8");
3728 channel.writeXmlForBackup(serializer, getContext());
3729
3730 XmlPullParser parser = Xml.newPullParser();
3731 parser.setInput(new BufferedInputStream(
3732 new ByteArrayInputStream(baos.toByteArray())), null);
3733 NotificationChannel restored = new NotificationChannel("a", "ab", IMPORTANCE_DEFAULT);
3734 restored.populateFromXmlForRestore(parser, getContext());
3735
3736 assertNull(restored.getSound());
3737 }
3738
3739 @Test
Julia Reynoldsd78263d2018-01-30 10:40:41 -05003740 public void testBackup() throws Exception {
3741 int systemChecks = mService.countSystemChecks;
Jay Aliomer4204f252019-08-26 11:36:53 -04003742 when(mListeners.queryPackageForServices(anyString(), anyInt(), anyInt()))
3743 .thenReturn(new ArraySet<>());
Julia Reynoldsd78263d2018-01-30 10:40:41 -05003744 mBinderService.getBackupPayload(1);
3745 assertEquals(1, mService.countSystemChecks - systemChecks);
3746 }
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003747
3748 @Test
Julia Reynolds469144c2019-06-21 14:30:28 -04003749 public void testEmptyVibration_noException() throws Exception {
3750 NotificationChannel channel = new NotificationChannel("a", "ab", IMPORTANCE_DEFAULT);
3751 channel.setVibrationPattern(new long[0]);
3752
3753 XmlSerializer serializer = new FastXmlSerializer();
3754 ByteArrayOutputStream baos = new ByteArrayOutputStream();
3755 serializer.setOutput(new BufferedOutputStream(baos), "utf-8");
3756 channel.writeXml(serializer);
3757 }
3758
3759 @Test
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003760 public void updateUriPermissions_update() throws Exception {
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003761 NotificationChannel c = new NotificationChannel(
Julia Reynolds27c0a962018-12-10 12:37:28 -05003762 TEST_CHANNEL_ID, TEST_CHANNEL_ID, IMPORTANCE_DEFAULT);
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003763 c.setSound(null, Notification.AUDIO_ATTRIBUTES_DEFAULT);
3764 Message message1 = new Message("", 0, "");
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003765 message1.setData("",
3766 ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 1));
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003767 Message message2 = new Message("", 1, "");
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003768 message2.setData("",
3769 ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 2));
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003770
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003771 Notification.Builder nbA = new Notification.Builder(mContext, c.getId())
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003772 .setContentTitle("foo")
3773 .setSmallIcon(android.R.drawable.sym_def_app_icon)
3774 .setStyle(new Notification.MessagingStyle("")
3775 .addMessage(message1)
3776 .addMessage(message2));
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003777 NotificationRecord recordA = new NotificationRecord(mContext, new StatusBarNotification(
3778 PKG, PKG, 0, "tag", mUid, 0, nbA.build(), new UserHandle(mUid), null, 0), c);
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003779
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003780 // First post means we grant access to both
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003781 reset(mUgm);
3782 reset(mUgmInternal);
3783 when(mUgmInternal.newUriPermissionOwner(any())).thenReturn(new Binder());
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003784 mService.updateUriPermissions(recordA, null, mContext.getPackageName(),
Julia Reynolds57a974b2019-10-07 11:51:47 -04003785 USER_SYSTEM);
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003786 verify(mUgm, times(1)).grantUriPermissionFromOwner(any(), anyInt(), any(),
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003787 eq(message1.getDataUri()), anyInt(), anyInt(), anyInt());
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003788 verify(mUgm, times(1)).grantUriPermissionFromOwner(any(), anyInt(), any(),
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003789 eq(message2.getDataUri()), anyInt(), anyInt(), anyInt());
3790
3791 Notification.Builder nbB = new Notification.Builder(mContext, c.getId())
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003792 .setContentTitle("foo")
3793 .setSmallIcon(android.R.drawable.sym_def_app_icon)
3794 .setStyle(new Notification.MessagingStyle("").addMessage(message2));
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003795 NotificationRecord recordB = new NotificationRecord(mContext, new StatusBarNotification(PKG,
3796 PKG, 0, "tag", mUid, 0, nbB.build(), new UserHandle(mUid), null, 0), c);
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003797
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003798 // Update means we drop access to first
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003799 reset(mUgmInternal);
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003800 mService.updateUriPermissions(recordB, recordA, mContext.getPackageName(),
Julia Reynolds57a974b2019-10-07 11:51:47 -04003801 USER_SYSTEM);
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003802 verify(mUgmInternal, times(1)).revokeUriPermissionFromOwner(any(),
3803 eq(message1.getDataUri()), anyInt(), anyInt());
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003804
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003805 // Update back means we grant access to first again
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003806 reset(mUgm);
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003807 mService.updateUriPermissions(recordA, recordB, mContext.getPackageName(),
Julia Reynolds57a974b2019-10-07 11:51:47 -04003808 USER_SYSTEM);
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003809 verify(mUgm, times(1)).grantUriPermissionFromOwner(any(), anyInt(), any(),
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003810 eq(message1.getDataUri()), anyInt(), anyInt(), anyInt());
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003811
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003812 // And update to empty means we drop everything
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003813 reset(mUgmInternal);
Jeff Sharkey6a97cc32018-04-17 12:16:20 -06003814 mService.updateUriPermissions(null, recordB, mContext.getPackageName(),
Julia Reynolds57a974b2019-10-07 11:51:47 -04003815 USER_SYSTEM);
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003816 verify(mUgmInternal, times(1)).revokeUriPermissionFromOwner(any(), eq(null),
Julia Reynoldse0d711f2017-09-01 08:50:47 -04003817 anyInt(), anyInt());
3818 }
Julia Reynoldsccc6ae62018-03-01 16:24:49 -05003819
3820 @Test
Julia Reynoldsea58c202020-02-03 12:52:49 -05003821 public void updateUriPermissions_posterDoesNotOwnUri() throws Exception {
3822 NotificationChannel c = new NotificationChannel(
3823 TEST_CHANNEL_ID, TEST_CHANNEL_ID, IMPORTANCE_DEFAULT);
3824 c.setSound(null, Notification.AUDIO_ATTRIBUTES_DEFAULT);
3825 Message message1 = new Message("", 0, "");
3826 message1.setData("",
3827 ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 1));
3828
3829 Notification.Builder nbA = new Notification.Builder(mContext, c.getId())
3830 .setContentTitle("foo")
3831 .setSmallIcon(android.R.drawable.sym_def_app_icon)
3832 .setStyle(new Notification.MessagingStyle("")
3833 .addMessage(message1));
3834 NotificationRecord recordA = new NotificationRecord(mContext, new StatusBarNotification(
3835 PKG, PKG, 0, "tag", mUid, 0, nbA.build(), new UserHandle(mUid), null, 0), c);
3836
3837 doThrow(new SecurityException("no access")).when(mUgm)
3838 .grantUriPermissionFromOwner(
3839 any(), anyInt(), any(), any(), anyInt(), anyInt(), anyInt());
3840
3841 when(mUgmInternal.newUriPermissionOwner(any())).thenReturn(new Binder());
3842 mService.updateUriPermissions(recordA, null, mContext.getPackageName(), USER_SYSTEM);
3843
3844 // yay, no crash
3845 }
3846
3847 @Test
Robin Leed107af62018-04-27 13:55:56 +02003848 public void testVisitUris() throws Exception {
3849 final Uri audioContents = Uri.parse("content://com.example/audio");
3850 final Uri backgroundImage = Uri.parse("content://com.example/background");
3851
3852 Bundle extras = new Bundle();
3853 extras.putParcelable(Notification.EXTRA_AUDIO_CONTENTS_URI, audioContents);
3854 extras.putString(Notification.EXTRA_BACKGROUND_IMAGE_URI, backgroundImage.toString());
3855
3856 Notification n = new Notification.Builder(mContext, "a")
3857 .setContentTitle("notification with uris")
3858 .setSmallIcon(android.R.drawable.sym_def_app_icon)
3859 .addExtras(extras)
3860 .build();
3861
3862 Consumer<Uri> visitor = (Consumer<Uri>) spy(Consumer.class);
3863 n.visitUris(visitor);
3864 verify(visitor, times(1)).accept(eq(audioContents));
3865 verify(visitor, times(1)).accept(eq(backgroundImage));
3866 }
3867
3868 @Test
Julia Reynoldsccc6ae62018-03-01 16:24:49 -05003869 public void testSetNotificationPolicy_preP_setOldFields() {
3870 ZenModeHelper mZenModeHelper = mock(ZenModeHelper.class);
3871 mService.mZenModeHelper = mZenModeHelper;
3872 NotificationManager.Policy userPolicy =
3873 new NotificationManager.Policy(0, 0, 0, SUPPRESSED_EFFECT_BADGE);
3874 when(mZenModeHelper.getNotificationPolicy()).thenReturn(userPolicy);
3875
3876 NotificationManager.Policy appPolicy = new NotificationManager.Policy(0, 0, 0,
3877 SUPPRESSED_EFFECT_SCREEN_ON | SUPPRESSED_EFFECT_SCREEN_OFF);
3878
3879 int expected = SUPPRESSED_EFFECT_BADGE
3880 | SUPPRESSED_EFFECT_SCREEN_ON | SUPPRESSED_EFFECT_SCREEN_OFF
Julia Reynoldseac2da22018-04-12 10:48:46 -04003881 | SUPPRESSED_EFFECT_PEEK | SUPPRESSED_EFFECT_LIGHTS
3882 | SUPPRESSED_EFFECT_FULL_SCREEN_INTENT;
Julia Reynoldsccc6ae62018-03-01 16:24:49 -05003883 int actual = mService.calculateSuppressedVisualEffects(appPolicy, userPolicy, O_MR1);
3884
3885 assertEquals(expected, actual);
3886 }
3887
3888 @Test
3889 public void testSetNotificationPolicy_preP_setNewFields() {
3890 ZenModeHelper mZenModeHelper = mock(ZenModeHelper.class);
3891 mService.mZenModeHelper = mZenModeHelper;
3892 NotificationManager.Policy userPolicy =
3893 new NotificationManager.Policy(0, 0, 0, SUPPRESSED_EFFECT_BADGE);
3894 when(mZenModeHelper.getNotificationPolicy()).thenReturn(userPolicy);
3895
3896 NotificationManager.Policy appPolicy = new NotificationManager.Policy(0, 0, 0,
3897 SUPPRESSED_EFFECT_NOTIFICATION_LIST);
3898
3899 int expected = SUPPRESSED_EFFECT_BADGE;
3900 int actual = mService.calculateSuppressedVisualEffects(appPolicy, userPolicy, O_MR1);
3901
3902 assertEquals(expected, actual);
3903 }
3904
3905 @Test
3906 public void testSetNotificationPolicy_preP_setOldNewFields() {
3907 ZenModeHelper mZenModeHelper = mock(ZenModeHelper.class);
3908 mService.mZenModeHelper = mZenModeHelper;
3909 NotificationManager.Policy userPolicy =
3910 new NotificationManager.Policy(0, 0, 0, SUPPRESSED_EFFECT_BADGE);
3911 when(mZenModeHelper.getNotificationPolicy()).thenReturn(userPolicy);
3912
3913 NotificationManager.Policy appPolicy = new NotificationManager.Policy(0, 0, 0,
3914 SUPPRESSED_EFFECT_SCREEN_ON | SUPPRESSED_EFFECT_STATUS_BAR);
3915
3916 int expected =
3917 SUPPRESSED_EFFECT_BADGE | SUPPRESSED_EFFECT_SCREEN_ON | SUPPRESSED_EFFECT_PEEK;
3918 int actual = mService.calculateSuppressedVisualEffects(appPolicy, userPolicy, O_MR1);
3919
3920 assertEquals(expected, actual);
3921 }
3922
3923 @Test
3924 public void testSetNotificationPolicy_P_setOldFields() {
3925 ZenModeHelper mZenModeHelper = mock(ZenModeHelper.class);
3926 mService.mZenModeHelper = mZenModeHelper;
3927 NotificationManager.Policy userPolicy =
3928 new NotificationManager.Policy(0, 0, 0, SUPPRESSED_EFFECT_BADGE);
3929 when(mZenModeHelper.getNotificationPolicy()).thenReturn(userPolicy);
3930
3931 NotificationManager.Policy appPolicy = new NotificationManager.Policy(0, 0, 0,
3932 SUPPRESSED_EFFECT_SCREEN_ON | SUPPRESSED_EFFECT_SCREEN_OFF);
3933
3934 int expected = SUPPRESSED_EFFECT_SCREEN_ON | SUPPRESSED_EFFECT_SCREEN_OFF
3935 | SUPPRESSED_EFFECT_PEEK | SUPPRESSED_EFFECT_AMBIENT
3936 | SUPPRESSED_EFFECT_LIGHTS | SUPPRESSED_EFFECT_FULL_SCREEN_INTENT;
3937 int actual = mService.calculateSuppressedVisualEffects(appPolicy, userPolicy, P);
3938
3939 assertEquals(expected, actual);
3940 }
3941
3942 @Test
3943 public void testSetNotificationPolicy_P_setNewFields() {
3944 ZenModeHelper mZenModeHelper = mock(ZenModeHelper.class);
3945 mService.mZenModeHelper = mZenModeHelper;
3946 NotificationManager.Policy userPolicy =
3947 new NotificationManager.Policy(0, 0, 0, SUPPRESSED_EFFECT_BADGE);
3948 when(mZenModeHelper.getNotificationPolicy()).thenReturn(userPolicy);
3949
3950 NotificationManager.Policy appPolicy = new NotificationManager.Policy(0, 0, 0,
3951 SUPPRESSED_EFFECT_NOTIFICATION_LIST | SUPPRESSED_EFFECT_AMBIENT
3952 | SUPPRESSED_EFFECT_LIGHTS | SUPPRESSED_EFFECT_FULL_SCREEN_INTENT);
3953
3954 int expected = SUPPRESSED_EFFECT_NOTIFICATION_LIST | SUPPRESSED_EFFECT_SCREEN_OFF
3955 | SUPPRESSED_EFFECT_AMBIENT | SUPPRESSED_EFFECT_LIGHTS
3956 | SUPPRESSED_EFFECT_FULL_SCREEN_INTENT;
3957 int actual = mService.calculateSuppressedVisualEffects(appPolicy, userPolicy, P);
3958
3959 assertEquals(expected, actual);
3960 }
3961
3962 @Test
3963 public void testSetNotificationPolicy_P_setOldNewFields() {
3964 ZenModeHelper mZenModeHelper = mock(ZenModeHelper.class);
3965 mService.mZenModeHelper = mZenModeHelper;
3966 NotificationManager.Policy userPolicy =
3967 new NotificationManager.Policy(0, 0, 0, SUPPRESSED_EFFECT_BADGE);
3968 when(mZenModeHelper.getNotificationPolicy()).thenReturn(userPolicy);
3969
3970 NotificationManager.Policy appPolicy = new NotificationManager.Policy(0, 0, 0,
3971 SUPPRESSED_EFFECT_SCREEN_ON | SUPPRESSED_EFFECT_STATUS_BAR);
3972
3973 int expected = SUPPRESSED_EFFECT_STATUS_BAR;
3974 int actual = mService.calculateSuppressedVisualEffects(appPolicy, userPolicy, P);
3975
3976 assertEquals(expected, actual);
3977
3978 appPolicy = new NotificationManager.Policy(0, 0, 0,
3979 SUPPRESSED_EFFECT_SCREEN_ON | SUPPRESSED_EFFECT_AMBIENT
3980 | SUPPRESSED_EFFECT_LIGHTS | SUPPRESSED_EFFECT_FULL_SCREEN_INTENT);
3981
3982 expected = SUPPRESSED_EFFECT_SCREEN_OFF | SUPPRESSED_EFFECT_AMBIENT
3983 | SUPPRESSED_EFFECT_LIGHTS | SUPPRESSED_EFFECT_FULL_SCREEN_INTENT;
3984 actual = mService.calculateSuppressedVisualEffects(appPolicy, userPolicy, P);
3985
3986 assertEquals(expected, actual);
3987 }
Julia Reynolds7217dc92018-03-07 12:12:09 -05003988
3989 @Test
Julia Reynoldse5c60452018-04-30 14:41:36 -04003990 public void testVisualDifference_foreground() {
3991 Notification.Builder nb1 = new Notification.Builder(mContext, "")
3992 .setContentTitle("foo");
3993 StatusBarNotification sbn1 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
3994 nb1.build(), new UserHandle(mUid), null, 0);
3995 NotificationRecord r1 =
3996 new NotificationRecord(mContext, sbn1, mock(NotificationChannel.class));
3997
3998 Notification.Builder nb2 = new Notification.Builder(mContext, "")
3999 .setFlag(FLAG_FOREGROUND_SERVICE, true)
4000 .setContentTitle("bar");
4001 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4002 nb2.build(), new UserHandle(mUid), null, 0);
4003 NotificationRecord r2 =
4004 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
4005
4006 assertFalse(mService.isVisuallyInterruptive(r1, r2));
4007 }
4008
4009 @Test
Julia Reynolds7217dc92018-03-07 12:12:09 -05004010 public void testVisualDifference_diffTitle() {
4011 Notification.Builder nb1 = new Notification.Builder(mContext, "")
4012 .setContentTitle("foo");
4013 StatusBarNotification sbn1 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4014 nb1.build(), new UserHandle(mUid), null, 0);
4015 NotificationRecord r1 =
4016 new NotificationRecord(mContext, sbn1, mock(NotificationChannel.class));
4017
4018 Notification.Builder nb2 = new Notification.Builder(mContext, "")
4019 .setContentTitle("bar");
4020 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4021 nb2.build(), new UserHandle(mUid), null, 0);
4022 NotificationRecord r2 =
4023 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
4024
4025 assertTrue(mService.isVisuallyInterruptive(r1, r2));
4026 }
4027
4028 @Test
Dan Sandler7d67bd42018-05-15 14:06:38 -04004029 public void testVisualDifference_inboxStyle() {
4030 Notification.Builder nb1 = new Notification.Builder(mContext, "")
4031 .setStyle(new Notification.InboxStyle()
4032 .addLine("line1").addLine("line2"));
4033 StatusBarNotification sbn1 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4034 nb1.build(), new UserHandle(mUid), null, 0);
4035 NotificationRecord r1 =
4036 new NotificationRecord(mContext, sbn1, mock(NotificationChannel.class));
4037
4038 Notification.Builder nb2 = new Notification.Builder(mContext, "")
4039 .setStyle(new Notification.InboxStyle()
4040 .addLine("line1").addLine("line2_changed"));
4041 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4042 nb2.build(), new UserHandle(mUid), null, 0);
4043 NotificationRecord r2 =
4044 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
4045
4046 assertTrue(mService.isVisuallyInterruptive(r1, r2)); // line 2 changed unnoticed
4047
4048 Notification.Builder nb3 = new Notification.Builder(mContext, "")
4049 .setStyle(new Notification.InboxStyle()
4050 .addLine("line1"));
4051 StatusBarNotification sbn3 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4052 nb3.build(), new UserHandle(mUid), null, 0);
4053 NotificationRecord r3 =
4054 new NotificationRecord(mContext, sbn3, mock(NotificationChannel.class));
4055
4056 assertTrue(mService.isVisuallyInterruptive(r1, r3)); // line 2 removed unnoticed
4057
4058 Notification.Builder nb4 = new Notification.Builder(mContext, "")
4059 .setStyle(new Notification.InboxStyle()
4060 .addLine("line1").addLine("line2").addLine("line3"));
4061 StatusBarNotification sbn4 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4062 nb4.build(), new UserHandle(mUid), null, 0);
4063 NotificationRecord r4 =
4064 new NotificationRecord(mContext, sbn4, mock(NotificationChannel.class));
4065
4066 assertTrue(mService.isVisuallyInterruptive(r1, r4)); // line 3 added unnoticed
4067
4068 Notification.Builder nb5 = new Notification.Builder(mContext, "")
4069 .setContentText("not an inbox");
4070 StatusBarNotification sbn5 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4071 nb5.build(), new UserHandle(mUid), null, 0);
4072 NotificationRecord r5 =
4073 new NotificationRecord(mContext, sbn5, mock(NotificationChannel.class));
4074
4075 assertTrue(mService.isVisuallyInterruptive(r1, r5)); // changed Styles, went unnoticed
4076 }
4077
4078 @Test
Julia Reynolds7217dc92018-03-07 12:12:09 -05004079 public void testVisualDifference_diffText() {
4080 Notification.Builder nb1 = new Notification.Builder(mContext, "")
4081 .setContentText("foo");
4082 StatusBarNotification sbn1 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4083 nb1.build(), new UserHandle(mUid), null, 0);
4084 NotificationRecord r1 =
4085 new NotificationRecord(mContext, sbn1, mock(NotificationChannel.class));
4086
4087 Notification.Builder nb2 = new Notification.Builder(mContext, "")
4088 .setContentText("bar");
4089 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4090 nb2.build(), new UserHandle(mUid), null, 0);
4091 NotificationRecord r2 =
4092 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
4093
4094 assertTrue(mService.isVisuallyInterruptive(r1, r2));
4095 }
4096
4097 @Test
Dan Sandler7d67bd42018-05-15 14:06:38 -04004098 public void testVisualDifference_sameText() {
4099 Notification.Builder nb1 = new Notification.Builder(mContext, "")
4100 .setContentText("foo");
4101 StatusBarNotification sbn1 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4102 nb1.build(), new UserHandle(mUid), null, 0);
4103 NotificationRecord r1 =
4104 new NotificationRecord(mContext, sbn1, mock(NotificationChannel.class));
4105
4106 Notification.Builder nb2 = new Notification.Builder(mContext, "")
4107 .setContentText("foo");
4108 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4109 nb2.build(), new UserHandle(mUid), null, 0);
4110 NotificationRecord r2 =
4111 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
4112
4113 assertFalse(mService.isVisuallyInterruptive(r1, r2));
4114 }
4115
4116 @Test
4117 public void testVisualDifference_sameTextButStyled() {
4118 Notification.Builder nb1 = new Notification.Builder(mContext, "")
4119 .setContentText(Html.fromHtml("<b>foo</b>"));
4120 StatusBarNotification sbn1 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4121 nb1.build(), new UserHandle(mUid), null, 0);
4122 NotificationRecord r1 =
4123 new NotificationRecord(mContext, sbn1, mock(NotificationChannel.class));
4124
4125 Notification.Builder nb2 = new Notification.Builder(mContext, "")
4126 .setContentText(Html.fromHtml("<b>foo</b>"));
4127 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4128 nb2.build(), new UserHandle(mUid), null, 0);
4129 NotificationRecord r2 =
4130 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
4131
4132 assertFalse(mService.isVisuallyInterruptive(r1, r2));
4133 }
4134
4135 @Test
4136 public void testVisualDifference_diffTextButStyled() {
4137 Notification.Builder nb1 = new Notification.Builder(mContext, "")
4138 .setContentText(Html.fromHtml("<b>foo</b>"));
4139 StatusBarNotification sbn1 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4140 nb1.build(), new UserHandle(mUid), null, 0);
4141 NotificationRecord r1 =
4142 new NotificationRecord(mContext, sbn1, mock(NotificationChannel.class));
4143
4144 Notification.Builder nb2 = new Notification.Builder(mContext, "")
4145 .setContentText(Html.fromHtml("<b>bar</b>"));
4146 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4147 nb2.build(), new UserHandle(mUid), null, 0);
4148 NotificationRecord r2 =
4149 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
4150
4151 assertTrue(mService.isVisuallyInterruptive(r1, r2));
4152 }
4153
4154 @Test
Julia Reynolds7217dc92018-03-07 12:12:09 -05004155 public void testVisualDifference_diffProgress() {
4156 Notification.Builder nb1 = new Notification.Builder(mContext, "")
4157 .setProgress(100, 90, false);
4158 StatusBarNotification sbn1 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4159 nb1.build(), new UserHandle(mUid), null, 0);
4160 NotificationRecord r1 =
4161 new NotificationRecord(mContext, sbn1, mock(NotificationChannel.class));
4162
4163 Notification.Builder nb2 = new Notification.Builder(mContext, "")
4164 .setProgress(100, 100, false);
4165 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4166 nb2.build(), new UserHandle(mUid), null, 0);
4167 NotificationRecord r2 =
4168 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
4169
4170 assertTrue(mService.isVisuallyInterruptive(r1, r2));
4171 }
4172
4173 @Test
4174 public void testVisualDifference_diffProgressNotDone() {
4175 Notification.Builder nb1 = new Notification.Builder(mContext, "")
4176 .setProgress(100, 90, false);
4177 StatusBarNotification sbn1 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4178 nb1.build(), new UserHandle(mUid), null, 0);
4179 NotificationRecord r1 =
4180 new NotificationRecord(mContext, sbn1, mock(NotificationChannel.class));
4181
4182 Notification.Builder nb2 = new Notification.Builder(mContext, "")
4183 .setProgress(100, 91, false);
4184 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4185 nb2.build(), new UserHandle(mUid), null, 0);
4186 NotificationRecord r2 =
4187 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
4188
4189 assertFalse(mService.isVisuallyInterruptive(r1, r2));
4190 }
Beverly5a20a5e2018-03-06 15:02:44 -05004191
4192 @Test
Dan Sandler7d67bd42018-05-15 14:06:38 -04004193 public void testVisualDifference_sameProgressStillDone() {
4194 Notification.Builder nb1 = new Notification.Builder(mContext, "")
4195 .setProgress(100, 100, false);
4196 StatusBarNotification sbn1 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4197 nb1.build(), new UserHandle(mUid), null, 0);
4198 NotificationRecord r1 =
4199 new NotificationRecord(mContext, sbn1, mock(NotificationChannel.class));
4200
4201 Notification.Builder nb2 = new Notification.Builder(mContext, "")
4202 .setProgress(100, 100, false);
4203 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4204 nb2.build(), new UserHandle(mUid), null, 0);
4205 NotificationRecord r2 =
4206 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
4207
4208 assertFalse(mService.isVisuallyInterruptive(r1, r2));
4209 }
4210
4211 @Test
Julia Reynoldsa4fb9da2018-06-04 12:27:58 -04004212 public void testVisualDifference_summary() {
4213 Notification.Builder nb1 = new Notification.Builder(mContext, "")
4214 .setGroup("bananas")
4215 .setFlag(Notification.FLAG_GROUP_SUMMARY, true)
4216 .setContentText("foo");
4217 StatusBarNotification sbn1 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4218 nb1.build(), new UserHandle(mUid), null, 0);
4219 NotificationRecord r1 =
4220 new NotificationRecord(mContext, sbn1, mock(NotificationChannel.class));
4221
4222 Notification.Builder nb2 = new Notification.Builder(mContext, "")
4223 .setGroup("bananas")
4224 .setFlag(Notification.FLAG_GROUP_SUMMARY, true)
4225 .setContentText("bar");
4226 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4227 nb2.build(), new UserHandle(mUid), null, 0);
4228 NotificationRecord r2 =
4229 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
4230
4231 assertFalse(mService.isVisuallyInterruptive(r1, r2));
4232 }
4233
4234 @Test
Julia Reynolds760fa762018-06-19 15:39:23 -04004235 public void testVisualDifference_summaryNewNotification() {
4236 Notification.Builder nb2 = new Notification.Builder(mContext, "")
4237 .setGroup("bananas")
4238 .setFlag(Notification.FLAG_GROUP_SUMMARY, true)
4239 .setContentText("bar");
4240 StatusBarNotification sbn2 = new StatusBarNotification(PKG, PKG, 0, "tag", mUid, 0,
4241 nb2.build(), new UserHandle(mUid), null, 0);
4242 NotificationRecord r2 =
4243 new NotificationRecord(mContext, sbn2, mock(NotificationChannel.class));
4244
4245 assertFalse(mService.isVisuallyInterruptive(null, r2));
4246 }
4247
4248 @Test
Beverly5a20a5e2018-03-06 15:02:44 -05004249 public void testHideAndUnhideNotificationsOnSuspendedPackageBroadcast() {
4250 // post 2 notification from this package
4251 final NotificationRecord notif1 = generateNotificationRecord(
4252 mTestNotificationChannel, 1, null, true);
4253 final NotificationRecord notif2 = generateNotificationRecord(
4254 mTestNotificationChannel, 2, null, false);
4255 mService.addNotification(notif1);
4256 mService.addNotification(notif2);
4257
4258 // on broadcast, hide the 2 notifications
4259 mService.simulatePackageSuspendBroadcast(true, PKG);
4260 ArgumentCaptor<List> captorHide = ArgumentCaptor.forClass(List.class);
4261 verify(mListeners, times(1)).notifyHiddenLocked(captorHide.capture());
4262 assertEquals(2, captorHide.getValue().size());
4263
4264 // on broadcast, unhide the 2 notifications
4265 mService.simulatePackageSuspendBroadcast(false, PKG);
4266 ArgumentCaptor<List> captorUnhide = ArgumentCaptor.forClass(List.class);
4267 verify(mListeners, times(1)).notifyUnhiddenLocked(captorUnhide.capture());
4268 assertEquals(2, captorUnhide.getValue().size());
4269 }
4270
4271 @Test
4272 public void testNoNotificationsHiddenOnSuspendedPackageBroadcast() {
4273 // post 2 notification from this package
4274 final NotificationRecord notif1 = generateNotificationRecord(
4275 mTestNotificationChannel, 1, null, true);
4276 final NotificationRecord notif2 = generateNotificationRecord(
4277 mTestNotificationChannel, 2, null, false);
4278 mService.addNotification(notif1);
4279 mService.addNotification(notif2);
4280
4281 // on broadcast, nothing is hidden since no notifications are of package "test_package"
4282 mService.simulatePackageSuspendBroadcast(true, "test_package");
4283 ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class);
4284 verify(mListeners, times(1)).notifyHiddenLocked(captor.capture());
4285 assertEquals(0, captor.getValue().size());
4286 }
Kristian Monsen05f34792018-04-09 10:27:16 +02004287
4288 @Test
Julia Reynolds0e5a3432019-01-17 09:40:46 -05004289 public void testHideAndUnhideNotificationsOnDistractingPackageBroadcast() {
4290 // Post 2 notifications from 2 packages
4291 NotificationRecord pkgA = new NotificationRecord(mContext,
4292 generateSbn("a", 1000, 9, 0), mTestNotificationChannel);
4293 mService.addNotification(pkgA);
4294 NotificationRecord pkgB = new NotificationRecord(mContext,
4295 generateSbn("b", 1001, 9, 0), mTestNotificationChannel);
4296 mService.addNotification(pkgB);
4297
4298 // on broadcast, hide one of the packages
4299 mService.simulatePackageDistractionBroadcast(
4300 PackageManager.RESTRICTION_HIDE_NOTIFICATIONS, new String[] {"a"});
4301 ArgumentCaptor<List<NotificationRecord>> captorHide = ArgumentCaptor.forClass(List.class);
4302 verify(mListeners, times(1)).notifyHiddenLocked(captorHide.capture());
4303 assertEquals(1, captorHide.getValue().size());
Julia Reynolds24edc002020-01-29 16:35:32 -05004304 assertEquals("a", captorHide.getValue().get(0).getSbn().getPackageName());
Julia Reynolds0e5a3432019-01-17 09:40:46 -05004305
4306 // on broadcast, unhide the package
4307 mService.simulatePackageDistractionBroadcast(
4308 PackageManager.RESTRICTION_HIDE_FROM_SUGGESTIONS, new String[] {"a"});
4309 ArgumentCaptor<List<NotificationRecord>> captorUnhide = ArgumentCaptor.forClass(List.class);
4310 verify(mListeners, times(1)).notifyUnhiddenLocked(captorUnhide.capture());
4311 assertEquals(1, captorUnhide.getValue().size());
Julia Reynolds24edc002020-01-29 16:35:32 -05004312 assertEquals("a", captorUnhide.getValue().get(0).getSbn().getPackageName());
Julia Reynolds0e5a3432019-01-17 09:40:46 -05004313 }
4314
4315 @Test
4316 public void testHideAndUnhideNotificationsOnDistractingPackageBroadcast_multiPkg() {
4317 // Post 2 notifications from 2 packages
4318 NotificationRecord pkgA = new NotificationRecord(mContext,
4319 generateSbn("a", 1000, 9, 0), mTestNotificationChannel);
4320 mService.addNotification(pkgA);
4321 NotificationRecord pkgB = new NotificationRecord(mContext,
4322 generateSbn("b", 1001, 9, 0), mTestNotificationChannel);
4323 mService.addNotification(pkgB);
4324
4325 // on broadcast, hide one of the packages
4326 mService.simulatePackageDistractionBroadcast(
4327 PackageManager.RESTRICTION_HIDE_NOTIFICATIONS, new String[] {"a", "b"});
4328 ArgumentCaptor<List<NotificationRecord>> captorHide = ArgumentCaptor.forClass(List.class);
woongki minbbc97282019-09-25 11:50:48 +09004329
4330 // should be called only once.
4331 verify(mListeners, times(1)).notifyHiddenLocked(captorHide.capture());
Julia Reynolds0e5a3432019-01-17 09:40:46 -05004332 assertEquals(2, captorHide.getValue().size());
Julia Reynolds24edc002020-01-29 16:35:32 -05004333 assertEquals("a", captorHide.getValue().get(0).getSbn().getPackageName());
4334 assertEquals("b", captorHide.getValue().get(1).getSbn().getPackageName());
Julia Reynolds0e5a3432019-01-17 09:40:46 -05004335
4336 // on broadcast, unhide the package
4337 mService.simulatePackageDistractionBroadcast(
4338 PackageManager.RESTRICTION_HIDE_FROM_SUGGESTIONS, new String[] {"a", "b"});
4339 ArgumentCaptor<List<NotificationRecord>> captorUnhide = ArgumentCaptor.forClass(List.class);
woongki minbbc97282019-09-25 11:50:48 +09004340
4341 // should be called only once.
4342 verify(mListeners, times(1)).notifyUnhiddenLocked(captorUnhide.capture());
Julia Reynolds0e5a3432019-01-17 09:40:46 -05004343 assertEquals(2, captorUnhide.getValue().size());
Julia Reynolds24edc002020-01-29 16:35:32 -05004344 assertEquals("a", captorUnhide.getValue().get(0).getSbn().getPackageName());
4345 assertEquals("b", captorUnhide.getValue().get(1).getSbn().getPackageName());
Julia Reynolds0e5a3432019-01-17 09:40:46 -05004346 }
4347
4348 @Test
4349 public void testNoNotificationsHiddenOnDistractingPackageBroadcast() {
4350 // post notification from this package
4351 final NotificationRecord notif1 = generateNotificationRecord(
4352 mTestNotificationChannel, 1, null, true);
4353 mService.addNotification(notif1);
4354
4355 // on broadcast, nothing is hidden since no notifications are of package "test_package"
4356 mService.simulatePackageDistractionBroadcast(
4357 PackageManager.RESTRICTION_HIDE_NOTIFICATIONS, new String[] {"test_package"});
4358 ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class);
4359 verify(mListeners, times(1)).notifyHiddenLocked(captor.capture());
4360 assertEquals(0, captor.getValue().size());
4361 }
4362
4363 @Test
Rajeev Kumarbc79dcd2020-02-04 19:54:30 -08004364 public void testCanUseManagedServicesNullPkg() {
4365 assertEquals(true, mService.canUseManagedServices(null, 0, null));
Kristian Monsen05f34792018-04-09 10:27:16 +02004366 }
4367
Kristian Monsen05f34792018-04-09 10:27:16 +02004368
4369 @Test
Rajeev Kumarbc79dcd2020-02-04 19:54:30 -08004370 public void testCanUseManagedServicesNoValidPkg() {
Julia Reynoldsd0ceefa2019-03-03 16:10:52 -05004371 assertEquals(true, mService.canUseManagedServices("d", 0, null));
4372 }
4373
4374 @Test
4375 public void testCanUseManagedServices_hasPermission() throws Exception {
4376 when(mPackageManager.checkPermission("perm", "pkg", 0))
4377 .thenReturn(PackageManager.PERMISSION_GRANTED);
4378
4379 assertEquals(true, mService.canUseManagedServices("pkg", 0, "perm"));
4380 }
4381
4382 @Test
4383 public void testCanUseManagedServices_noPermission() throws Exception {
4384 when(mPackageManager.checkPermission("perm", "pkg", 0))
4385 .thenReturn(PackageManager.PERMISSION_DENIED);
4386
4387 assertEquals(false, mService.canUseManagedServices("pkg", 0, "perm"));
4388 }
4389
4390 @Test
4391 public void testCanUseManagedServices_permDoesNotMatter() {
4392 assertEquals(true, mService.canUseManagedServices("pkg", 0, null));
Kristian Monsen05f34792018-04-09 10:27:16 +02004393 }
Julia Reynoldsb3c68ff2018-05-22 14:58:39 -04004394
4395 @Test
4396 public void testOnNotificationVisibilityChanged_triggersInterruptionUsageStat() {
4397 final NotificationRecord r = generateNotificationRecord(
4398 mTestNotificationChannel, 1, null, true);
4399 r.setTextChanged(true);
4400 mService.addNotification(r);
4401
4402 mService.mNotificationDelegate.onNotificationVisibilityChanged(new NotificationVisibility[]
4403 {NotificationVisibility.obtain(r.getKey(), 1, 1, true)},
4404 new NotificationVisibility[]{});
4405
4406 verify(mAppUsageStats).reportInterruptiveNotification(anyString(), anyString(), anyInt());
4407 }
4408
4409 @Test
Will Brockmand3d49332020-02-10 19:43:03 -05004410 public void testOnNotificationVisibilityChanged_triggersVisibilityLog() {
4411 final NotificationRecord r = generateNotificationRecord(
4412 mTestNotificationChannel, 1, null, true);
4413 r.setTextChanged(true);
Will Brockman4f0f9d22020-02-23 21:18:11 -05004414 r.getSbn().setInstanceId(mNotificationInstanceIdSequence.newInstanceId());
Will Brockmand3d49332020-02-10 19:43:03 -05004415 mService.addNotification(r);
4416
4417 mService.mNotificationDelegate.onNotificationVisibilityChanged(new NotificationVisibility[]
4418 {NotificationVisibility.obtain(r.getKey(), 1, 1, true)},
4419 new NotificationVisibility[]{});
4420
Will Brockman9918db92020-03-06 16:48:39 -05004421 assertEquals(1, mNotificationRecordLogger.numCalls());
Will Brockmand3d49332020-02-10 19:43:03 -05004422 assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_OPEN,
Will Brockman9918db92020-03-06 16:48:39 -05004423 mNotificationRecordLogger.event(0));
Will Brockman4f0f9d22020-02-23 21:18:11 -05004424 assertEquals(1, mNotificationRecordLogger.get(0).getInstanceId());
Will Brockmand3d49332020-02-10 19:43:03 -05004425
4426 mService.mNotificationDelegate.onNotificationVisibilityChanged(
4427 new NotificationVisibility[]{},
4428 new NotificationVisibility[]
4429 {NotificationVisibility.obtain(r.getKey(), 1, 1, true)}
4430 );
4431
Will Brockman9918db92020-03-06 16:48:39 -05004432 assertEquals(2, mNotificationRecordLogger.numCalls());
Will Brockmand3d49332020-02-10 19:43:03 -05004433 assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_CLOSE,
Will Brockman9918db92020-03-06 16:48:39 -05004434 mNotificationRecordLogger.event(1));
Will Brockman4f0f9d22020-02-23 21:18:11 -05004435 assertEquals(1, mNotificationRecordLogger.get(1).getInstanceId());
Will Brockmand3d49332020-02-10 19:43:03 -05004436 }
4437
4438 @Test
Julia Reynoldsb3c68ff2018-05-22 14:58:39 -04004439 public void testSetNotificationsShownFromListener_triggersInterruptionUsageStat()
4440 throws RemoteException {
4441 final NotificationRecord r = generateNotificationRecord(
4442 mTestNotificationChannel, 1, null, true);
4443 r.setTextChanged(true);
4444 mService.addNotification(r);
4445
4446 mBinderService.setNotificationsShownFromListener(null, new String[] {r.getKey()});
4447
4448 verify(mAppUsageStats).reportInterruptiveNotification(anyString(), anyString(), anyInt());
4449 }
4450
4451 @Test
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04004452 public void testMaybeRecordInterruptionLocked_doesNotRecordTwice()
Julia Reynoldsb3c68ff2018-05-22 14:58:39 -04004453 throws RemoteException {
4454 final NotificationRecord r = generateNotificationRecord(
4455 mTestNotificationChannel, 1, null, true);
4456 r.setInterruptive(true);
4457 mService.addNotification(r);
4458
4459 mService.maybeRecordInterruptionLocked(r);
4460 mService.maybeRecordInterruptionLocked(r);
4461
4462 verify(mAppUsageStats, times(1)).reportInterruptiveNotification(
4463 anyString(), anyString(), anyInt());
Julia Reynoldsfd9f8342020-03-06 09:36:00 -05004464 verify(mHistoryManager, times(1)).addNotification(any());
Julia Reynoldsb3c68ff2018-05-22 14:58:39 -04004465 }
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04004466
4467 @Test
Mady Mellorc39b4ae2019-01-09 17:11:37 -08004468 public void testBubble() throws Exception {
Mady Mellora92268c2020-03-09 17:25:08 -07004469 mBinderService.setBubblesAllowed(PKG, mUid, BUBBLE_PREFERENCE_NONE);
4470 assertFalse(mBinderService.areBubblesAllowed(PKG));
4471 assertEquals(mBinderService.getBubblePreferenceForPackage(PKG, mUid),
4472 BUBBLE_PREFERENCE_NONE);
Julia Reynolds33ab8a02018-12-17 16:19:52 -05004473 }
4474
4475 @Test
Mady Mellora92268c2020-03-09 17:25:08 -07004476 public void testUserApprovedBubblesForPackageSelected() throws Exception {
4477 mBinderService.setBubblesAllowed(PKG, mUid, BUBBLE_PREFERENCE_SELECTED);
4478 assertEquals(mBinderService.getBubblePreferenceForPackage(PKG, mUid),
4479 BUBBLE_PREFERENCE_SELECTED);
4480 }
4481
4482 @Test
4483 public void testUserApprovedBubblesForPackageAll() throws Exception {
4484 mBinderService.setBubblesAllowed(PKG, mUid, BUBBLE_PREFERENCE_ALL);
4485 assertTrue(mBinderService.areBubblesAllowed(PKG));
4486 assertEquals(mBinderService.getBubblePreferenceForPackage(PKG, mUid),
4487 BUBBLE_PREFERENCE_ALL);
Mady Mellor9db685a2019-01-23 13:23:37 -08004488 }
4489
4490 @Test
4491 public void testUserRejectsBubblesForPackage() throws Exception {
Mady Mellora92268c2020-03-09 17:25:08 -07004492 mBinderService.setBubblesAllowed(PKG, mUid, BUBBLE_PREFERENCE_NONE);
4493 assertFalse(mBinderService.areBubblesAllowed(PKG));
Mady Mellor9db685a2019-01-23 13:23:37 -08004494 }
4495
4496 @Test
Julia Reynoldsb6634872018-09-25 13:19:53 -04004497 public void testIsCallerInstantApp_primaryUser() throws Exception {
4498 ApplicationInfo info = new ApplicationInfo();
4499 info.privateFlags = ApplicationInfo.PRIVATE_FLAG_INSTANT;
4500 when(mPackageManager.getApplicationInfo(anyString(), anyInt(), eq(0))).thenReturn(info);
Julia Reynolds268647a2018-10-25 16:54:27 -04004501 when(mPackageManager.getPackagesForUid(anyInt())).thenReturn(new String[]{"any"});
Julia Reynoldsb6634872018-09-25 13:19:53 -04004502
Julia Reynolds268647a2018-10-25 16:54:27 -04004503 assertTrue(mService.isCallerInstantApp(45770, 0));
Julia Reynoldsb6634872018-09-25 13:19:53 -04004504
4505 info.privateFlags = 0;
Julia Reynolds268647a2018-10-25 16:54:27 -04004506 assertFalse(mService.isCallerInstantApp(575370, 0));
Julia Reynoldsb6634872018-09-25 13:19:53 -04004507 }
4508
4509 @Test
4510 public void testIsCallerInstantApp_secondaryUser() throws Exception {
4511 ApplicationInfo info = new ApplicationInfo();
4512 info.privateFlags = ApplicationInfo.PRIVATE_FLAG_INSTANT;
4513 when(mPackageManager.getApplicationInfo(anyString(), anyInt(), eq(10))).thenReturn(info);
4514 when(mPackageManager.getApplicationInfo(anyString(), anyInt(), eq(0))).thenReturn(null);
Julia Reynolds268647a2018-10-25 16:54:27 -04004515 when(mPackageManager.getPackagesForUid(anyInt())).thenReturn(new String[]{"any"});
Julia Reynoldsb6634872018-09-25 13:19:53 -04004516
Julia Reynolds268647a2018-10-25 16:54:27 -04004517 assertTrue(mService.isCallerInstantApp(68638450, 10));
Julia Reynoldsb6634872018-09-25 13:19:53 -04004518 }
4519
4520 @Test
Julia Reynolds86869c92019-06-21 10:45:06 -04004521 public void testIsCallerInstantApp_userAllNotification() throws Exception {
4522 ApplicationInfo info = new ApplicationInfo();
4523 info.privateFlags = ApplicationInfo.PRIVATE_FLAG_INSTANT;
Julia Reynolds57a974b2019-10-07 11:51:47 -04004524 when(mPackageManager.getApplicationInfo(anyString(), anyInt(), eq(USER_SYSTEM)))
Julia Reynolds86869c92019-06-21 10:45:06 -04004525 .thenReturn(info);
4526 when(mPackageManager.getPackagesForUid(anyInt())).thenReturn(new String[]{"any"});
4527
4528 assertTrue(mService.isCallerInstantApp(45770, UserHandle.USER_ALL));
4529
4530 info.privateFlags = 0;
4531 assertFalse(mService.isCallerInstantApp(575370, UserHandle.USER_ALL ));
4532 }
4533
4534 @Test
Julia Reynoldsb6634872018-09-25 13:19:53 -04004535 public void testResolveNotificationUid_sameApp_nonSystemUser() throws Exception {
4536 ApplicationInfo info = new ApplicationInfo();
4537 info.uid = Binder.getCallingUid();
4538 when(mPackageManager.getApplicationInfo(anyString(), anyInt(), eq(10))).thenReturn(info);
4539 when(mPackageManager.getApplicationInfo(anyString(), anyInt(), eq(0))).thenReturn(null);
4540
4541 int actualUid = mService.resolveNotificationUid("caller", "caller", info.uid, 10);
4542
4543 assertEquals(info.uid, actualUid);
4544 }
4545
4546 @Test
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04004547 public void testResolveNotificationUid_sameApp() throws Exception {
4548 ApplicationInfo info = new ApplicationInfo();
4549 info.uid = Binder.getCallingUid();
Julia Reynoldsb6634872018-09-25 13:19:53 -04004550 when(mPackageManager.getApplicationInfo(anyString(), anyInt(), eq(0))).thenReturn(info);
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04004551
4552 int actualUid = mService.resolveNotificationUid("caller", "caller", info.uid, 0);
4553
4554 assertEquals(info.uid, actualUid);
4555 }
4556
4557 @Test
Julia Reynoldsecc1b572018-10-01 16:19:24 -04004558 public void testResolveNotificationUid_sameAppDiffPackage() throws Exception {
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04004559 ApplicationInfo info = new ApplicationInfo();
4560 info.uid = Binder.getCallingUid();
Julia Reynoldsecc1b572018-10-01 16:19:24 -04004561 when(mPackageManager.getApplicationInfo(anyString(), anyInt(), eq(0))).thenReturn(info);
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04004562
Julia Reynoldsecc1b572018-10-01 16:19:24 -04004563 int actualUid = mService.resolveNotificationUid("caller", "callerAlso", info.uid, 0);
4564
4565 assertEquals(info.uid, actualUid);
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04004566 }
4567
4568 @Test
4569 public void testResolveNotificationUid_sameAppWrongUid() throws Exception {
4570 ApplicationInfo info = new ApplicationInfo();
4571 info.uid = 1356347;
4572 when(mPackageManager.getApplicationInfo(anyString(), anyInt(), anyInt())).thenReturn(info);
4573
4574 try {
4575 mService.resolveNotificationUid("caller", "caller", 9, 0);
4576 fail("Incorrect uid didn't throw security exception");
4577 } catch (SecurityException e) {
4578 // yay
4579 }
4580 }
4581
4582 @Test
4583 public void testResolveNotificationUid_delegateAllowed() throws Exception {
4584 int expectedUid = 123;
4585
4586 when(mPackageManagerClient.getPackageUidAsUser("target", 0)).thenReturn(expectedUid);
4587 mService.setPreferencesHelper(mPreferencesHelper);
4588 when(mPreferencesHelper.isDelegateAllowed(anyString(), anyInt(), anyString(), anyInt()))
4589 .thenReturn(true);
4590
4591 assertEquals(expectedUid, mService.resolveNotificationUid("caller", "target", 9, 0));
4592 }
4593
4594 @Test
4595 public void testResolveNotificationUid_androidAllowed() throws Exception {
4596 int expectedUid = 123;
4597
4598 when(mPackageManagerClient.getPackageUidAsUser("target", 0)).thenReturn(expectedUid);
4599 // no delegate
4600
4601 assertEquals(expectedUid, mService.resolveNotificationUid("android", "target", 0, 0));
4602 }
4603
4604 @Test
Julia Reynoldsa46a7692019-08-15 14:35:46 -04004605 public void testPostFromAndroidForNonExistentPackage() throws Exception {
4606 final String notReal = "NOT REAL";
4607 when(mPackageManagerClient.getPackageUidAsUser(anyString(), anyInt())).thenThrow(
4608 PackageManager.NameNotFoundException.class);
4609 ApplicationInfo ai = new ApplicationInfo();
4610 ai.uid = -1;
4611 when(mPackageManager.getApplicationInfo(anyString(), anyInt(), anyInt())).thenReturn(ai);
4612
Julia Reynolds24edc002020-01-29 16:35:32 -05004613 final StatusBarNotification sbn = generateNotificationRecord(null).getSbn();
Julia Reynoldsa46a7692019-08-15 14:35:46 -04004614 try {
Julia Reynoldsb6c83742019-07-30 18:03:40 -04004615 mInternalService.enqueueNotification(notReal, "android", 0, 0,
4616 "testPostFromAndroidForNonExistentPackage",
Julia Reynoldsa46a7692019-08-15 14:35:46 -04004617 sbn.getId(), sbn.getNotification(), sbn.getUserId());
4618 fail("can't post notifications for nonexistent packages, even if you exist");
4619 } catch (SecurityException e) {
4620 // yay
4621 }
4622 }
4623
4624 @Test
4625 public void testCancelFromAndroidForNonExistentPackage() throws Exception {
4626 final String notReal = "NOT REAL";
4627 when(mPackageManagerClient.getPackageUidAsUser(eq(notReal), anyInt())).thenThrow(
4628 PackageManager.NameNotFoundException.class);
4629 ApplicationInfo ai = new ApplicationInfo();
4630 ai.uid = -1;
4631 when(mPackageManager.getApplicationInfo(anyString(), anyInt(), anyInt())).thenReturn(ai);
4632
4633 // unlike the post case, ignore instead of throwing
Julia Reynolds24edc002020-01-29 16:35:32 -05004634 final StatusBarNotification sbn = generateNotificationRecord(null).getSbn();
Julia Reynoldsa46a7692019-08-15 14:35:46 -04004635
4636 mInternalService.cancelNotification(notReal, "android", 0, 0, "tag",
4637 sbn.getId(), sbn.getUserId());
4638 }
4639
4640 @Test
Julia Reynoldsa7ba45a2018-08-29 09:07:52 -04004641 public void testResolveNotificationUid_delegateNotAllowed() throws Exception {
4642 when(mPackageManagerClient.getPackageUidAsUser("target", 0)).thenReturn(123);
4643 // no delegate
4644
4645 try {
4646 mService.resolveNotificationUid("caller", "target", 9, 0);
4647 fail("Incorrect uid didn't throw security exception");
4648 } catch (SecurityException e) {
4649 // yay
4650 }
4651 }
Julia Reynolds564273f2018-09-13 15:53:11 -04004652
4653 @Test
4654 public void testRemoveForegroundServiceFlagFromNotification_enqueued() {
4655 Notification n = new Notification.Builder(mContext, "").build();
4656 n.flags |= FLAG_FOREGROUND_SERVICE;
4657
4658 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 9, null, mUid, 0,
4659 n, new UserHandle(mUid), null, 0);
4660 NotificationRecord r = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
4661
4662 mService.addEnqueuedNotification(r);
4663
4664 mInternalService.removeForegroundServiceFlagFromNotification(
Julia Reynolds24edc002020-01-29 16:35:32 -05004665 PKG, r.getSbn().getId(), r.getSbn().getUserId());
Julia Reynolds564273f2018-09-13 15:53:11 -04004666
4667 waitForIdle();
4668
4669 verify(mListeners, timeout(200).times(0)).notifyPostedLocked(any(), any());
4670 }
4671
4672 @Test
4673 public void testRemoveForegroundServiceFlagFromNotification_posted() {
4674 Notification n = new Notification.Builder(mContext, "").build();
4675 n.flags |= FLAG_FOREGROUND_SERVICE;
4676
4677 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 9, null, mUid, 0,
4678 n, new UserHandle(mUid), null, 0);
4679 NotificationRecord r = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
4680
4681 mService.addNotification(r);
4682
4683 mInternalService.removeForegroundServiceFlagFromNotification(
Julia Reynolds24edc002020-01-29 16:35:32 -05004684 PKG, r.getSbn().getId(), r.getSbn().getUserId());
Julia Reynolds564273f2018-09-13 15:53:11 -04004685
4686 waitForIdle();
4687
4688 ArgumentCaptor<NotificationRecord> captor =
4689 ArgumentCaptor.forClass(NotificationRecord.class);
4690 verify(mListeners, times(1)).notifyPostedLocked(captor.capture(), any());
4691
4692 assertEquals(0, captor.getValue().getNotification().flags);
4693 }
Beverly58b24532018-10-02 09:08:23 -04004694
4695 @Test
Bernardo Rufino18725b62020-01-21 14:12:43 +00004696 public void testAllowForegroundCustomToasts() throws Exception {
Beverly58b24532018-10-02 09:08:23 -04004697 final String testPackage = "testPackageName";
4698 assertEquals(0, mService.mToastQueue.size());
4699 mService.isSystemUid = false;
4700
4701 // package is not suspended
4702 when(mPackageManager.isPackageSuspendedForUser(testPackage, UserHandle.getUserId(mUid)))
4703 .thenReturn(false);
4704
4705 // notifications from this package are blocked by the user
4706 mService.setPreferencesHelper(mPreferencesHelper);
4707 when(mPreferencesHelper.getImportance(testPackage, mUid)).thenReturn(IMPORTANCE_NONE);
4708
Bernardo Rufinoe6cb3102020-03-06 20:33:11 +00004709 setAppInForegroundForToasts(mUid, true);
Beverly58b24532018-10-02 09:08:23 -04004710
4711 // enqueue toast -> toast should still enqueue
Bernardo Rufino52af6db2019-12-20 18:26:07 +00004712 ((INotificationManager) mService.mService).enqueueToast(testPackage, new Binder(),
Beverly58b24532018-10-02 09:08:23 -04004713 new TestableToastCallback(), 2000, 0);
4714 assertEquals(1, mService.mToastQueue.size());
4715 }
4716
4717 @Test
Bernardo Rufino18725b62020-01-21 14:12:43 +00004718 public void testDisallowBackgroundCustomToasts() throws Exception {
4719 final String testPackage = "testPackageName";
4720 assertEquals(0, mService.mToastQueue.size());
4721 mService.isSystemUid = false;
4722
4723 // package is not suspended
4724 when(mPackageManager.isPackageSuspendedForUser(testPackage, UserHandle.getUserId(mUid)))
4725 .thenReturn(false);
4726
Bernardo Rufinoe6cb3102020-03-06 20:33:11 +00004727 setAppInForegroundForToasts(mUid, false);
Bernardo Rufino18725b62020-01-21 14:12:43 +00004728
4729 // enqueue toast -> no toasts enqueued
4730 ((INotificationManager) mService.mService).enqueueToast(testPackage, new Binder(),
4731 new TestableToastCallback(), 2000, 0);
4732 assertEquals(0, mService.mToastQueue.size());
4733 }
4734
4735 @Test
4736 public void testAllowForegroundTextToasts() throws Exception {
4737 final String testPackage = "testPackageName";
4738 assertEquals(0, mService.mToastQueue.size());
4739 mService.isSystemUid = false;
4740
4741 // package is not suspended
4742 when(mPackageManager.isPackageSuspendedForUser(testPackage, UserHandle.getUserId(mUid)))
4743 .thenReturn(false);
4744
Bernardo Rufinoe6cb3102020-03-06 20:33:11 +00004745 setAppInForegroundForToasts(mUid, true);
Bernardo Rufino18725b62020-01-21 14:12:43 +00004746
4747 // enqueue toast -> toast should still enqueue
4748 ((INotificationManager) mService.mService).enqueueTextToast(testPackage, new Binder(),
4749 "Text", 2000, 0, null);
4750 assertEquals(1, mService.mToastQueue.size());
4751 }
4752
4753 @Test
4754 public void testAllowBackgroundTextToasts() throws Exception {
4755 final String testPackage = "testPackageName";
4756 assertEquals(0, mService.mToastQueue.size());
4757 mService.isSystemUid = false;
4758
4759 // package is not suspended
4760 when(mPackageManager.isPackageSuspendedForUser(testPackage, UserHandle.getUserId(mUid)))
4761 .thenReturn(false);
4762
Bernardo Rufinoe6cb3102020-03-06 20:33:11 +00004763 setAppInForegroundForToasts(mUid, false);
Bernardo Rufino18725b62020-01-21 14:12:43 +00004764
4765 // enqueue toast -> toast should still enqueue
4766 ((INotificationManager) mService.mService).enqueueTextToast(testPackage, new Binder(),
4767 "Text", 2000, 0, null);
4768 assertEquals(1, mService.mToastQueue.size());
4769 }
4770
4771 @Test
4772 public void testTextToastsCallStatusBar() throws Exception {
4773 final String testPackage = "testPackageName";
4774 assertEquals(0, mService.mToastQueue.size());
4775 mService.isSystemUid = false;
4776
4777 // package is not suspended
4778 when(mPackageManager.isPackageSuspendedForUser(testPackage, UserHandle.getUserId(mUid)))
4779 .thenReturn(false);
4780
4781 // enqueue toast -> no toasts enqueued
4782 ((INotificationManager) mService.mService).enqueueTextToast(testPackage, new Binder(),
4783 "Text", 2000, 0, null);
Bernardo Rufino78f5d832020-04-03 11:50:23 +01004784 verify(mStatusBar).showToast(anyInt(), any(), any(), any(), any(), anyInt(), any());
Bernardo Rufino18725b62020-01-21 14:12:43 +00004785 }
4786
4787 @Test
Beverly58b24532018-10-02 09:08:23 -04004788 public void testDisallowToastsFromSuspendedPackages() throws Exception {
4789 final String testPackage = "testPackageName";
4790 assertEquals(0, mService.mToastQueue.size());
4791 mService.isSystemUid = false;
4792
4793 // package is suspended
4794 when(mPackageManager.isPackageSuspendedForUser(testPackage, UserHandle.getUserId(mUid)))
4795 .thenReturn(true);
4796
4797 // notifications from this package are NOT blocked by the user
4798 mService.setPreferencesHelper(mPreferencesHelper);
4799 when(mPreferencesHelper.getImportance(testPackage, mUid)).thenReturn(IMPORTANCE_LOW);
4800
4801 // enqueue toast -> no toasts enqueued
Bernardo Rufino52af6db2019-12-20 18:26:07 +00004802 ((INotificationManager) mService.mService).enqueueToast(testPackage, new Binder(),
Beverly58b24532018-10-02 09:08:23 -04004803 new TestableToastCallback(), 2000, 0);
4804 assertEquals(0, mService.mToastQueue.size());
4805 }
4806
4807 @Test
4808 public void testDisallowToastsFromBlockedApps() throws Exception {
4809 final String testPackage = "testPackageName";
4810 assertEquals(0, mService.mToastQueue.size());
4811 mService.isSystemUid = false;
4812
4813 // package is not suspended
4814 when(mPackageManager.isPackageSuspendedForUser(testPackage, UserHandle.getUserId(mUid)))
4815 .thenReturn(false);
4816
4817 // notifications from this package are blocked by the user
4818 mService.setPreferencesHelper(mPreferencesHelper);
4819 when(mPreferencesHelper.getImportance(testPackage, mUid)).thenReturn(IMPORTANCE_NONE);
4820
Bernardo Rufinoe6cb3102020-03-06 20:33:11 +00004821 setAppInForegroundForToasts(mUid, false);
Beverly58b24532018-10-02 09:08:23 -04004822
4823 // enqueue toast -> no toasts enqueued
Bernardo Rufino52af6db2019-12-20 18:26:07 +00004824 ((INotificationManager) mService.mService).enqueueToast(testPackage, new Binder(),
Beverly58b24532018-10-02 09:08:23 -04004825 new TestableToastCallback(), 2000, 0);
4826 assertEquals(0, mService.mToastQueue.size());
4827 }
4828
4829 @Test
4830 public void testAlwaysAllowSystemToasts() throws Exception {
4831 final String testPackage = "testPackageName";
4832 assertEquals(0, mService.mToastQueue.size());
4833 mService.isSystemUid = true;
4834
4835 // package is suspended
4836 when(mPackageManager.isPackageSuspendedForUser(testPackage, UserHandle.getUserId(mUid)))
4837 .thenReturn(true);
4838
4839 // notifications from this package ARE blocked by the user
4840 mService.setPreferencesHelper(mPreferencesHelper);
4841 when(mPreferencesHelper.getImportance(testPackage, mUid)).thenReturn(IMPORTANCE_NONE);
4842
Bernardo Rufinoe6cb3102020-03-06 20:33:11 +00004843 setAppInForegroundForToasts(mUid, false);
Beverly58b24532018-10-02 09:08:23 -04004844
4845 // enqueue toast -> system toast can still be enqueued
Bernardo Rufino52af6db2019-12-20 18:26:07 +00004846 ((INotificationManager) mService.mService).enqueueToast(testPackage, new Binder(),
Beverly58b24532018-10-02 09:08:23 -04004847 new TestableToastCallback(), 2000, 0);
4848 assertEquals(1, mService.mToastQueue.size());
4849 }
Tony Mak29996702018-11-26 16:23:34 +00004850
Bernardo Rufinoe6cb3102020-03-06 20:33:11 +00004851 private void setAppInForegroundForToasts(int uid, boolean inForeground) {
4852 int importance = (inForeground) ? IMPORTANCE_FOREGROUND : IMPORTANCE_NONE;
4853 when(mActivityManager.getUidImportance(mUid)).thenReturn(importance);
4854 when(mAtm.hasResumedActivity(uid)).thenReturn(inForeground);
4855 }
4856
Tony Mak29996702018-11-26 16:23:34 +00004857 @Test
Alex Mang509e5542020-01-03 13:06:40 -08004858 public void testOnPanelRevealedAndHidden() {
4859 int items = 5;
4860 mService.mNotificationDelegate.onPanelRevealed(false, items);
4861 verify(mAssistants, times(1)).onPanelRevealed(eq(items));
4862
4863 mService.mNotificationDelegate.onPanelHidden();
4864 verify(mAssistants, times(1)).onPanelHidden();
Will Brockman9918db92020-03-06 16:48:39 -05004865
4866 assertEquals(2, mNotificationRecordLogger.numCalls());
4867 assertEquals(NotificationRecordLogger.NotificationPanelEvent.NOTIFICATION_PANEL_OPEN,
4868 mNotificationRecordLogger.event(0));
4869 assertEquals(NotificationRecordLogger.NotificationPanelEvent.NOTIFICATION_PANEL_CLOSE,
4870 mNotificationRecordLogger.event(1));
Alex Mang509e5542020-01-03 13:06:40 -08004871 }
4872
4873 @Test
Tony Mak29996702018-11-26 16:23:34 +00004874 public void testOnNotificationSmartReplySent() {
4875 final int replyIndex = 2;
4876 final String reply = "Hello";
Milo Sredkov13d88112019-02-01 12:23:24 +00004877 final boolean modifiedBeforeSending = true;
Tony Mak29996702018-11-26 16:23:34 +00004878 final boolean generatedByAssistant = true;
4879
4880 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
Milo Sredkov13d88112019-02-01 12:23:24 +00004881 r.setSuggestionsGeneratedByAssistant(generatedByAssistant);
Tony Mak29996702018-11-26 16:23:34 +00004882 mService.addNotification(r);
4883
4884 mService.mNotificationDelegate.onNotificationSmartReplySent(
Milo Sredkov13d88112019-02-01 12:23:24 +00004885 r.getKey(), replyIndex, reply, NOTIFICATION_LOCATION_UNKNOWN,
4886 modifiedBeforeSending);
Tony Mak29996702018-11-26 16:23:34 +00004887 verify(mAssistants).notifyAssistantSuggestedReplySent(
Julia Reynolds24edc002020-01-29 16:35:32 -05004888 eq(r.getSbn()), eq(reply), eq(generatedByAssistant));
Will Brockman9918db92020-03-06 16:48:39 -05004889 assertEquals(1, mNotificationRecordLogger.numCalls());
4890 assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_SMART_REPLIED,
4891 mNotificationRecordLogger.event(0));
Tony Mak29996702018-11-26 16:23:34 +00004892 }
Tony Mak7d4b3a52018-11-27 17:29:36 +00004893
4894 @Test
4895 public void testOnNotificationActionClick() {
4896 final int actionIndex = 2;
4897 final Notification.Action action =
4898 new Notification.Action.Builder(null, "text", null).build();
4899 final boolean generatedByAssistant = false;
4900
4901 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
4902 mService.addNotification(r);
4903
4904 NotificationVisibility notificationVisibility =
4905 NotificationVisibility.obtain(r.getKey(), 1, 2, true);
4906 mService.mNotificationDelegate.onNotificationActionClick(
4907 10, 10, r.getKey(), actionIndex, action, notificationVisibility,
4908 generatedByAssistant);
4909 verify(mAssistants).notifyAssistantActionClicked(
Julia Reynolds24edc002020-01-29 16:35:32 -05004910 eq(r.getSbn()), eq(actionIndex), eq(action), eq(generatedByAssistant));
Will Brockman9918db92020-03-06 16:48:39 -05004911
4912 assertEquals(1, mNotificationRecordLogger.numCalls());
4913 assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_ACTION_CLICKED,
4914 mNotificationRecordLogger.event(0));
Tony Mak7d4b3a52018-11-27 17:29:36 +00004915 }
Gustav Sennton44dc5882018-12-13 14:38:50 +00004916
4917 @Test
4918 public void testLogSmartSuggestionsVisible_triggerOnExpandAndVisible() {
4919 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
4920 mService.addNotification(r);
4921
Gustav Senntona8e38aa2019-01-22 14:55:39 +00004922 mService.mNotificationDelegate.onNotificationExpansionChanged(r.getKey(), false, true,
4923 NOTIFICATION_LOCATION_UNKNOWN);
Gustav Sennton44dc5882018-12-13 14:38:50 +00004924 NotificationVisibility[] notificationVisibility = new NotificationVisibility[] {
4925 NotificationVisibility.obtain(r.getKey(), 0, 0, true)
4926 };
4927 mService.mNotificationDelegate.onNotificationVisibilityChanged(notificationVisibility,
4928 new NotificationVisibility[0]);
4929
4930 assertEquals(1, mService.countLogSmartSuggestionsVisible);
4931 }
4932
4933 @Test
4934 public void testLogSmartSuggestionsVisible_noTriggerOnExpand() {
4935 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
4936 mService.addNotification(r);
4937
Gustav Senntona8e38aa2019-01-22 14:55:39 +00004938 mService.mNotificationDelegate.onNotificationExpansionChanged(r.getKey(), false, true,
4939 NOTIFICATION_LOCATION_UNKNOWN);
Gustav Sennton44dc5882018-12-13 14:38:50 +00004940
4941 assertEquals(0, mService.countLogSmartSuggestionsVisible);
4942 }
4943
4944 @Test
4945 public void testLogSmartSuggestionsVisible_noTriggerOnVisible() {
4946 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
4947 mService.addNotification(r);
4948
Julia Reynolds95334132018-12-19 11:15:35 -05004949 NotificationVisibility[] notificationVisibility = new NotificationVisibility[]{
Gustav Sennton44dc5882018-12-13 14:38:50 +00004950 NotificationVisibility.obtain(r.getKey(), 0, 0, true)
4951 };
4952 mService.mNotificationDelegate.onNotificationVisibilityChanged(notificationVisibility,
4953 new NotificationVisibility[0]);
4954
4955 assertEquals(0, mService.countLogSmartSuggestionsVisible);
4956 }
Julia Reynolds95334132018-12-19 11:15:35 -05004957
Colin Cross5ea7fb72019-12-18 17:16:36 -08004958 @Test
Julia Reynolds95334132018-12-19 11:15:35 -05004959 public void testReportSeen_delegated() {
4960 Notification.Builder nb =
4961 new Notification.Builder(mContext, mTestNotificationChannel.getId())
4962 .setContentTitle("foo")
4963 .setSmallIcon(android.R.drawable.sym_def_app_icon);
4964
4965 StatusBarNotification sbn = new StatusBarNotification(PKG, "opPkg", 0, "tag", mUid, 0,
4966 nb.build(), new UserHandle(mUid), null, 0);
4967 NotificationRecord r = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
4968
4969 mService.reportSeen(r);
4970 verify(mAppUsageStats, never()).reportEvent(anyString(), anyInt(), anyInt());
4971
4972 }
4973
4974 @Test
4975 public void testReportSeen_notDelegated() {
4976 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
4977
4978 mService.reportSeen(r);
4979 verify(mAppUsageStats, times(1)).reportEvent(anyString(), anyInt(), anyInt());
4980 }
Julia Reynolds3207e2f2018-12-20 09:39:53 -05004981
4982 @Test
4983 public void testNotificationStats_notificationError() {
4984 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
4985 mService.addNotification(r);
4986
Julia Reynolds24edc002020-01-29 16:35:32 -05004987 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, r.getSbn().getId(),
4988 r.getSbn().getTag(), mUid, 0,
Julia Reynolds3207e2f2018-12-20 09:39:53 -05004989 new Notification.Builder(mContext, mTestNotificationChannel.getId()).build(),
4990 new UserHandle(mUid), null, 0);
4991 NotificationRecord update = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
4992 mService.addEnqueuedNotification(update);
Julia Reynolds24edc002020-01-29 16:35:32 -05004993 assertNull(update.getSbn().getNotification().getSmallIcon());
Julia Reynolds3207e2f2018-12-20 09:39:53 -05004994
4995 NotificationManagerService.PostNotificationRunnable runnable =
4996 mService.new PostNotificationRunnable(update.getKey());
4997 runnable.run();
4998 waitForIdle();
4999
5000 ArgumentCaptor<NotificationStats> captor = ArgumentCaptor.forClass(NotificationStats.class);
5001 verify(mListeners).notifyRemovedLocked(any(), anyInt(), captor.capture());
5002 assertNotNull(captor.getValue());
5003 }
Tony Mak9a3c1f12019-03-04 16:04:42 +00005004
5005 @Test
Julia Reynolds7a6d07a2019-03-18 11:31:56 -04005006 public void testCanNotifyAsUser_crossUser() throws Exception {
5007 // same user no problem
5008 mBinderService.canNotifyAsPackage("src", "target", mContext.getUserId());
5009
5010 // cross user, no permission, problem
5011 try {
5012 mBinderService.canNotifyAsPackage("src", "target", mContext.getUserId() + 1);
5013 fail("Should not be callable cross user without cross user permission");
5014 } catch (SecurityException e) {
5015 // good
5016 }
5017
5018 // cross user, with permission, no problem
Will Brockmancfd98302020-01-29 15:57:30 -05005019 enableInteractAcrossUsers();
Julia Reynolds7a6d07a2019-03-18 11:31:56 -04005020 mBinderService.canNotifyAsPackage("src", "target", mContext.getUserId() + 1);
5021 }
5022
5023 @Test
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -04005024 public void testgetNotificationChannels_crossUser() throws Exception {
5025 // same user no problem
5026 mBinderService.getNotificationChannels("src", "target", mContext.getUserId());
5027
5028 // cross user, no permission, problem
5029 try {
5030 mBinderService.getNotificationChannels("src", "target", mContext.getUserId() + 1);
5031 fail("Should not be callable cross user without cross user permission");
5032 } catch (SecurityException e) {
5033 // good
5034 }
5035
5036 // cross user, with permission, no problem
Will Brockmancfd98302020-01-29 15:57:30 -05005037 enableInteractAcrossUsers();
Julia Reynoldsb4a9e9c2019-03-20 15:46:08 -04005038 mBinderService.getNotificationChannels("src", "target", mContext.getUserId() + 1);
5039 }
5040
5041 @Test
Tony Mak9a3c1f12019-03-04 16:04:42 +00005042 public void setDefaultAssistantForUser_fromConfigXml() {
5043 clearDeviceConfig();
5044 ComponentName xmlConfig = new ComponentName("config", "xml");
Jay Aliomer4204f252019-08-26 11:36:53 -04005045 ArraySet<ComponentName> components = new ArraySet<>(Arrays.asList(xmlConfig));
Tony Mak9a3c1f12019-03-04 16:04:42 +00005046 when(mResources
5047 .getString(
5048 com.android.internal.R.string.config_defaultAssistantAccessComponent))
5049 .thenReturn(xmlConfig.flattenToString());
5050 when(mContext.getResources()).thenReturn(mResources);
Jay Aliomer4204f252019-08-26 11:36:53 -04005051 when(mAssistants.queryPackageForServices(eq(null), anyInt(), anyInt()))
5052 .thenReturn(components);
5053 when(mAssistants.getDefaultComponents())
5054 .thenReturn(components);
Tony Mak9a3c1f12019-03-04 16:04:42 +00005055 mService.setNotificationAssistantAccessGrantedCallback(
5056 mNotificationAssistantAccessGrantedCallback);
5057
Jay Aliomer4204f252019-08-26 11:36:53 -04005058
Tony Mak9a3c1f12019-03-04 16:04:42 +00005059 mService.setDefaultAssistantForUser(0);
5060
5061 verify(mNotificationAssistantAccessGrantedCallback)
5062 .onGranted(eq(xmlConfig), eq(0), eq(true));
5063 }
5064
5065 @Test
5066 public void setDefaultAssistantForUser_fromDeviceConfig() {
5067 ComponentName xmlConfig = new ComponentName("xml", "config");
5068 ComponentName deviceConfig = new ComponentName("device", "config");
5069 setDefaultAssistantInDeviceConfig(deviceConfig.flattenToString());
5070 when(mResources
5071 .getString(com.android.internal.R.string.config_defaultAssistantAccessComponent))
5072 .thenReturn(xmlConfig.flattenToString());
5073 when(mContext.getResources()).thenReturn(mResources);
Jay Aliomer4204f252019-08-26 11:36:53 -04005074 when(mAssistants.queryPackageForServices(eq(null), anyInt(), anyInt()))
Tony Mak9a3c1f12019-03-04 16:04:42 +00005075 .thenReturn(new ArraySet<>(Arrays.asList(xmlConfig, deviceConfig)));
Jay Aliomer4204f252019-08-26 11:36:53 -04005076 when(mAssistants.getDefaultComponents())
5077 .thenReturn(new ArraySet<>(Arrays.asList(deviceConfig)));
Tony Mak9a3c1f12019-03-04 16:04:42 +00005078 mService.setNotificationAssistantAccessGrantedCallback(
5079 mNotificationAssistantAccessGrantedCallback);
5080
5081 mService.setDefaultAssistantForUser(0);
5082
5083 verify(mNotificationAssistantAccessGrantedCallback)
5084 .onGranted(eq(deviceConfig), eq(0), eq(true));
5085 }
5086
5087 @Test
5088 public void setDefaultAssistantForUser_deviceConfigInvalid() {
5089 ComponentName xmlConfig = new ComponentName("xml", "config");
5090 ComponentName deviceConfig = new ComponentName("device", "config");
5091 setDefaultAssistantInDeviceConfig(deviceConfig.flattenToString());
5092 when(mResources
5093 .getString(com.android.internal.R.string.config_defaultAssistantAccessComponent))
5094 .thenReturn(xmlConfig.flattenToString());
5095 when(mContext.getResources()).thenReturn(mResources);
5096 // Only xmlConfig is valid, deviceConfig is not.
5097 when(mAssistants.queryPackageForServices(eq(null), anyInt(), eq(0)))
Jay Aliomer4204f252019-08-26 11:36:53 -04005098 .thenReturn(new ArraySet<>(Collections.singleton(xmlConfig)));
5099 when(mAssistants.getDefaultComponents())
5100 .thenReturn(new ArraySet<>(Arrays.asList(xmlConfig, deviceConfig)));
Tony Mak9a3c1f12019-03-04 16:04:42 +00005101 mService.setNotificationAssistantAccessGrantedCallback(
5102 mNotificationAssistantAccessGrantedCallback);
5103
5104 mService.setDefaultAssistantForUser(0);
5105
5106 verify(mNotificationAssistantAccessGrantedCallback)
5107 .onGranted(eq(xmlConfig), eq(0), eq(true));
5108 }
5109
Mady Mellor7eb18ef2019-03-27 14:03:46 -07005110 @Test
Jay Aliomer4204f252019-08-26 11:36:53 -04005111 public void clearMultipleDefaultAssistantPackagesShouldEnableOnlyOne() throws RemoteException {
5112 ArrayMap<Boolean, ArrayList<ComponentName>> changedListeners =
5113 generateResetComponentValues();
5114 when(mListeners.resetComponents(anyString(), anyInt())).thenReturn(changedListeners);
5115 ArrayMap<Boolean, ArrayList<ComponentName>> changes = new ArrayMap<>();
5116 ComponentName deviceConfig1 = new ComponentName("device", "config1");
5117 ComponentName deviceConfig2 = new ComponentName("device", "config2");
5118 changes.put(true, new ArrayList(Arrays.asList(deviceConfig1, deviceConfig2)));
5119 changes.put(false, new ArrayList());
5120 when(mAssistants.resetComponents(anyString(), anyInt())).thenReturn(changes);
5121 mService.getBinderService().clearData("device", 0, false);
5122 verify(mAssistants, times(1))
5123 .setPackageOrComponentEnabled(
5124 eq("device/config2"),
5125 eq(0), eq(true), eq(false));
5126 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
5127 eq("device"), eq(0), eq(false), eq(true));
5128 }
5129
5130 @Test
5131 public void clearDefaultListenersPackageShouldEnableIt() throws RemoteException {
5132 ArrayMap<Boolean, ArrayList<ComponentName>> changedAssistants =
5133 generateResetComponentValues();
5134 when(mAssistants.resetComponents(anyString(), anyInt())).thenReturn(changedAssistants);
5135 ComponentName deviceConfig = new ComponentName("device", "config");
5136 ArrayMap<Boolean, ArrayList<ComponentName>> changes = new ArrayMap<>();
5137 changes.put(true, new ArrayList(Arrays.asList(deviceConfig)));
5138 changes.put(false, new ArrayList());
5139 when(mListeners.resetComponents(anyString(), anyInt()))
5140 .thenReturn(changes);
5141 mService.getBinderService().clearData("device", 0, false);
5142 verify(mConditionProviders, times(1)).setPackageOrComponentEnabled(
5143 eq("device"), eq(0), eq(false), eq(true));
5144 }
5145
5146 @Test
5147 public void clearDefaultDnDPackageShouldEnableIt() throws RemoteException {
5148 ComponentName deviceConfig = new ComponentName("device", "config");
5149 ArrayMap<Boolean, ArrayList<ComponentName>> changed = generateResetComponentValues();
5150 when(mAssistants.resetComponents(anyString(), anyInt())).thenReturn(changed);
5151 when(mListeners.resetComponents(anyString(), anyInt())).thenReturn(changed);
5152 mService.getBinderService().clearData("device", 0, false);
5153 verify(mConditionProviders, times(1)).resetPackage(
5154 eq("device"), eq(0));
5155 }
5156
5157 @Test
Mady Mellor65dcaa92019-04-03 12:21:44 -07005158 public void testFlagBubble() throws RemoteException {
Mady Mellora92268c2020-03-09 17:25:08 -07005159 setUpPrefsForBubbles(PKG, mUid,
5160 true /* global */,
5161 BUBBLE_PREFERENCE_ALL /* app */,
5162 true /* channel */);
Mady Mellor65dcaa92019-04-03 12:21:44 -07005163
Mady Mellor9e923e12019-12-17 16:08:46 -08005164 NotificationRecord nr =
5165 generateMessageBubbleNotifRecord(mTestNotificationChannel, "testFlagBubble");
Mady Mellor65dcaa92019-04-03 12:21:44 -07005166
Julia Reynolds24edc002020-01-29 16:35:32 -05005167 mBinderService.enqueueNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
5168 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
Mady Mellor65dcaa92019-04-03 12:21:44 -07005169 waitForIdle();
5170
5171 StatusBarNotification[] notifs = mBinderService.getActiveNotifications(PKG);
5172 assertEquals(1, notifs.length);
5173 assertTrue((notifs[0].getNotification().flags & FLAG_BUBBLE) != 0);
5174 assertTrue(mService.getNotificationRecord(
Julia Reynolds24edc002020-01-29 16:35:32 -05005175 nr.getSbn().getKey()).getNotification().isBubbleNotification());
Mady Mellor65dcaa92019-04-03 12:21:44 -07005176 }
5177
5178 @Test
Mady Mellorc6820342019-05-20 12:04:36 -07005179 public void testFlagBubble_noFlag_appNotAllowed() throws RemoteException {
Mady Mellora92268c2020-03-09 17:25:08 -07005180 setUpPrefsForBubbles(PKG, mUid,
5181 true /* global */,
5182 BUBBLE_PREFERENCE_NONE /* app */,
5183 true /* channel */);
Mady Mellorc6820342019-05-20 12:04:36 -07005184
Mady Mellor9e923e12019-12-17 16:08:46 -08005185 NotificationRecord nr = generateMessageBubbleNotifRecord(mTestNotificationChannel,
5186 "testFlagBubble_noFlag_appNotAllowed");
Mady Mellorc6820342019-05-20 12:04:36 -07005187
Julia Reynolds24edc002020-01-29 16:35:32 -05005188 mBinderService.enqueueNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
5189 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
Mady Mellorc6820342019-05-20 12:04:36 -07005190 waitForIdle();
5191
5192 StatusBarNotification[] notifs = mBinderService.getActiveNotifications(PKG);
5193 assertEquals(1, notifs.length);
5194 assertEquals((notifs[0].getNotification().flags & FLAG_BUBBLE), 0);
5195 assertFalse(mService.getNotificationRecord(
Julia Reynolds24edc002020-01-29 16:35:32 -05005196 nr.getSbn().getKey()).getNotification().isBubbleNotification());
Mady Mellorc6820342019-05-20 12:04:36 -07005197 }
5198
5199 @Test
Mady Mellor9e923e12019-12-17 16:08:46 -08005200 public void testFlagBubbleNotifs_noFlag_whenAppForeground() throws RemoteException {
Mady Mellora92268c2020-03-09 17:25:08 -07005201 setUpPrefsForBubbles(PKG, mUid,
5202 true /* global */,
5203 BUBBLE_PREFERENCE_ALL /* app */,
5204 true /* channel */);
Mady Mellor7eb18ef2019-03-27 14:03:46 -07005205
Mady Mellorbe797962019-04-01 16:04:24 -07005206 // Notif with bubble metadata but not our other misc requirements
Mady Mellor9e923e12019-12-17 16:08:46 -08005207 Notification.Builder nb = new Notification.Builder(mContext,
5208 mTestNotificationChannel.getId())
5209 .setContentTitle("foo")
5210 .setSmallIcon(android.R.drawable.sym_def_app_icon)
Mady Mellora92268c2020-03-09 17:25:08 -07005211 .setBubbleMetadata(getBubbleMetadata());
Mady Mellor9e923e12019-12-17 16:08:46 -08005212 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, "tag", mUid, 0,
5213 nb.build(), new UserHandle(mUid), null, 0);
5214 NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
Mady Mellorbe797962019-04-01 16:04:24 -07005215
5216 // Say we're foreground
Julia Reynolds24edc002020-01-29 16:35:32 -05005217 when(mActivityManager.getPackageImportance(nr.getSbn().getPackageName())).thenReturn(
Mady Mellorbe797962019-04-01 16:04:24 -07005218 IMPORTANCE_FOREGROUND);
Julia Reynolds24edc002020-01-29 16:35:32 -05005219 mBinderService.enqueueNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
5220 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
Mady Mellorbe797962019-04-01 16:04:24 -07005221 waitForIdle();
5222
Mady Mellor9e923e12019-12-17 16:08:46 -08005223 // if notif isn't configured properly it doesn't get to bubble just because app is
5224 // foreground.
Mady Mellorbe797962019-04-01 16:04:24 -07005225 assertFalse(mService.getNotificationRecord(
Julia Reynolds24edc002020-01-29 16:35:32 -05005226 nr.getSbn().getKey()).getNotification().isBubbleNotification());
Mady Mellorbe797962019-04-01 16:04:24 -07005227 }
5228
5229 @Test
Mady Mellorbe797962019-04-01 16:04:24 -07005230 public void testFlagBubbleNotifs_flag_messaging() throws RemoteException {
Mady Mellora92268c2020-03-09 17:25:08 -07005231 setUpPrefsForBubbles(PKG, mUid,
5232 true /* global */,
5233 BUBBLE_PREFERENCE_ALL /* app */,
5234 true /* channel */);
Mady Mellorbe797962019-04-01 16:04:24 -07005235
Mady Mellor9e923e12019-12-17 16:08:46 -08005236 NotificationRecord nr = generateMessageBubbleNotifRecord(mTestNotificationChannel,
5237 "testFlagBubbleNotifs_flag_messaging");
Mady Mellorbe797962019-04-01 16:04:24 -07005238
Julia Reynolds24edc002020-01-29 16:35:32 -05005239 mBinderService.enqueueNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
5240 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
Mady Mellorbe797962019-04-01 16:04:24 -07005241 waitForIdle();
5242
5243 // yes allowed, yes messaging, yes bubble
5244 assertTrue(mService.getNotificationRecord(
Julia Reynolds24edc002020-01-29 16:35:32 -05005245 nr.getSbn().getKey()).getNotification().isBubbleNotification());
Mady Mellorbe797962019-04-01 16:04:24 -07005246 }
5247
5248 @Test
Mady Mellorbe797962019-04-01 16:04:24 -07005249 public void testFlagBubbleNotifs_noFlag_messaging_appNotAllowed() throws RemoteException {
Mady Mellora92268c2020-03-09 17:25:08 -07005250 setUpPrefsForBubbles(PKG, mUid,
5251 true /* global */,
5252 BUBBLE_PREFERENCE_NONE /* app */,
5253 true /* channel */);
Mady Mellor7eb18ef2019-03-27 14:03:46 -07005254
Mady Mellor9e923e12019-12-17 16:08:46 -08005255 NotificationRecord nr = generateMessageBubbleNotifRecord(mTestNotificationChannel,
5256 "testFlagBubbleNotifs_noFlag_messaging_appNotAllowed");
Mady Mellor7eb18ef2019-03-27 14:03:46 -07005257
5258 // Post the notification
Julia Reynolds24edc002020-01-29 16:35:32 -05005259 mBinderService.enqueueNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
5260 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
Mady Mellor7eb18ef2019-03-27 14:03:46 -07005261 waitForIdle();
5262
5263 // not allowed, no bubble
5264 assertFalse(mService.getNotificationRecord(
Julia Reynolds24edc002020-01-29 16:35:32 -05005265 nr.getSbn().getKey()).getNotification().isBubbleNotification());
Mady Mellor7eb18ef2019-03-27 14:03:46 -07005266 }
5267
5268 @Test
Mady Mellorbe797962019-04-01 16:04:24 -07005269 public void testFlagBubbleNotifs_noFlag_notBubble() throws RemoteException {
Mady Mellora92268c2020-03-09 17:25:08 -07005270 setUpPrefsForBubbles(PKG, mUid,
5271 true /* global */,
5272 BUBBLE_PREFERENCE_ALL /* app */,
5273 true /* channel */);
Mady Mellor7eb18ef2019-03-27 14:03:46 -07005274
Mady Mellor9e923e12019-12-17 16:08:46 -08005275 // Messaging notif WITHOUT bubble metadata
5276 Notification.Builder nb = getMessageStyleNotifBuilder(false /* addBubbleMetadata */,
5277 null /* groupKey */, false /* isSummary */);
5278
5279 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1,
5280 "testFlagBubbleNotifs_noFlag_notBubble", mUid, 0,
5281 nb.build(), new UserHandle(mUid), null, 0);
5282 NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
Mady Mellor7eb18ef2019-03-27 14:03:46 -07005283
5284 // Post the notification
Julia Reynolds24edc002020-01-29 16:35:32 -05005285 mBinderService.enqueueNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
5286 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
Mady Mellor7eb18ef2019-03-27 14:03:46 -07005287 waitForIdle();
5288
5289 // no bubble metadata, no bubble
5290 assertFalse(mService.getNotificationRecord(
Julia Reynolds24edc002020-01-29 16:35:32 -05005291 nr.getSbn().getKey()).getNotification().isBubbleNotification());
Mady Mellor7eb18ef2019-03-27 14:03:46 -07005292 }
5293
5294 @Test
Mady Mellorbe797962019-04-01 16:04:24 -07005295 public void testFlagBubbleNotifs_noFlag_messaging_channelNotAllowed() throws RemoteException {
Mady Mellora92268c2020-03-09 17:25:08 -07005296 setUpPrefsForBubbles(PKG, mUid,
5297 true /* global */,
5298 BUBBLE_PREFERENCE_ALL /* app */,
5299 false /* channel */);
Mady Mellor7eb18ef2019-03-27 14:03:46 -07005300
Mady Mellor9e923e12019-12-17 16:08:46 -08005301 NotificationRecord nr = generateMessageBubbleNotifRecord(mTestNotificationChannel,
5302 "testFlagBubbleNotifs_noFlag_messaging_channelNotAllowed");
Mady Mellora92268c2020-03-09 17:25:08 -07005303 nr.getChannel().lockFields(USER_LOCKED_ALLOW_BUBBLE);
Mady Mellor7eb18ef2019-03-27 14:03:46 -07005304
5305 // Post the notification
Julia Reynolds24edc002020-01-29 16:35:32 -05005306 mBinderService.enqueueNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
5307 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
Mady Mellor7eb18ef2019-03-27 14:03:46 -07005308 waitForIdle();
5309
5310 // channel not allowed, no bubble
5311 assertFalse(mService.getNotificationRecord(
Julia Reynolds24edc002020-01-29 16:35:32 -05005312 nr.getSbn().getKey()).getNotification().isBubbleNotification());
Mady Mellor7eb18ef2019-03-27 14:03:46 -07005313 }
Tony Mak9a3c1f12019-03-04 16:04:42 +00005314
Mady Mellor49b1bf12019-03-29 12:00:02 -07005315 @Test
Beverly9e6a7642020-02-13 10:11:29 -05005316 public void testCancelNotificationsFromApp_cancelsBubbles() throws Exception {
Mady Mellor49b1bf12019-03-29 12:00:02 -07005317 final NotificationRecord nrBubble = generateNotificationRecord(mTestNotificationChannel);
Julia Reynolds24edc002020-01-29 16:35:32 -05005318 nrBubble.getSbn().getNotification().flags |= FLAG_BUBBLE;
Mady Mellor49b1bf12019-03-29 12:00:02 -07005319
5320 // Post the notification
Julia Reynoldsb6c83742019-07-30 18:03:40 -04005321 mBinderService.enqueueNotificationWithTag(PKG, PKG,
5322 "testAppCancelNotifications_cancelsBubbles",
Julia Reynolds24edc002020-01-29 16:35:32 -05005323 nrBubble.getSbn().getId(), nrBubble.getSbn().getNotification(),
5324 nrBubble.getSbn().getUserId());
Mady Mellor49b1bf12019-03-29 12:00:02 -07005325 waitForIdle();
5326
5327 StatusBarNotification[] notifs = mBinderService.getActiveNotifications(PKG);
5328 assertEquals(1, notifs.length);
5329 assertEquals(1, mService.getNotificationRecordCount());
5330
Julia Reynoldsb6c83742019-07-30 18:03:40 -04005331 mBinderService.cancelNotificationWithTag(PKG, PKG,
Julia Reynolds24edc002020-01-29 16:35:32 -05005332 "testAppCancelNotifications_cancelsBubbles", nrBubble.getSbn().getId(),
5333 nrBubble.getSbn().getUserId());
Mady Mellor49b1bf12019-03-29 12:00:02 -07005334 waitForIdle();
5335
5336 StatusBarNotification[] notifs2 = mBinderService.getActiveNotifications(PKG);
5337 assertEquals(0, notifs2.length);
5338 assertEquals(0, mService.getNotificationRecordCount());
5339 }
5340
5341 @Test
Beverly9e6a7642020-02-13 10:11:29 -05005342 public void testCancelAllNotificationsFromApp_cancelsBubble() throws Exception {
5343 final NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel);
5344 nr.getSbn().getNotification().flags |= FLAG_BUBBLE;
5345 mService.addNotification(nr);
5346
5347 mBinderService.cancelAllNotifications(PKG, nr.getSbn().getUserId());
5348 waitForIdle();
5349
5350 StatusBarNotification[] notifs = mBinderService.getActiveNotifications(PKG);
5351 assertEquals(0, notifs.length);
5352 assertEquals(0, mService.getNotificationRecordCount());
5353 }
5354
5355 @Test
Mady Mellor49b1bf12019-03-29 12:00:02 -07005356 public void testCancelAllNotificationsFromListener_ignoresBubbles() throws Exception {
5357 final NotificationRecord nrNormal = generateNotificationRecord(mTestNotificationChannel);
5358 final NotificationRecord nrBubble = generateNotificationRecord(mTestNotificationChannel);
Julia Reynolds24edc002020-01-29 16:35:32 -05005359 nrBubble.getSbn().getNotification().flags |= FLAG_BUBBLE;
Mady Mellor49b1bf12019-03-29 12:00:02 -07005360
5361 mService.addNotification(nrNormal);
5362 mService.addNotification(nrBubble);
5363
5364 mService.getBinderService().cancelNotificationsFromListener(null, null);
5365 waitForIdle();
5366
5367 StatusBarNotification[] notifs = mBinderService.getActiveNotifications(PKG);
5368 assertEquals(1, notifs.length);
5369 assertEquals(1, mService.getNotificationRecordCount());
5370 }
5371
5372 @Test
5373 public void testCancelNotificationsFromListener_ignoresBubbles() throws Exception {
5374 final NotificationRecord nrNormal = generateNotificationRecord(mTestNotificationChannel);
5375 final NotificationRecord nrBubble = generateNotificationRecord(mTestNotificationChannel);
Julia Reynolds24edc002020-01-29 16:35:32 -05005376 nrBubble.getSbn().getNotification().flags |= FLAG_BUBBLE;
Mady Mellor49b1bf12019-03-29 12:00:02 -07005377
5378 mService.addNotification(nrNormal);
5379 mService.addNotification(nrBubble);
5380
Julia Reynolds24edc002020-01-29 16:35:32 -05005381 String[] keys = {nrNormal.getSbn().getKey(), nrBubble.getSbn().getKey()};
Mady Mellor49b1bf12019-03-29 12:00:02 -07005382 mService.getBinderService().cancelNotificationsFromListener(null, keys);
5383 waitForIdle();
5384
5385 StatusBarNotification[] notifs = mBinderService.getActiveNotifications(PKG);
5386 assertEquals(1, notifs.length);
5387 assertEquals(1, mService.getNotificationRecordCount());
Will Brockman9918db92020-03-06 16:48:39 -05005388
5389 assertEquals(1, mNotificationRecordLogger.numCalls());
5390 assertEquals(NotificationRecordLogger.NotificationCancelledEvent
5391 .NOTIFICATION_CANCEL_LISTENER_CANCEL, mNotificationRecordLogger.event(0));
Mady Mellor49b1bf12019-03-29 12:00:02 -07005392 }
Julia Reynoldsad6dd352019-03-07 16:46:22 -05005393
Julia Reynolds4214da92019-04-10 15:04:06 -04005394 @Test
Beverly9e6a7642020-02-13 10:11:29 -05005395 public void testCancelAllNotificationsFromStatusBar_ignoresBubble() throws Exception {
5396 // GIVEN a notification bubble
5397 final NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel);
5398 nr.getSbn().getNotification().flags |= FLAG_BUBBLE;
5399 mService.addNotification(nr);
5400
5401 // WHEN the status bar clears all notifications
5402 mService.mNotificationDelegate.onClearAll(mUid, Binder.getCallingPid(),
5403 nr.getSbn().getUserId());
5404 waitForIdle();
5405
5406 // THEN the bubble notification does not get removed
5407 StatusBarNotification[] notifs = mBinderService.getActiveNotifications(PKG);
5408 assertEquals(1, notifs.length);
5409 assertEquals(1, mService.getNotificationRecordCount());
5410 }
5411
5412
5413 @Test
Julia Reynolds088c4482019-04-10 12:43:27 -04005414 public void testGetAllowedAssistantAdjustments() throws Exception {
5415 List<String> capabilities = mBinderService.getAllowedAssistantAdjustments(null);
Julia Reynoldsad6dd352019-03-07 16:46:22 -05005416 assertNotNull(capabilities);
5417
5418 for (int i = capabilities.size() - 1; i >= 0; i--) {
5419 String capability = capabilities.get(i);
Julia Reynolds088c4482019-04-10 12:43:27 -04005420 mBinderService.disallowAssistantAdjustment(capability);
5421 assertEquals(i + 1, mBinderService.getAllowedAssistantAdjustments(null).size());
5422 List<String> currentCapabilities = mBinderService.getAllowedAssistantAdjustments(null);
Julia Reynoldsad6dd352019-03-07 16:46:22 -05005423 assertNotNull(currentCapabilities);
5424 assertFalse(currentCapabilities.contains(capability));
5425 }
5426 }
Julia Reynoldsc7dcdc22019-03-25 10:26:14 -04005427
Julia Reynolds4214da92019-04-10 15:04:06 -04005428 @Test
Julia Reynoldsc7dcdc22019-03-25 10:26:14 -04005429 public void testAdjustRestrictedKey() throws Exception {
5430 NotificationRecord r = generateNotificationRecord(mTestNotificationChannel);
Julia Reynolds4214da92019-04-10 15:04:06 -04005431 mService.addNotification(r);
5432 when(mAssistants.isSameUser(any(), anyInt())).thenReturn(true);
Julia Reynoldsc7dcdc22019-03-25 10:26:14 -04005433
5434 when(mAssistants.isAdjustmentAllowed(KEY_IMPORTANCE)).thenReturn(true);
5435 when(mAssistants.isAdjustmentAllowed(KEY_USER_SENTIMENT)).thenReturn(false);
5436
5437 Bundle signals = new Bundle();
5438 signals.putInt(KEY_IMPORTANCE, IMPORTANCE_LOW);
5439 signals.putInt(KEY_USER_SENTIMENT, USER_SENTIMENT_NEGATIVE);
Julia Reynolds24edc002020-01-29 16:35:32 -05005440 Adjustment adjustment = new Adjustment(r.getSbn().getPackageName(), r.getKey(), signals,
Julia Reynoldsc7dcdc22019-03-25 10:26:14 -04005441 "", r.getUser().getIdentifier());
5442
5443 mBinderService.applyAdjustmentFromAssistant(null, adjustment);
5444 r.applyAdjustments();
5445
5446 assertEquals(IMPORTANCE_LOW, r.getAssistantImportance());
5447 assertEquals(USER_SENTIMENT_NEUTRAL, r.getUserSentiment());
5448 }
Julia Reynolds657d1642019-03-27 12:15:57 -04005449
Julia Reynolds4214da92019-04-10 15:04:06 -04005450 @Test
Julia Reynoldsa94365d2019-04-09 10:48:43 -04005451 public void testAutomaticZenRuleValidation_policyFilterAgreement() throws Exception {
Julia Reynolds4214da92019-04-10 15:04:06 -04005452 when(mConditionProviders.isPackageOrComponentAllowed(anyString(), anyInt()))
5453 .thenReturn(true);
5454 mService.setZenHelper(mock(ZenModeHelper.class));
5455 ComponentName owner = new ComponentName(mContext, this.getClass());
Julia Reynoldsa94365d2019-04-09 10:48:43 -04005456 ZenPolicy zenPolicy = new ZenPolicy.Builder().allowAlarms(true).build();
5457 boolean isEnabled = true;
5458 AutomaticZenRule rule = new AutomaticZenRule("test", owner, owner, mock(Uri.class),
5459 zenPolicy, NotificationManager.INTERRUPTION_FILTER_NONE, isEnabled);
5460
5461 try {
5462 mBinderService.addAutomaticZenRule(rule);
Julia Reynolds4214da92019-04-10 15:04:06 -04005463 fail("Zen policy only applies to priority only mode");
Julia Reynoldsa94365d2019-04-09 10:48:43 -04005464 } catch (IllegalArgumentException e) {
5465 // yay
5466 }
5467
5468 rule = new AutomaticZenRule("test", owner, owner, mock(Uri.class),
5469 zenPolicy, NotificationManager.INTERRUPTION_FILTER_PRIORITY, isEnabled);
5470 mBinderService.addAutomaticZenRule(rule);
5471
5472 rule = new AutomaticZenRule("test", owner, owner, mock(Uri.class),
5473 null, NotificationManager.INTERRUPTION_FILTER_NONE, isEnabled);
5474 mBinderService.addAutomaticZenRule(rule);
5475 }
5476
Julia Reynolds4214da92019-04-10 15:04:06 -04005477 @Test
Julia Reynolds657d1642019-03-27 12:15:57 -04005478 public void testAreNotificationsEnabledForPackage_crossUser() throws Exception {
5479 try {
5480 mBinderService.areNotificationsEnabledForPackage(mContext.getPackageName(),
5481 mUid + UserHandle.PER_USER_RANGE);
5482 fail("Cannot call cross user without permission");
5483 } catch (SecurityException e) {
5484 // pass
5485 }
5486
5487 // cross user, with permission, no problem
Will Brockmancfd98302020-01-29 15:57:30 -05005488 enableInteractAcrossUsers();
Julia Reynolds657d1642019-03-27 12:15:57 -04005489 mBinderService.areNotificationsEnabledForPackage(mContext.getPackageName(),
5490 mUid + UserHandle.PER_USER_RANGE);
5491 }
Julia Reynolds2f7592d2019-03-27 12:17:23 -04005492
Julia Reynolds4214da92019-04-10 15:04:06 -04005493 @Test
Julia Reynolds2f7592d2019-03-27 12:17:23 -04005494 public void testAreBubblesAllowedForPackage_crossUser() throws Exception {
5495 try {
Mady Mellora92268c2020-03-09 17:25:08 -07005496 mBinderService.getBubblePreferenceForPackage(mContext.getPackageName(),
Julia Reynolds2f7592d2019-03-27 12:17:23 -04005497 mUid + UserHandle.PER_USER_RANGE);
5498 fail("Cannot call cross user without permission");
5499 } catch (SecurityException e) {
5500 // pass
5501 }
5502
5503 // cross user, with permission, no problem
Will Brockmancfd98302020-01-29 15:57:30 -05005504 enableInteractAcrossUsers();
Mady Mellora92268c2020-03-09 17:25:08 -07005505 mBinderService.getBubblePreferenceForPackage(mContext.getPackageName(),
Julia Reynolds2f7592d2019-03-27 12:17:23 -04005506 mUid + UserHandle.PER_USER_RANGE);
5507 }
Mady Mellora54e9fa2019-04-18 13:26:18 -07005508
Will Brockmancfd98302020-01-29 15:57:30 -05005509 private void enableInteractAcrossUsers() {
5510 TestablePermissions perms = mContext.getTestablePermissions();
5511 perms.setPermission(android.Manifest.permission.INTERACT_ACROSS_USERS, PERMISSION_GRANTED);
5512 }
5513
Mady Mellora54e9fa2019-04-18 13:26:18 -07005514 @Test
5515 public void testNotificationBubbleChanged_false() throws Exception {
Mady Mellora92268c2020-03-09 17:25:08 -07005516 setUpPrefsForBubbles(PKG, mUid,
5517 true /* global */,
5518 BUBBLE_PREFERENCE_ALL /* app */,
5519 true /* channel */);
Mady Mellora54e9fa2019-04-18 13:26:18 -07005520
Mady Mellor9e923e12019-12-17 16:08:46 -08005521 // Notif with bubble metadata
5522 NotificationRecord nr = generateMessageBubbleNotifRecord(mTestNotificationChannel,
5523 "testNotificationBubbleChanged_false");
Mady Mellora54e9fa2019-04-18 13:26:18 -07005524
Julia Reynolds24edc002020-01-29 16:35:32 -05005525 mBinderService.enqueueNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
5526 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
Mady Mellora54e9fa2019-04-18 13:26:18 -07005527 waitForIdle();
5528
Mady Mellor66efd5e2019-05-15 13:38:11 -07005529 // Reset as this is called when the notif is first sent
5530 reset(mListeners);
5531
Mady Mellora54e9fa2019-04-18 13:26:18 -07005532 // First we were a bubble
5533 StatusBarNotification[] notifsBefore = mBinderService.getActiveNotifications(PKG);
5534 assertEquals(1, notifsBefore.length);
5535 assertTrue((notifsBefore[0].getNotification().flags & FLAG_BUBBLE) != 0);
5536
5537 // Notify we're not a bubble
Mady Mellor9adfe6a2020-03-30 17:23:26 -07005538 mService.mNotificationDelegate.onNotificationBubbleChanged(nr.getKey(), false, 0);
Mady Mellora54e9fa2019-04-18 13:26:18 -07005539 waitForIdle();
5540
Mady Mellor3a0a1b42019-05-23 06:40:21 -07005541 // Make sure we are not a bubble
5542 StatusBarNotification[] notifsAfter = mBinderService.getActiveNotifications(PKG);
5543 assertEquals(1, notifsAfter.length);
5544 assertEquals((notifsAfter[0].getNotification().flags & FLAG_BUBBLE), 0);
Mady Mellora54e9fa2019-04-18 13:26:18 -07005545 }
5546
5547 @Test
5548 public void testNotificationBubbleChanged_true() throws Exception {
Mady Mellora92268c2020-03-09 17:25:08 -07005549 setUpPrefsForBubbles(PKG, mUid,
5550 true /* global */,
5551 BUBBLE_PREFERENCE_ALL /* app */,
5552 true /* channel */);
Mady Mellora54e9fa2019-04-18 13:26:18 -07005553
Mady Mellor9e923e12019-12-17 16:08:46 -08005554 // Notif that is not a bubble
Mady Mellora54e9fa2019-04-18 13:26:18 -07005555 NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel,
Mady Mellor9e923e12019-12-17 16:08:46 -08005556 1, null, false);
Julia Reynolds24edc002020-01-29 16:35:32 -05005557 mBinderService.enqueueNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
5558 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
Mady Mellora54e9fa2019-04-18 13:26:18 -07005559 waitForIdle();
5560
5561 // Would be a normal notification because wouldn't have met requirements to bubble
5562 StatusBarNotification[] notifsBefore = mBinderService.getActiveNotifications(PKG);
5563 assertEquals(1, notifsBefore.length);
5564 assertEquals((notifsBefore[0].getNotification().flags & FLAG_BUBBLE), 0);
5565
Mady Mellor9e923e12019-12-17 16:08:46 -08005566 // Update the notification to be message style / meet bubble requirements
5567 NotificationRecord nr2 = generateMessageBubbleNotifRecord(mTestNotificationChannel,
Julia Reynolds24edc002020-01-29 16:35:32 -05005568 nr.getSbn().getTag());
5569 mBinderService.enqueueNotificationWithTag(PKG, PKG, nr2.getSbn().getTag(),
5570 nr2.getSbn().getId(), nr2.getSbn().getNotification(), nr2.getSbn().getUserId());
Mady Mellor9e923e12019-12-17 16:08:46 -08005571 waitForIdle();
Mady Mellora54e9fa2019-04-18 13:26:18 -07005572
Mady Mellor66efd5e2019-05-15 13:38:11 -07005573 // Reset as this is called when the notif is first sent
5574 reset(mListeners);
5575
Mady Mellora54e9fa2019-04-18 13:26:18 -07005576 // Notify we are now a bubble
Mady Mellor9adfe6a2020-03-30 17:23:26 -07005577 mService.mNotificationDelegate.onNotificationBubbleChanged(nr.getKey(), true, 0);
Mady Mellora54e9fa2019-04-18 13:26:18 -07005578 waitForIdle();
5579
Mady Mellor3a0a1b42019-05-23 06:40:21 -07005580 // Make sure we are a bubble
5581 StatusBarNotification[] notifsAfter = mBinderService.getActiveNotifications(PKG);
5582 assertEquals(1, notifsAfter.length);
5583 assertTrue((notifsAfter[0].getNotification().flags & FLAG_BUBBLE) != 0);
Mady Mellora54e9fa2019-04-18 13:26:18 -07005584 }
5585
5586 @Test
5587 public void testNotificationBubbleChanged_true_notAllowed() throws Exception {
Mady Mellora92268c2020-03-09 17:25:08 -07005588 setUpPrefsForBubbles(PKG, mUid,
5589 true /* global */,
5590 BUBBLE_PREFERENCE_ALL /* app */,
5591 true /* channel */);
Mady Mellora54e9fa2019-04-18 13:26:18 -07005592
5593 // Notif that is not a bubble
Mady Mellor9e923e12019-12-17 16:08:46 -08005594 NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel);
Julia Reynolds24edc002020-01-29 16:35:32 -05005595 mBinderService.enqueueNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
5596 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
Mady Mellora54e9fa2019-04-18 13:26:18 -07005597 waitForIdle();
5598
Mady Mellor66efd5e2019-05-15 13:38:11 -07005599 // Reset as this is called when the notif is first sent
5600 reset(mListeners);
5601
Mady Mellora54e9fa2019-04-18 13:26:18 -07005602 // Would be a normal notification because wouldn't have met requirements to bubble
5603 StatusBarNotification[] notifsBefore = mBinderService.getActiveNotifications(PKG);
5604 assertEquals(1, notifsBefore.length);
5605 assertEquals((notifsBefore[0].getNotification().flags & FLAG_BUBBLE), 0);
5606
5607 // Notify we are now a bubble
Mady Mellor9adfe6a2020-03-30 17:23:26 -07005608 mService.mNotificationDelegate.onNotificationBubbleChanged(nr.getKey(), true, 0);
Mady Mellora54e9fa2019-04-18 13:26:18 -07005609 waitForIdle();
5610
5611 // We still wouldn't be a bubble because the notification didn't meet requirements
5612 StatusBarNotification[] notifsAfter = mBinderService.getActiveNotifications(PKG);
5613 assertEquals(1, notifsAfter.length);
5614 assertEquals((notifsAfter[0].getNotification().flags & FLAG_BUBBLE), 0);
5615 }
Mady Mellor5c11a2e2019-04-25 17:26:15 -07005616
5617 @Test
Mady Mellor13f9bc82020-03-24 19:09:28 -07005618 public void testNotificationBubbleIsFlagRemoved_resetOnUpdate() throws Exception {
Mady Mellora92268c2020-03-09 17:25:08 -07005619 setUpPrefsForBubbles(PKG, mUid,
5620 true /* global */,
5621 BUBBLE_PREFERENCE_ALL /* app */,
5622 true /* channel */);
5623
Mady Mellor13f9bc82020-03-24 19:09:28 -07005624 // Notif with bubble metadata
5625 NotificationRecord nr = generateMessageBubbleNotifRecord(mTestNotificationChannel,
5626 "testNotificationBubbleIsFlagRemoved_resetOnUpdate");
5627
5628 mBinderService.enqueueNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
5629 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
5630 waitForIdle();
5631 // Flag shouldn't be modified
5632 NotificationRecord recordToCheck = mService.getNotificationRecord(nr.getSbn().getKey());
5633 assertFalse(recordToCheck.isFlagBubbleRemoved());
5634
5635 // Notify we're not a bubble
Mady Mellor9adfe6a2020-03-30 17:23:26 -07005636 mService.mNotificationDelegate.onNotificationBubbleChanged(nr.getKey(), false, 0);
Mady Mellor13f9bc82020-03-24 19:09:28 -07005637 waitForIdle();
5638 // Flag should be modified
5639 recordToCheck = mService.getNotificationRecord(nr.getSbn().getKey());
5640 assertTrue(recordToCheck.isFlagBubbleRemoved());
5641
5642
5643 // Update the notif
5644 mBinderService.enqueueNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
5645 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
5646 waitForIdle();
5647 // And the flag is reset
5648 recordToCheck = mService.getNotificationRecord(nr.getSbn().getKey());
5649 assertFalse(recordToCheck.isFlagBubbleRemoved());
5650 }
5651
5652 @Test
5653 public void testNotificationBubbleIsFlagRemoved_resetOnBubbleChangedTrue() throws Exception {
Mady Mellora92268c2020-03-09 17:25:08 -07005654 setUpPrefsForBubbles(PKG, mUid,
5655 true /* global */,
5656 BUBBLE_PREFERENCE_ALL /* app */,
5657 true /* channel */);
5658
Mady Mellor13f9bc82020-03-24 19:09:28 -07005659 // Notif with bubble metadata
5660 NotificationRecord nr = generateMessageBubbleNotifRecord(mTestNotificationChannel,
5661 "testNotificationBubbleIsFlagRemoved_trueOnBubbleChangedTrue");
5662
5663 mBinderService.enqueueNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
5664 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
5665 waitForIdle();
5666 // Flag shouldn't be modified
5667 NotificationRecord recordToCheck = mService.getNotificationRecord(nr.getSbn().getKey());
5668 assertFalse(recordToCheck.isFlagBubbleRemoved());
5669
5670 // Notify we're not a bubble
Mady Mellor9adfe6a2020-03-30 17:23:26 -07005671 mService.mNotificationDelegate.onNotificationBubbleChanged(nr.getKey(), false, 0);
Mady Mellor13f9bc82020-03-24 19:09:28 -07005672 waitForIdle();
5673 // Flag should be modified
5674 recordToCheck = mService.getNotificationRecord(nr.getSbn().getKey());
5675 assertTrue(recordToCheck.isFlagBubbleRemoved());
5676
5677 // Notify we are a bubble
Mady Mellor9adfe6a2020-03-30 17:23:26 -07005678 mService.mNotificationDelegate.onNotificationBubbleChanged(nr.getKey(), true, 0);
Mady Mellor13f9bc82020-03-24 19:09:28 -07005679 waitForIdle();
5680 // And the flag is reset
5681 assertFalse(recordToCheck.isFlagBubbleRemoved());
5682 }
5683
5684 @Test
Mady Mellorf44b6832020-01-14 13:26:14 -08005685 public void testOnBubbleNotificationSuppressionChanged() throws Exception {
Mady Mellora92268c2020-03-09 17:25:08 -07005686 setUpPrefsForBubbles(PKG, mUid,
5687 true /* global */,
5688 BUBBLE_PREFERENCE_ALL /* app */,
5689 true /* channel */);
Mady Mellor56515c42020-02-18 17:58:36 -08005690
Mady Mellorf44b6832020-01-14 13:26:14 -08005691 // Bubble notification
5692 NotificationRecord nr = generateMessageBubbleNotifRecord(mTestNotificationChannel, "tag");
5693
Julia Reynolds24edc002020-01-29 16:35:32 -05005694 mBinderService.enqueueNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
5695 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
Mady Mellorf44b6832020-01-14 13:26:14 -08005696 waitForIdle();
5697
5698 // NOT suppressed
5699 Notification n = mBinderService.getActiveNotifications(PKG)[0].getNotification();
5700 assertFalse(n.getBubbleMetadata().isNotificationSuppressed());
5701
5702 // Reset as this is called when the notif is first sent
5703 reset(mListeners);
5704
5705 // Test: update suppression to true
5706 mService.mNotificationDelegate.onBubbleNotificationSuppressionChanged(nr.getKey(), true);
5707 waitForIdle();
5708
5709 // Check
5710 n = mBinderService.getActiveNotifications(PKG)[0].getNotification();
5711 assertTrue(n.getBubbleMetadata().isNotificationSuppressed());
5712
5713 // Reset to check again
5714 reset(mListeners);
5715
5716 // Test: update suppression to false
5717 mService.mNotificationDelegate.onBubbleNotificationSuppressionChanged(nr.getKey(), false);
5718 waitForIdle();
5719
5720 // Check
5721 n = mBinderService.getActiveNotifications(PKG)[0].getNotification();
5722 assertFalse(n.getBubbleMetadata().isNotificationSuppressed());
5723 }
5724
5725 @Test
Aran Inkfd2bfd32019-10-04 16:30:01 -04005726 public void testGrantInlineReplyUriPermission_recordExists() throws Exception {
5727 NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel, 0);
5728 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Julia Reynolds24edc002020-01-29 16:35:32 -05005729 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
Aran Inkfd2bfd32019-10-04 16:30:01 -04005730 waitForIdle();
5731
5732 // A notification exists for the given record
5733 StatusBarNotification[] notifsBefore = mBinderService.getActiveNotifications(PKG);
5734 assertEquals(1, notifsBefore.length);
5735
5736 reset(mPackageManager);
5737
5738 Uri uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 1);
5739
5740 mService.mNotificationDelegate.grantInlineReplyUriPermission(
Julia Reynolds24edc002020-01-29 16:35:32 -05005741 nr.getKey(), uri, nr.getSbn().getUser(), nr.getSbn().getPackageName(),
5742 nr.getSbn().getUid());
Aran Inkfd2bfd32019-10-04 16:30:01 -04005743
5744 // Grant permission called for the UID of SystemUI under the target user ID
5745 verify(mUgm, times(1)).grantUriPermissionFromOwner(any(),
Julia Reynolds24edc002020-01-29 16:35:32 -05005746 eq(nr.getSbn().getUid()), eq(nr.getSbn().getPackageName()), eq(uri), anyInt(),
5747 anyInt(), eq(nr.getSbn().getUserId()));
Aran Inkfd2bfd32019-10-04 16:30:01 -04005748 }
5749
5750 @Test
Aran Ink979c9762019-10-24 16:09:45 -04005751 public void testGrantInlineReplyUriPermission_noRecordExists() throws Exception {
5752 NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel, 0);
5753 waitForIdle();
5754
5755 // No notifications exist for the given record
5756 StatusBarNotification[] notifsBefore = mBinderService.getActiveNotifications(PKG);
5757 assertEquals(0, notifsBefore.length);
5758
5759 Uri uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 1);
5760 int uid = 0; // sysui on primary user
5761
5762 mService.mNotificationDelegate.grantInlineReplyUriPermission(
Julia Reynolds24edc002020-01-29 16:35:32 -05005763 nr.getKey(), uri, nr.getSbn().getUser(), nr.getSbn().getPackageName(),
5764 nr.getSbn().getUid());
Aran Ink979c9762019-10-24 16:09:45 -04005765
5766 // Grant permission still called if no NotificationRecord exists for the given key
5767 verify(mUgm, times(1)).grantUriPermissionFromOwner(any(),
Julia Reynolds24edc002020-01-29 16:35:32 -05005768 eq(nr.getSbn().getUid()), eq(nr.getSbn().getPackageName()), eq(uri), anyInt(),
5769 anyInt(), eq(nr.getSbn().getUserId()));
Aran Ink979c9762019-10-24 16:09:45 -04005770 }
5771
5772 @Test
Aran Inkfd2bfd32019-10-04 16:30:01 -04005773 public void testGrantInlineReplyUriPermission_userAll() throws Exception {
5774 // generate a NotificationRecord for USER_ALL to make sure it's converted into USER_SYSTEM
5775 NotificationRecord nr =
5776 generateNotificationRecord(mTestNotificationChannel, UserHandle.USER_ALL);
5777 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Julia Reynolds24edc002020-01-29 16:35:32 -05005778 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
Aran Inkfd2bfd32019-10-04 16:30:01 -04005779 waitForIdle();
5780
5781 // A notification exists for the given record
5782 StatusBarNotification[] notifsBefore = mBinderService.getActiveNotifications(PKG);
5783 assertEquals(1, notifsBefore.length);
5784
5785 reset(mPackageManager);
5786
5787 Uri uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 1);
5788
5789 mService.mNotificationDelegate.grantInlineReplyUriPermission(
Julia Reynolds24edc002020-01-29 16:35:32 -05005790 nr.getKey(), uri, nr.getSbn().getUser(), nr.getSbn().getPackageName(),
5791 nr.getSbn().getUid());
Aran Inkfd2bfd32019-10-04 16:30:01 -04005792
5793 // Target user for the grant is USER_ALL instead of USER_SYSTEM
5794 verify(mUgm, times(1)).grantUriPermissionFromOwner(any(),
Julia Reynolds24edc002020-01-29 16:35:32 -05005795 eq(nr.getSbn().getUid()), eq(nr.getSbn().getPackageName()), eq(uri), anyInt(),
5796 anyInt(), eq(UserHandle.USER_SYSTEM));
Aran Inkfd2bfd32019-10-04 16:30:01 -04005797 }
5798
5799 @Test
5800 public void testGrantInlineReplyUriPermission_acrossUsers() throws Exception {
5801 // generate a NotificationRecord for USER_ALL to make sure it's converted into USER_SYSTEM
5802 int otherUserId = 11;
5803 NotificationRecord nr =
5804 generateNotificationRecord(mTestNotificationChannel, otherUserId);
5805 mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
Julia Reynolds24edc002020-01-29 16:35:32 -05005806 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
Aran Inkfd2bfd32019-10-04 16:30:01 -04005807 waitForIdle();
5808
5809 // A notification exists for the given record
5810 StatusBarNotification[] notifsBefore = mBinderService.getActiveNotifications(PKG);
5811 assertEquals(1, notifsBefore.length);
5812
5813 reset(mPackageManager);
5814
5815 Uri uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 1);
5816
5817 int uid = 0; // sysui on primary user
Aran Ink979c9762019-10-24 16:09:45 -04005818 int otherUserUid = (otherUserId * 100000) + 1; // sysui as a different user
Aran Inkfd2bfd32019-10-04 16:30:01 -04005819 String sysuiPackage = "sysui";
5820 final String[] sysuiPackages = new String[] { sysuiPackage };
5821 when(mPackageManager.getPackagesForUid(uid)).thenReturn(sysuiPackages);
5822
5823 // Make sure to mock call for USER_SYSTEM and not USER_ALL, since it's been replaced by the
5824 // time this is called
5825 when(mPackageManager.getPackageUid(sysuiPackage, 0, otherUserId))
5826 .thenReturn(otherUserUid);
5827
Aran Ink979c9762019-10-24 16:09:45 -04005828 mService.mNotificationDelegate.grantInlineReplyUriPermission(
Julia Reynolds24edc002020-01-29 16:35:32 -05005829 nr.getKey(), uri, nr.getSbn().getUser(), nr.getSbn().getPackageName(), uid);
Aran Inkfd2bfd32019-10-04 16:30:01 -04005830
5831 // Target user for the grant is USER_ALL instead of USER_SYSTEM
5832 verify(mUgm, times(1)).grantUriPermissionFromOwner(any(),
Julia Reynolds24edc002020-01-29 16:35:32 -05005833 eq(otherUserUid), eq(nr.getSbn().getPackageName()), eq(uri), anyInt(), anyInt(),
Aran Inkfd2bfd32019-10-04 16:30:01 -04005834 eq(otherUserId));
5835 }
5836
5837 @Test
Aran Ink979c9762019-10-24 16:09:45 -04005838 public void testClearInlineReplyUriPermission_uriRecordExists() throws Exception {
5839 NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel, 0);
5840 reset(mPackageManager);
Aran Inkfd2bfd32019-10-04 16:30:01 -04005841
Aran Ink979c9762019-10-24 16:09:45 -04005842 Uri uri1 = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 1);
5843 Uri uri2 = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 2);
Aran Inkfd2bfd32019-10-04 16:30:01 -04005844
Aran Ink979c9762019-10-24 16:09:45 -04005845 // create an inline record with two uris in it
5846 mService.mNotificationDelegate.grantInlineReplyUriPermission(
Julia Reynolds24edc002020-01-29 16:35:32 -05005847 nr.getKey(), uri1, nr.getSbn().getUser(), nr.getSbn().getPackageName(),
5848 nr.getSbn().getUid());
Aran Ink979c9762019-10-24 16:09:45 -04005849 mService.mNotificationDelegate.grantInlineReplyUriPermission(
Julia Reynolds24edc002020-01-29 16:35:32 -05005850 nr.getKey(), uri2, nr.getSbn().getUser(), nr.getSbn().getPackageName(),
5851 nr.getSbn().getUid());
Aran Inkfd2bfd32019-10-04 16:30:01 -04005852
Aran Ink979c9762019-10-24 16:09:45 -04005853 InlineReplyUriRecord record = mService.mInlineReplyRecordsByKey.get(nr.getKey());
5854 assertNotNull(record); // record exists
5855 assertEquals(record.getUris().size(), 2); // record has two uris in it
Aran Inkfd2bfd32019-10-04 16:30:01 -04005856
Julia Reynolds24edc002020-01-29 16:35:32 -05005857 mService.mNotificationDelegate.clearInlineReplyUriPermissions(nr.getKey(),
5858 nr.getSbn().getUid());
Aran Ink979c9762019-10-24 16:09:45 -04005859
5860 // permissionOwner destroyed
5861 verify(mUgmInternal, times(1)).revokeUriPermissionFromOwner(
5862 eq(record.getPermissionOwner()), eq(null), eq(~0), eq(nr.getUserId()));
5863 }
5864
5865
5866 @Test
5867 public void testClearInlineReplyUriPermission_noUriRecordExists() throws Exception {
5868 NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel, 0);
5869 reset(mPackageManager);
5870
Julia Reynolds24edc002020-01-29 16:35:32 -05005871 mService.mNotificationDelegate.clearInlineReplyUriPermissions(nr.getKey(),
5872 nr.getSbn().getUid());
Aran Ink979c9762019-10-24 16:09:45 -04005873
5874 // no permissionOwner destroyed
5875 verify(mUgmInternal, times(0)).revokeUriPermissionFromOwner(
5876 any(), eq(null), eq(~0), eq(nr.getUserId()));
5877 }
5878
5879 @Test
5880 public void testClearInlineReplyUriPermission_userAll() throws Exception {
5881 NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel,
5882 UserHandle.USER_ALL);
5883 reset(mPackageManager);
5884
5885 Uri uri1 = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 1);
5886 Uri uri2 = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 2);
5887
5888 // create an inline record a uri in it
5889 mService.mNotificationDelegate.grantInlineReplyUriPermission(
Julia Reynolds24edc002020-01-29 16:35:32 -05005890 nr.getKey(), uri1, nr.getSbn().getUser(), nr.getSbn().getPackageName(),
5891 nr.getSbn().getUid());
Aran Ink979c9762019-10-24 16:09:45 -04005892
5893 InlineReplyUriRecord record = mService.mInlineReplyRecordsByKey.get(nr.getKey());
5894 assertNotNull(record); // record exists
5895
Julia Reynolds24edc002020-01-29 16:35:32 -05005896 mService.mNotificationDelegate.clearInlineReplyUriPermissions(
5897 nr.getKey(), nr.getSbn().getUid());
Aran Ink979c9762019-10-24 16:09:45 -04005898
5899 // permissionOwner destroyed for USER_SYSTEM, not USER_ALL
5900 verify(mUgmInternal, times(1)).revokeUriPermissionFromOwner(
5901 eq(record.getPermissionOwner()), eq(null), eq(~0), eq(USER_SYSTEM));
Aran Inkfd2bfd32019-10-04 16:30:01 -04005902 }
5903
5904 @Test
Mady Mellor5c11a2e2019-04-25 17:26:15 -07005905 public void testNotificationBubbles_disabled_lowRamDevice() throws Exception {
Mady Mellora92268c2020-03-09 17:25:08 -07005906 setUpPrefsForBubbles(PKG, mUid,
5907 true /* global */,
5908 BUBBLE_PREFERENCE_ALL /* app */,
5909 true /* channel */);
Mady Mellor5c11a2e2019-04-25 17:26:15 -07005910
Mady Mellor9e923e12019-12-17 16:08:46 -08005911 // And we are low ram
5912 when(mActivityManager.isLowRamDevice()).thenReturn(true);
5913
5914 // Notification that would typically bubble
5915 NotificationRecord nr = generateMessageBubbleNotifRecord(mTestNotificationChannel,
5916 "testNotificationBubbles_disabled_lowRamDevice");
Julia Reynolds24edc002020-01-29 16:35:32 -05005917 mBinderService.enqueueNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
5918 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
Mady Mellor5c11a2e2019-04-25 17:26:15 -07005919 waitForIdle();
5920
Mady Mellor9e923e12019-12-17 16:08:46 -08005921 // But we wouldn't be a bubble because the device is low ram & all bubbles are disabled.
Mady Mellor5c11a2e2019-04-25 17:26:15 -07005922 StatusBarNotification[] notifsAfter = mBinderService.getActiveNotifications(PKG);
5923 assertEquals(1, notifsAfter.length);
5924 assertEquals((notifsAfter[0].getNotification().flags & FLAG_BUBBLE), 0);
Mady Mellor5c11a2e2019-04-25 17:26:15 -07005925 }
Julia Reynoldsb681ffe2019-06-19 13:40:46 -04005926
5927 @Test
5928 public void testRemoveLargeRemoteViews() throws Exception {
5929 int removeSize = mContext.getResources().getInteger(
5930 com.android.internal.R.integer.config_notificationStripRemoteViewSizeBytes);
5931
5932 RemoteViews rv = mock(RemoteViews.class);
5933 when(rv.estimateMemoryUsage()).thenReturn(removeSize);
5934 when(rv.clone()).thenReturn(rv);
5935 RemoteViews rv1 = mock(RemoteViews.class);
5936 when(rv1.estimateMemoryUsage()).thenReturn(removeSize);
5937 when(rv1.clone()).thenReturn(rv1);
5938 RemoteViews rv2 = mock(RemoteViews.class);
5939 when(rv2.estimateMemoryUsage()).thenReturn(removeSize);
5940 when(rv2.clone()).thenReturn(rv2);
5941 RemoteViews rv3 = mock(RemoteViews.class);
5942 when(rv3.estimateMemoryUsage()).thenReturn(removeSize);
5943 when(rv3.clone()).thenReturn(rv3);
5944 RemoteViews rv4 = mock(RemoteViews.class);
5945 when(rv4.estimateMemoryUsage()).thenReturn(removeSize);
5946 when(rv4.clone()).thenReturn(rv4);
5947 // note: different!
5948 RemoteViews rv5 = mock(RemoteViews.class);
5949 when(rv5.estimateMemoryUsage()).thenReturn(removeSize - 1);
5950 when(rv5.clone()).thenReturn(rv5);
5951
5952 Notification np = new Notification.Builder(mContext, "test")
5953 .setSmallIcon(android.R.drawable.sym_def_app_icon)
5954 .setContentText("test")
5955 .setCustomContentView(rv)
5956 .setCustomBigContentView(rv1)
5957 .setCustomHeadsUpContentView(rv2)
5958 .build();
5959 Notification n = new Notification.Builder(mContext, "test")
5960 .setSmallIcon(android.R.drawable.sym_def_app_icon)
5961 .setContentText("test")
5962 .setCustomContentView(rv3)
5963 .setCustomBigContentView(rv4)
5964 .setCustomHeadsUpContentView(rv5)
5965 .setPublicVersion(np)
5966 .build();
5967
5968 assertNotNull(np.contentView);
5969 assertNotNull(np.bigContentView);
5970 assertNotNull(np.headsUpContentView);
5971
5972 assertTrue(n.publicVersion.extras.containsKey(Notification.EXTRA_CONTAINS_CUSTOM_VIEW));
5973 assertNotNull(n.publicVersion.contentView);
5974 assertNotNull(n.publicVersion.bigContentView);
5975 assertNotNull(n.publicVersion.headsUpContentView);
5976
5977 mService.fixNotification(n, PKG, "tag", 9, 0);
5978
5979 assertNull(n.contentView);
5980 assertNull(n.bigContentView);
5981 assertNotNull(n.headsUpContentView);
5982 assertNull(n.publicVersion.contentView);
5983 assertNull(n.publicVersion.bigContentView);
5984 assertNull(n.publicVersion.headsUpContentView);
5985
5986 verify(mUsageStats, times(5)).registerImageRemoved(PKG);
5987 }
Mady Mellor06b770c2019-08-29 18:01:00 -07005988
Colin Cross5ea7fb72019-12-18 17:16:36 -08005989 @Test
Mady Mellora7731962019-06-17 17:57:02 -07005990 public void testNotificationBubbles_flagAutoExpandForeground_fails_notForeground()
5991 throws Exception {
Mady Mellora92268c2020-03-09 17:25:08 -07005992 setUpPrefsForBubbles(PKG, mUid,
5993 true /* global */,
5994 BUBBLE_PREFERENCE_ALL /* app */,
5995 true /* channel */);
Mady Mellora7731962019-06-17 17:57:02 -07005996
Mady Mellor9e923e12019-12-17 16:08:46 -08005997 NotificationRecord nr = generateMessageBubbleNotifRecord(mTestNotificationChannel,
5998 "testNotificationBubbles_flagAutoExpandForeground_fails_notForeground");
5999 // Modify metadata flags
Julia Reynolds24edc002020-01-29 16:35:32 -05006000 nr.getSbn().getNotification().getBubbleMetadata().setFlags(
Mady Mellor9e923e12019-12-17 16:08:46 -08006001 Notification.BubbleMetadata.FLAG_AUTO_EXPAND_BUBBLE
6002 | Notification.BubbleMetadata.FLAG_SUPPRESS_NOTIFICATION);
Mady Mellora7731962019-06-17 17:57:02 -07006003
6004 // Ensure we're not foreground
Julia Reynolds24edc002020-01-29 16:35:32 -05006005 when(mActivityManager.getPackageImportance(nr.getSbn().getPackageName())).thenReturn(
Mady Mellora7731962019-06-17 17:57:02 -07006006 IMPORTANCE_VISIBLE);
6007
Julia Reynolds24edc002020-01-29 16:35:32 -05006008 mBinderService.enqueueNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
6009 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
Mady Mellora7731962019-06-17 17:57:02 -07006010 waitForIdle();
6011
6012 // yes allowed, yes messaging, yes bubble
Julia Reynolds24edc002020-01-29 16:35:32 -05006013 Notification notif = mService.getNotificationRecord(nr.getSbn().getKey()).getNotification();
Mady Mellora7731962019-06-17 17:57:02 -07006014 assertTrue(notif.isBubbleNotification());
6015
6016 // Our flags should have failed since we're not foreground
6017 assertFalse(notif.getBubbleMetadata().getAutoExpandBubble());
6018 assertFalse(notif.getBubbleMetadata().isNotificationSuppressed());
6019 }
6020
6021 @Test
6022 public void testNotificationBubbles_flagAutoExpandForeground_succeeds_foreground()
6023 throws RemoteException {
Mady Mellora92268c2020-03-09 17:25:08 -07006024 setUpPrefsForBubbles(PKG, mUid,
6025 true /* global */,
6026 BUBBLE_PREFERENCE_ALL /* app */,
6027 true /* channel */);
Mady Mellora7731962019-06-17 17:57:02 -07006028
Mady Mellor9e923e12019-12-17 16:08:46 -08006029 NotificationRecord nr = generateMessageBubbleNotifRecord(mTestNotificationChannel,
6030 "testNotificationBubbles_flagAutoExpandForeground_succeeds_foreground");
6031 // Modify metadata flags
Julia Reynolds24edc002020-01-29 16:35:32 -05006032 nr.getSbn().getNotification().getBubbleMetadata().setFlags(
Mady Mellor9e923e12019-12-17 16:08:46 -08006033 Notification.BubbleMetadata.FLAG_AUTO_EXPAND_BUBBLE
6034 | Notification.BubbleMetadata.FLAG_SUPPRESS_NOTIFICATION);
Mady Mellora7731962019-06-17 17:57:02 -07006035
6036 // Ensure we are in the foreground
Julia Reynolds24edc002020-01-29 16:35:32 -05006037 when(mActivityManager.getPackageImportance(nr.getSbn().getPackageName())).thenReturn(
Mady Mellora7731962019-06-17 17:57:02 -07006038 IMPORTANCE_FOREGROUND);
6039
Julia Reynolds24edc002020-01-29 16:35:32 -05006040 mBinderService.enqueueNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
6041 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
Mady Mellora7731962019-06-17 17:57:02 -07006042 waitForIdle();
6043
6044 // yes allowed, yes messaging, yes bubble
Julia Reynolds24edc002020-01-29 16:35:32 -05006045 Notification notif = mService.getNotificationRecord(nr.getSbn().getKey()).getNotification();
Mady Mellora7731962019-06-17 17:57:02 -07006046 assertTrue(notif.isBubbleNotification());
6047
Mady Mellor9e923e12019-12-17 16:08:46 -08006048 // Our flags should have passed since we are foreground
Mady Mellora7731962019-06-17 17:57:02 -07006049 assertTrue(notif.getBubbleMetadata().getAutoExpandBubble());
6050 assertTrue(notif.getBubbleMetadata().isNotificationSuppressed());
6051 }
Mady Mellor22f2f072019-04-18 13:26:18 -07006052
6053 @Test
Mady Mellor2ac2d3a2020-01-08 17:18:54 -08006054 public void testNotificationBubbles_flagRemoved_whenShortcutRemoved()
6055 throws RemoteException {
Mady Mellora92268c2020-03-09 17:25:08 -07006056 setUpPrefsForBubbles(PKG, mUid,
6057 true /* global */,
6058 BUBBLE_PREFERENCE_ALL /* app */,
6059 true /* channel */);
Mady Mellor2ac2d3a2020-01-08 17:18:54 -08006060
6061 ArgumentCaptor<LauncherApps.Callback> launcherAppsCallback =
6062 ArgumentCaptor.forClass(LauncherApps.Callback.class);
6063
6064 // Messaging notification with shortcut info
6065 Notification.BubbleMetadata metadata =
Mady Melloraa9ce172020-03-17 10:34:20 -07006066 new Notification.BubbleMetadata.Builder("someshortcutId").build();
Mady Mellor2ac2d3a2020-01-08 17:18:54 -08006067 Notification.Builder nb = getMessageStyleNotifBuilder(false /* addDefaultMetadata */,
6068 null /* groupKey */, false /* isSummary */);
6069 nb.setBubbleMetadata(metadata);
6070 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1,
6071 "tag", mUid, 0, nb.build(), new UserHandle(mUid), null, 0);
6072 NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
6073
6074 // Pretend the shortcut exists
6075 List<ShortcutInfo> shortcutInfos = new ArrayList<>();
Julia Reynoldsd61bdf12020-02-25 12:25:07 -05006076 ShortcutInfo info = mock(ShortcutInfo.class);
6077 when(info.isLongLived()).thenReturn(true);
Julia Reynoldsfa273072020-04-14 15:31:21 -04006078 when(info.isEnabled()).thenReturn(true);
Julia Reynoldsd61bdf12020-02-25 12:25:07 -05006079 shortcutInfos.add(info);
Mady Mellor2ac2d3a2020-01-08 17:18:54 -08006080 when(mLauncherApps.getShortcuts(any(), any())).thenReturn(shortcutInfos);
Julia Reynoldsfa273072020-04-14 15:31:21 -04006081 when(mShortcutServiceInternal.isSharingShortcut(anyInt(), anyString(), anyString(),
6082 anyString(), anyInt(), any())).thenReturn(true);
Mady Mellor2ac2d3a2020-01-08 17:18:54 -08006083
6084 // Test: Send the bubble notification
Julia Reynolds24edc002020-01-29 16:35:32 -05006085 mBinderService.enqueueNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
6086 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
Mady Mellor2ac2d3a2020-01-08 17:18:54 -08006087 waitForIdle();
6088
6089 // Verify:
6090
6091 // Make sure we register the callback for shortcut changes
6092 verify(mLauncherApps, times(1)).registerCallback(launcherAppsCallback.capture(), any());
6093
6094 // yes allowed, yes messaging w/shortcut, yes bubble
Julia Reynolds24edc002020-01-29 16:35:32 -05006095 Notification notif = mService.getNotificationRecord(nr.getSbn().getKey()).getNotification();
Mady Mellor2ac2d3a2020-01-08 17:18:54 -08006096 assertTrue(notif.isBubbleNotification());
6097
6098 // Test: Remove the shortcut
Mady Mellor56515c42020-02-18 17:58:36 -08006099 when(mLauncherApps.getShortcuts(any(), any())).thenReturn(null);
Mady Mellor2ac2d3a2020-01-08 17:18:54 -08006100 launcherAppsCallback.getValue().onShortcutsChanged(PKG, Collections.emptyList(),
6101 new UserHandle(mUid));
Mady Mellor56515c42020-02-18 17:58:36 -08006102 waitForIdle();
Mady Mellor2ac2d3a2020-01-08 17:18:54 -08006103
6104 // Verify:
6105
6106 // Make sure callback is unregistered
6107 verify(mLauncherApps, times(1)).unregisterCallback(launcherAppsCallback.getValue());
6108
6109 // We're no longer a bubble
Julia Reynoldsd61bdf12020-02-25 12:25:07 -05006110 Notification notif2 = mService.getNotificationRecord(
6111 nr.getSbn().getKey()).getNotification();
Mady Mellor2ac2d3a2020-01-08 17:18:54 -08006112 assertFalse(notif2.isBubbleNotification());
6113 }
6114
Mady Mellor56515c42020-02-18 17:58:36 -08006115
6116 @Test
6117 public void testNotificationBubbles_shortcut_stopListeningWhenNotifRemoved()
6118 throws RemoteException {
Mady Mellora92268c2020-03-09 17:25:08 -07006119 setUpPrefsForBubbles(PKG, mUid,
6120 true /* global */,
6121 BUBBLE_PREFERENCE_ALL /* app */,
6122 true /* channel */);
Mady Mellor56515c42020-02-18 17:58:36 -08006123
6124 ArgumentCaptor<LauncherApps.Callback> launcherAppsCallback =
6125 ArgumentCaptor.forClass(LauncherApps.Callback.class);
6126
6127 // Messaging notification with shortcut info
Mady Melloraa9ce172020-03-17 10:34:20 -07006128 Notification.BubbleMetadata metadata = new Notification.BubbleMetadata.Builder(
6129 "someshortcutId").build();
Mady Mellor56515c42020-02-18 17:58:36 -08006130 Notification.Builder nb = getMessageStyleNotifBuilder(false /* addDefaultMetadata */,
6131 null /* groupKey */, false /* isSummary */);
6132 nb.setBubbleMetadata(metadata);
6133 StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1,
6134 "tag", mUid, 0, nb.build(), new UserHandle(mUid), null, 0);
6135 NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
6136
6137 // Pretend the shortcut exists
6138 List<ShortcutInfo> shortcutInfos = new ArrayList<>();
6139 ShortcutInfo info = mock(ShortcutInfo.class);
6140 when(info.isLongLived()).thenReturn(true);
Julia Reynoldsfa273072020-04-14 15:31:21 -04006141 when(info.isEnabled()).thenReturn(true);
Mady Mellor56515c42020-02-18 17:58:36 -08006142 shortcutInfos.add(info);
6143 when(mLauncherApps.getShortcuts(any(), any())).thenReturn(shortcutInfos);
Julia Reynoldsfa273072020-04-14 15:31:21 -04006144 when(mShortcutServiceInternal.isSharingShortcut(anyInt(), anyString(), anyString(),
6145 anyString(), anyInt(), any())).thenReturn(true);
Mady Mellor56515c42020-02-18 17:58:36 -08006146
6147 // Test: Send the bubble notification
6148 mBinderService.enqueueNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
6149 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
6150 waitForIdle();
6151
6152 // Verify:
6153
6154 // Make sure we register the callback for shortcut changes
6155 verify(mLauncherApps, times(1)).registerCallback(launcherAppsCallback.capture(), any());
6156
6157 // yes allowed, yes messaging w/shortcut, yes bubble
6158 Notification notif = mService.getNotificationRecord(nr.getSbn().getKey()).getNotification();
6159 assertTrue(notif.isBubbleNotification());
6160
6161 // Test: Remove the notification
6162 mBinderService.cancelNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
6163 nr.getSbn().getId(), nr.getSbn().getUserId());
6164 waitForIdle();
6165
6166 // Verify:
6167
6168 // Make sure callback is unregistered
6169 verify(mLauncherApps, times(1)).unregisterCallback(launcherAppsCallback.getValue());
6170 }
6171
Mady Mellor2ac2d3a2020-01-08 17:18:54 -08006172 @Test
Mady Mellor22f2f072019-04-18 13:26:18 -07006173 public void testNotificationBubbles_bubbleChildrenStay_whenGroupSummaryDismissed()
6174 throws Exception {
Mady Mellora92268c2020-03-09 17:25:08 -07006175 setUpPrefsForBubbles(PKG, mUid,
6176 true /* global */,
6177 BUBBLE_PREFERENCE_ALL /* app */,
6178 true /* channel */);
Mady Mellor22f2f072019-04-18 13:26:18 -07006179
6180 NotificationRecord nrSummary = addGroupWithBubblesAndValidateAdded(
6181 true /* summaryAutoCancel */);
6182
6183 // Dismiss summary
6184 final NotificationVisibility nv = NotificationVisibility.obtain(nrSummary.getKey(), 1, 2,
6185 true);
Julia Reynolds24edc002020-01-29 16:35:32 -05006186 mService.mNotificationDelegate.onNotificationClear(mUid, 0, PKG,
6187 nrSummary.getSbn().getTag(),
6188 nrSummary.getSbn().getId(), nrSummary.getUserId(), nrSummary.getKey(),
Mady Mellor22f2f072019-04-18 13:26:18 -07006189 NotificationStats.DISMISSAL_SHADE,
6190 NotificationStats.DISMISS_SENTIMENT_NEUTRAL, nv);
6191 waitForIdle();
6192
6193 // The bubble should still exist
6194 StatusBarNotification[] notifsAfter = mBinderService.getActiveNotifications(PKG);
6195 assertEquals(1, notifsAfter.length);
6196 }
6197
6198 @Test
6199 public void testNotificationBubbles_bubbleChildrenStay_whenGroupSummaryClicked()
6200 throws Exception {
Mady Mellora92268c2020-03-09 17:25:08 -07006201 setUpPrefsForBubbles(PKG, mUid,
6202 true /* global */,
6203 BUBBLE_PREFERENCE_ALL /* app */,
6204 true /* channel */);
Mady Mellor22f2f072019-04-18 13:26:18 -07006205
6206 NotificationRecord nrSummary = addGroupWithBubblesAndValidateAdded(
6207 true /* summaryAutoCancel */);
6208
6209 // Click summary
6210 final NotificationVisibility nv = NotificationVisibility.obtain(nrSummary.getKey(), 1, 2,
6211 true);
6212 mService.mNotificationDelegate.onNotificationClick(mUid, Binder.getCallingPid(),
6213 nrSummary.getKey(), nv);
6214 waitForIdle();
6215
6216 // The bubble should still exist
6217 StatusBarNotification[] notifsAfter = mBinderService.getActiveNotifications(PKG);
6218 assertEquals(1, notifsAfter.length);
Will Brockman9918db92020-03-06 16:48:39 -05006219
6220 // Check we got the click log and associated dismissal logs
6221 assertEquals(6, mNotificationRecordLogger.numCalls());
6222 // Skip the notification-creation logs
6223 assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_CLICKED,
6224 mNotificationRecordLogger.event(3));
6225 assertEquals(NotificationRecordLogger.NotificationCancelledEvent.NOTIFICATION_CANCEL_CLICK,
6226 mNotificationRecordLogger.event(4));
6227 assertEquals(NotificationRecordLogger.NotificationCancelledEvent
6228 .NOTIFICATION_CANCEL_GROUP_SUMMARY_CANCELED,
6229 mNotificationRecordLogger.event(5));
Mady Mellor22f2f072019-04-18 13:26:18 -07006230 }
Julia Reynolds57a974b2019-10-07 11:51:47 -04006231
6232 @Test
Beverly9e6a7642020-02-13 10:11:29 -05006233 public void testNotificationBubbles_bubbleStays_whenClicked()
6234 throws Exception {
Mady Mellora92268c2020-03-09 17:25:08 -07006235 setUpPrefsForBubbles(PKG, mUid,
6236 true /* global */,
6237 BUBBLE_PREFERENCE_ALL /* app */,
6238 true /* channel */);
6239
Beverly9e6a7642020-02-13 10:11:29 -05006240 // GIVEN a notification that has the auto cancels flag (cancel on click) and is a bubble
Beverly9e6a7642020-02-13 10:11:29 -05006241 final NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel);
6242 nr.getSbn().getNotification().flags |= FLAG_BUBBLE | FLAG_AUTO_CANCEL;
6243 mService.addNotification(nr);
6244
6245 // WHEN we click the notification
6246 final NotificationVisibility nv = NotificationVisibility.obtain(nr.getKey(), 1, 2, true);
6247 mService.mNotificationDelegate.onNotificationClick(mUid, Binder.getCallingPid(),
6248 nr.getKey(), nv);
6249 waitForIdle();
6250
6251 // THEN the bubble should still exist
6252 StatusBarNotification[] notifsAfter = mBinderService.getActiveNotifications(PKG);
6253 assertEquals(1, notifsAfter.length);
Will Brockman9918db92020-03-06 16:48:39 -05006254
6255 // Check we got the click log
6256 assertEquals(1, mNotificationRecordLogger.numCalls());
6257 assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_CLICKED,
6258 mNotificationRecordLogger.event(0));
Beverly9e6a7642020-02-13 10:11:29 -05006259 }
6260
6261 @Test
Julia Reynolds57a974b2019-10-07 11:51:47 -04006262 public void testLoadDefaultApprovedServices_emptyResources() {
6263 TestableResources tr = mContext.getOrCreateTestableResources();
6264 tr.addOverride(com.android.internal.R.string.config_defaultListenerAccessPackages, "");
6265 tr.addOverride(com.android.internal.R.string.config_defaultDndAccessPackages, "");
6266 tr.addOverride(com.android.internal.R.string.config_defaultAssistantAccessComponent, "");
6267 setDefaultAssistantInDeviceConfig("");
6268
6269 mService.loadDefaultApprovedServices(USER_SYSTEM);
6270
6271 verify(mListeners, never()).addDefaultComponentOrPackage(anyString());
6272 verify(mConditionProviders, never()).addDefaultComponentOrPackage(anyString());
6273 verify(mAssistants, never()).addDefaultComponentOrPackage(anyString());
6274 }
6275
6276 @Test
6277 public void testLoadDefaultApprovedServices_dnd() {
6278 TestableResources tr = mContext.getOrCreateTestableResources();
6279 tr.addOverride(com.android.internal.R.string.config_defaultDndAccessPackages, "test");
6280 when(mListeners.queryPackageForServices(anyString(), anyInt(), anyInt()))
6281 .thenReturn(new ArraySet<>());
6282
6283 mService.loadDefaultApprovedServices(USER_SYSTEM);
6284
Jay Aliomer76e1f2722020-03-05 12:36:38 -05006285 verify(mConditionProviders, times(1)).loadDefaultsFromConfig();
Julia Reynolds57a974b2019-10-07 11:51:47 -04006286 }
6287
6288 // TODO: add tests for the rest of the non-empty cases
Julia Reynoldsb317ff72019-11-26 14:20:51 -05006289
6290 @Test
6291 public void testOnUnlockUser() {
6292 UserInfo ui = new UserInfo();
6293 ui.id = 10;
6294 mService.onUnlockUser(ui);
6295 waitForIdle();
6296
6297 verify(mHistoryManager, timeout(MAX_POST_DELAY).times(1)).onUserUnlocked(ui.id);
6298 }
6299
6300 @Test
6301 public void testOnStopUser() {
6302 UserInfo ui = new UserInfo();
6303 ui.id = 10;
6304 mService.onStopUser(ui);
6305 waitForIdle();
6306
6307 verify(mHistoryManager, timeout(MAX_POST_DELAY).times(1)).onUserStopped(ui.id);
6308 }
6309
6310 @Test
6311 public void testOnBootPhase() {
6312 mService.onBootPhase(SystemService.PHASE_ACTIVITY_MANAGER_READY);
6313
6314 verify(mHistoryManager, never()).onBootPhaseAppsCanStart();
6315
6316 mService.onBootPhase(SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
6317
6318 verify(mHistoryManager, times(1)).onBootPhaseAppsCanStart();
6319 }
6320
6321 @Test
6322 public void testHandleOnPackageChanged() {
6323 String[] pkgs = new String[] {PKG, PKG_N_MR1};
6324 int[] uids = new int[] {mUid, UserHandle.PER_USER_RANGE + 1};
6325
6326 mService.handleOnPackageChanged(false, USER_SYSTEM, pkgs, uids);
6327
6328 verify(mHistoryManager, never()).onPackageRemoved(anyInt(), anyString());
6329
6330 mService.handleOnPackageChanged(true, USER_SYSTEM, pkgs, uids);
6331
6332 verify(mHistoryManager, times(1)).onPackageRemoved(UserHandle.getUserId(uids[0]), pkgs[0]);
6333 verify(mHistoryManager, times(1)).onPackageRemoved(UserHandle.getUserId(uids[1]), pkgs[1]);
6334 }
6335
6336 @Test
6337 public void testNotificationHistory_addNoisyNotification() throws Exception {
6338 NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel,
Mady Mellor9e923e12019-12-17 16:08:46 -08006339 null /* tvExtender */);
Julia Reynolds24edc002020-01-29 16:35:32 -05006340 mBinderService.enqueueNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
6341 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
Julia Reynoldsb317ff72019-11-26 14:20:51 -05006342 waitForIdle();
6343
6344 verify(mHistoryManager, times(1)).addNotification(any());
6345 }
Julia Reynolds0f767342019-12-18 09:11:55 -05006346
6347 @Test
6348 public void createConversationNotificationChannel() throws Exception {
6349 NotificationChannel original = new NotificationChannel("a", "a", IMPORTANCE_HIGH);
6350 original.setAllowBubbles(!original.canBubble());
6351 original.setShowBadge(!original.canShowBadge());
6352
6353 Parcel parcel = Parcel.obtain();
6354 original.writeToParcel(parcel, 0);
6355 parcel.setDataPosition(0);
6356 NotificationChannel orig = NotificationChannel.CREATOR.createFromParcel(parcel);
6357 assertEquals(original, orig);
6358 assertFalse(TextUtils.isEmpty(orig.getName()));
6359
6360 mBinderService.createNotificationChannels(PKG, new ParceledListSlice(Arrays.asList(
6361 orig)));
6362
Julia Reynolds7c267522020-01-16 11:26:41 -05006363 mBinderService.createConversationNotificationChannelForPackage(
6364 PKG, mUid, "key", orig, "friend");
Julia Reynolds0f767342019-12-18 09:11:55 -05006365
6366 NotificationChannel friendChannel = mBinderService.getConversationNotificationChannel(
Julia Reynolds12ba4cf2020-01-10 16:01:38 -05006367 PKG, 0, PKG, original.getId(), false, "friend");
Julia Reynolds0f767342019-12-18 09:11:55 -05006368
6369 assertEquals(original.getName(), friendChannel.getName());
6370 assertEquals(original.getId(), friendChannel.getParentChannelId());
6371 assertEquals("friend", friendChannel.getConversationId());
6372 assertEquals(null, original.getConversationId());
6373 assertEquals(original.canShowBadge(), friendChannel.canShowBadge());
Mady Mellora92268c2020-03-09 17:25:08 -07006374 assertFalse(friendChannel.canBubble()); // can't be modified by app
Julia Reynolds0f767342019-12-18 09:11:55 -05006375 assertFalse(original.getId().equals(friendChannel.getId()));
6376 assertNotNull(friendChannel.getId());
6377 }
6378
6379 @Test
6380 public void deleteConversationNotificationChannels() throws Exception {
6381 NotificationChannel messagesParent =
6382 new NotificationChannel("messages", "messages", IMPORTANCE_HIGH);
6383 Parcel msgParcel = Parcel.obtain();
6384 messagesParent.writeToParcel(msgParcel, 0);
6385 msgParcel.setDataPosition(0);
6386
6387 NotificationChannel callsParent =
6388 new NotificationChannel("calls", "calls", IMPORTANCE_HIGH);
6389 Parcel callParcel = Parcel.obtain();
6390 callsParent.writeToParcel(callParcel, 0);
6391 callParcel.setDataPosition(0);
6392
6393 mBinderService.createNotificationChannels(PKG, new ParceledListSlice(Arrays.asList(
6394 messagesParent, callsParent)));
6395
6396 String conversationId = "friend";
6397
6398 mBinderService.createConversationNotificationChannelForPackage(
Julia Reynolds7c267522020-01-16 11:26:41 -05006399 PKG, mUid, "key", NotificationChannel.CREATOR.createFromParcel(msgParcel),
6400 conversationId);
Julia Reynolds0f767342019-12-18 09:11:55 -05006401 mBinderService.createConversationNotificationChannelForPackage(
Julia Reynolds7c267522020-01-16 11:26:41 -05006402 PKG, mUid, "key", NotificationChannel.CREATOR.createFromParcel(callParcel),
Julia Reynolds0f767342019-12-18 09:11:55 -05006403 conversationId);
6404
6405 NotificationChannel messagesChild = mBinderService.getConversationNotificationChannel(
Julia Reynolds12ba4cf2020-01-10 16:01:38 -05006406 PKG, 0, PKG, messagesParent.getId(), false, conversationId);
Julia Reynolds0f767342019-12-18 09:11:55 -05006407 NotificationChannel callsChild = mBinderService.getConversationNotificationChannel(
Julia Reynolds12ba4cf2020-01-10 16:01:38 -05006408 PKG, 0, PKG, callsParent.getId(), false, conversationId);
Julia Reynolds0f767342019-12-18 09:11:55 -05006409
6410 assertEquals(messagesParent.getId(), messagesChild.getParentChannelId());
6411 assertEquals(conversationId, messagesChild.getConversationId());
6412
6413 assertEquals(callsParent.getId(), callsChild.getParentChannelId());
6414 assertEquals(conversationId, callsChild.getConversationId());
6415
6416 mBinderService.deleteConversationNotificationChannels(PKG, mUid, conversationId);
6417
6418 assertNull(mBinderService.getConversationNotificationChannel(
Julia Reynolds12ba4cf2020-01-10 16:01:38 -05006419 PKG, 0, PKG, messagesParent.getId(), false, conversationId));
Julia Reynolds0f767342019-12-18 09:11:55 -05006420 assertNull(mBinderService.getConversationNotificationChannel(
Julia Reynolds12ba4cf2020-01-10 16:01:38 -05006421 PKG, 0, PKG, callsParent.getId(), false, conversationId));
Julia Reynolds0f767342019-12-18 09:11:55 -05006422 }
Julia Reynolds24edc002020-01-29 16:35:32 -05006423
6424 @Test
6425 public void testCorrectCategory_systemOn_appCannotTurnOff() {
6426 int requested = 0;
6427 int system = PRIORITY_CATEGORY_CALLS | PRIORITY_CATEGORY_CONVERSATIONS;
6428
6429 int actual = mService.correctCategory(requested, PRIORITY_CATEGORY_CONVERSATIONS,
6430 system);
6431
6432 assertEquals(PRIORITY_CATEGORY_CONVERSATIONS, actual);
6433 }
6434
6435 @Test
6436 public void testCorrectCategory_systemOff_appTurnOff_noChanges() {
6437 int requested = PRIORITY_CATEGORY_CALLS;
6438 int system = PRIORITY_CATEGORY_CALLS;
6439
6440 int actual = mService.correctCategory(requested, PRIORITY_CATEGORY_CONVERSATIONS,
6441 system);
6442
6443 assertEquals(PRIORITY_CATEGORY_CALLS, actual);
6444 }
6445
6446 @Test
6447 public void testCorrectCategory_systemOn_appTurnOn_noChanges() {
6448 int requested = PRIORITY_CATEGORY_CALLS | PRIORITY_CATEGORY_CONVERSATIONS;
6449 int system = PRIORITY_CATEGORY_CALLS | PRIORITY_CATEGORY_CONVERSATIONS;
6450
6451 int actual = mService.correctCategory(requested, PRIORITY_CATEGORY_CONVERSATIONS,
6452 system);
6453
6454 assertEquals(PRIORITY_CATEGORY_CALLS | PRIORITY_CATEGORY_CONVERSATIONS, actual);
6455 }
6456
6457 @Test
6458 public void testCorrectCategory_systemOff_appCannotTurnOn() {
6459 int requested = PRIORITY_CATEGORY_CALLS | PRIORITY_CATEGORY_CONVERSATIONS;
6460 int system = PRIORITY_CATEGORY_CALLS;
6461
6462 int actual = mService.correctCategory(requested, PRIORITY_CATEGORY_CONVERSATIONS,
6463 system);
6464
6465 assertEquals(PRIORITY_CATEGORY_CALLS, actual);
6466 }
Julia Reynolds882f2062020-02-05 12:11:38 -05006467
6468 @Test
6469 public void testGetConversationsForPackage_hasShortcut() throws Exception {
6470 mService.setPreferencesHelper(mPreferencesHelper);
6471 ArrayList<ConversationChannelWrapper> convos = new ArrayList<>();
6472 ConversationChannelWrapper convo1 = new ConversationChannelWrapper();
6473 NotificationChannel channel1 = new NotificationChannel("a", "a", 1);
6474 channel1.setConversationId("parent1", "convo 1");
6475 convo1.setNotificationChannel(channel1);
6476 convos.add(convo1);
6477
6478 ConversationChannelWrapper convo2 = new ConversationChannelWrapper();
6479 NotificationChannel channel2 = new NotificationChannel("b", "b", 1);
6480 channel2.setConversationId("parent1", "convo 2");
6481 convo2.setNotificationChannel(channel2);
6482 convos.add(convo2);
6483 when(mPreferencesHelper.getConversations(anyString(), anyInt())).thenReturn(convos);
6484
Julia Reynolds882f2062020-02-05 12:11:38 -05006485 ShortcutInfo si = mock(ShortcutInfo.class);
6486 when(si.getShortLabel()).thenReturn("Hello");
Mady Mellor774d5fe2020-03-05 11:35:03 -08006487 when(si.isLongLived()).thenReturn(true);
Julia Reynoldsfa273072020-04-14 15:31:21 -04006488 when(si.isEnabled()).thenReturn(true);
Julia Reynolds882f2062020-02-05 12:11:38 -05006489 when(mLauncherApps.getShortcuts(any(), any())).thenReturn(Arrays.asList(si));
Julia Reynoldsfa273072020-04-14 15:31:21 -04006490 when(mShortcutServiceInternal.isSharingShortcut(anyInt(), anyString(), anyString(),
6491 anyString(), anyInt(), any())).thenReturn(true);
Julia Reynolds882f2062020-02-05 12:11:38 -05006492
6493 List<ConversationChannelWrapper> conversations =
6494 mBinderService.getConversationsForPackage(PKG_P, mUid).getList();
6495 assertEquals(si, conversations.get(0).getShortcutInfo());
6496 assertEquals(si, conversations.get(1).getShortcutInfo());
Mady Mellor774d5fe2020-03-05 11:35:03 -08006497 }
Julia Reynolds882f2062020-02-05 12:11:38 -05006498
Mady Mellor774d5fe2020-03-05 11:35:03 -08006499 @Test
6500 public void testGetConversationsForPackage_shortcut_notLongLived() throws Exception {
6501 mService.setPreferencesHelper(mPreferencesHelper);
6502 ArrayList<ConversationChannelWrapper> convos = new ArrayList<>();
6503 ConversationChannelWrapper convo1 = new ConversationChannelWrapper();
6504 NotificationChannel channel1 = new NotificationChannel("a", "a", 1);
6505 channel1.setConversationId("parent1", "convo 1");
6506 convo1.setNotificationChannel(channel1);
6507 convos.add(convo1);
6508
6509 ConversationChannelWrapper convo2 = new ConversationChannelWrapper();
6510 NotificationChannel channel2 = new NotificationChannel("b", "b", 1);
6511 channel2.setConversationId("parent1", "convo 2");
6512 convo2.setNotificationChannel(channel2);
6513 convos.add(convo2);
6514 when(mPreferencesHelper.getConversations(anyString(), anyInt())).thenReturn(convos);
6515
6516 ShortcutInfo si = mock(ShortcutInfo.class);
6517 when(si.getShortLabel()).thenReturn("Hello");
6518 when(si.isLongLived()).thenReturn(false);
6519 when(mLauncherApps.getShortcuts(any(), any())).thenReturn(Arrays.asList(si));
6520
6521 List<ConversationChannelWrapper> conversations =
6522 mBinderService.getConversationsForPackage(PKG_P, mUid).getList();
6523 assertNull(conversations.get(0).getShortcutInfo());
6524 assertNull(conversations.get(1).getShortcutInfo());
Julia Reynolds882f2062020-02-05 12:11:38 -05006525 }
6526
6527 @Test
6528 public void testGetConversationsForPackage_doesNotHaveShortcut() throws Exception {
6529 mService.setPreferencesHelper(mPreferencesHelper);
6530 ArrayList<ConversationChannelWrapper> convos = new ArrayList<>();
6531 ConversationChannelWrapper convo1 = new ConversationChannelWrapper();
6532 NotificationChannel channel1 = new NotificationChannel("a", "a", 1);
6533 channel1.setConversationId("parent1", "convo 1");
6534 convo1.setNotificationChannel(channel1);
6535 convos.add(convo1);
6536
6537 ConversationChannelWrapper convo2 = new ConversationChannelWrapper();
6538 NotificationChannel channel2 = new NotificationChannel("b", "b", 1);
6539 channel2.setConversationId("parent1", "convo 2");
6540 convo2.setNotificationChannel(channel2);
6541 convos.add(convo2);
6542 when(mPreferencesHelper.getConversations(anyString(), anyInt())).thenReturn(convos);
6543
6544 List<ConversationChannelWrapper> conversations =
6545 mBinderService.getConversationsForPackage(PKG_P, mUid).getList();
6546 assertNull(conversations.get(0).getShortcutInfo());
6547 assertNull(conversations.get(1).getShortcutInfo());
6548 }
Mady Mellor57b34162020-04-01 08:44:00 -07006549
6550 @Test
6551 public void testShortcutHelperNull_doesntCrashEnqueue() throws RemoteException {
6552 mService.setShortcutHelper(null);
6553 NotificationRecord nr =
6554 generateMessageBubbleNotifRecord(mTestNotificationChannel,
6555 "testShortcutHelperNull_doesntCrashEnqueue");
6556 try {
6557 mBinderService.enqueueNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
6558 nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
6559 waitForIdle();
6560 } catch (Exception e) {
6561 fail(e.getMessage());
6562 }
6563 }
Geoffrey Pitsche75a66e2016-11-22 11:12:11 -05006564}