blob: ce1edcd584f69fc8ee327b375c20165d1c7b2168 [file] [log] [blame]
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001/*
2 * Copyright (C) 2011 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
Sudheer Shanka8ab22992018-11-29 00:08:58 -080017package com.android.server.net;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070018
Erik Klinef851d6d2015-04-20 16:03:48 +090019import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070020import static android.net.ConnectivityManager.TYPE_WIFI;
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +090021import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Jeff Sharkey2e471452018-01-19 18:02:47 +090022import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -070023import static android.net.NetworkPolicy.LIMIT_DISABLED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070024import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -070025import static android.net.NetworkPolicy.WARNING_DISABLED;
Felipe Leme46b451f2016-08-19 08:46:17 -070026import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070027import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070028import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Mike Yuf9729752018-08-17 15:22:05 +080029import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
30import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
31import static android.net.NetworkPolicyManager.RULE_NONE;
32import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
33import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
34import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Felipe Lemee88729d2016-08-17 16:43:01 -070035import static android.net.NetworkPolicyManager.uidPoliciesToString;
Mike Yuf9729752018-08-17 15:22:05 +080036import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkeye0c29952018-02-20 17:24:55 -070037import static android.net.NetworkStats.IFACE_ALL;
38import static android.net.NetworkStats.SET_ALL;
39import static android.net.NetworkStats.TAG_ALL;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070040import static android.net.NetworkTemplate.buildTemplateMobileAll;
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +090041import static android.net.NetworkTemplate.buildTemplateWifi;
Jeff Sharkey241dde22012-02-03 14:50:07 -080042import static android.net.TrafficStats.MB_IN_BYTES;
Mike Yuf9729752018-08-17 15:22:05 +080043import static android.os.Process.SYSTEM_UID;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070044import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070045import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
Jeff Sharkey53313d72017-07-13 16:47:32 -060046import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070047import static android.telephony.CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG;
48import static android.telephony.CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG;
49import static android.telephony.CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT;
Jeff Sharkey36b414b2018-03-30 11:00:03 -060050import static android.telephony.SubscriptionPlan.BYTES_UNLIMITED;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -070051import static android.telephony.SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED;
Felipe Lemeef134662016-08-10 14:46:39 -070052
Jeff Sharkey36b414b2018-03-30 11:00:03 -060053import static com.android.server.net.NetworkPolicyManagerInternal.QUOTA_TYPE_JOBS;
54import static com.android.server.net.NetworkPolicyManagerInternal.QUOTA_TYPE_MULTIPATH;
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +090055import static com.android.server.net.NetworkPolicyManagerService.OPPORTUNISTIC_QUOTA_UNKNOWN;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070056import static com.android.server.net.NetworkPolicyManagerService.TYPE_LIMIT;
57import static com.android.server.net.NetworkPolicyManagerService.TYPE_LIMIT_SNOOZED;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -070058import static com.android.server.net.NetworkPolicyManagerService.TYPE_RAPID;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070059import static com.android.server.net.NetworkPolicyManagerService.TYPE_WARNING;
Jeff Sharkey53313d72017-07-13 16:47:32 -060060
Felipe Leme9f27e7a2016-08-12 15:19:40 -070061import static org.junit.Assert.assertEquals;
62import static org.junit.Assert.assertFalse;
63import static org.junit.Assert.assertNotNull;
64import static org.junit.Assert.assertNull;
65import static org.junit.Assert.assertTrue;
66import static org.junit.Assert.fail;
Jeff Sharkey53313d72017-07-13 16:47:32 -060067import static org.mockito.ArgumentMatchers.any;
Sudheer Shanka543339f2017-07-28 15:18:07 -070068import static org.mockito.ArgumentMatchers.anyBoolean;
Jeff Sharkey53313d72017-07-13 16:47:32 -060069import static org.mockito.ArgumentMatchers.anyInt;
70import static org.mockito.ArgumentMatchers.anyLong;
71import static org.mockito.ArgumentMatchers.anyString;
72import static org.mockito.ArgumentMatchers.eq;
73import static org.mockito.ArgumentMatchers.isA;
jackqdyulei29c82ab2017-03-10 14:09:16 -080074import static org.mockito.Mockito.atLeast;
Felipe Lemeef134662016-08-10 14:46:39 -070075import static org.mockito.Mockito.atLeastOnce;
76import static org.mockito.Mockito.doAnswer;
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +090077import static org.mockito.Mockito.doNothing;
Felipe Lemeef134662016-08-10 14:46:39 -070078import static org.mockito.Mockito.mock;
Felipe Leme3d3308d2016-08-23 17:41:47 -070079import static org.mockito.Mockito.never;
Jeff Sharkey2e471452018-01-19 18:02:47 +090080import static org.mockito.Mockito.reset;
Felipe Lemeef134662016-08-10 14:46:39 -070081import static org.mockito.Mockito.verify;
82import static org.mockito.Mockito.when;
83
Felipe Leme3d3308d2016-08-23 17:41:47 -070084import android.Manifest;
Felipe Lemeef134662016-08-10 14:46:39 -070085import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -080086import android.app.ActivityManagerInternal;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070087import android.app.IActivityManager;
Felipe Lemeef134662016-08-10 14:46:39 -070088import android.app.IUidObserver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070089import android.app.Notification;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -070090import android.app.NotificationManager;
Felipe Lemeef134662016-08-10 14:46:39 -070091import android.app.usage.UsageStatsManagerInternal;
92import android.content.Context;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070093import android.content.Intent;
Felipe Lemeef134662016-08-10 14:46:39 -070094import android.content.pm.ApplicationInfo;
Felipe Leme3d3308d2016-08-23 17:41:47 -070095import android.content.pm.IPackageManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070096import android.content.pm.PackageInfo;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070097import android.content.pm.PackageManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070098import android.content.pm.Signature;
Felipe Leme3d3308d2016-08-23 17:41:47 -070099import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700100import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700101import android.net.INetworkManagementEventObserver;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700102import android.net.INetworkPolicyListener;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700103import android.net.LinkProperties;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900104import android.net.Network;
Stephen Chena1c92b72017-02-06 13:18:11 -0800105import android.net.NetworkCapabilities;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700106import android.net.NetworkInfo;
107import android.net.NetworkInfo.DetailedState;
108import android.net.NetworkPolicy;
Sudheer Shanka6a3c07e2018-09-11 15:21:22 -0700109import android.net.NetworkPolicyManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700110import android.net.NetworkState;
111import android.net.NetworkStats;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900112import android.net.NetworkStatsHistory;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700113import android.net.NetworkTemplate;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900114import android.net.StringNetworkSpecifier;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700115import android.os.Binder;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700116import android.os.INetworkManagementService;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700117import android.os.PersistableBundle;
Felipe Lemeef134662016-08-10 14:46:39 -0700118import android.os.PowerManagerInternal;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800119import android.os.PowerSaveState;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700120import android.os.RemoteException;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700121import android.os.SimpleClock;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700122import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700123import android.os.UserHandle;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700124import android.telephony.CarrierConfigManager;
125import android.telephony.SubscriptionManager;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900126import android.telephony.SubscriptionPlan;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700127import android.telephony.TelephonyManager;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700128import android.test.suitebuilder.annotation.MediumTest;
Felipe Lemee88729d2016-08-17 16:43:01 -0700129import android.text.TextUtils;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900130import android.util.DataUnit;
Felipe Lemeef134662016-08-10 14:46:39 -0700131import android.util.Log;
Mike Yuf9729752018-08-17 15:22:05 +0800132import android.util.Pair;
Jeff Sharkey0fc6d032018-03-30 16:25:11 -0600133import android.util.Range;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600134import android.util.RecurrenceRule;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700135
Brett Chabota26eda92018-07-23 13:08:30 -0700136import androidx.test.InstrumentationRegistry;
137import androidx.test.runner.AndroidJUnit4;
138
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700139import com.android.internal.telephony.PhoneConstants;
Lorenzo Colitti281a17c2016-10-28 12:56:03 +0900140import com.android.internal.util.test.BroadcastInterceptingContext;
141import com.android.internal.util.test.BroadcastInterceptingContext.FutureIntent;
Sudheer Shanka8ab22992018-11-29 00:08:58 -0800142import com.android.server.DeviceIdleController;
143import com.android.server.LocalServices;
Felipe Lemeef134662016-08-10 14:46:39 -0700144
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700145import com.google.common.util.concurrent.AbstractFuture;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700146
Kweku Adamsa9e55bc2018-11-19 14:59:15 -0800147import libcore.io.IoUtils;
148import libcore.io.Streams;
149
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700150import org.junit.After;
151import org.junit.Before;
Felipe Lemee88729d2016-08-17 16:43:01 -0700152import org.junit.Rule;
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700153import org.junit.Test;
Felipe Lemee88729d2016-08-17 16:43:01 -0700154import org.junit.rules.MethodRule;
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700155import org.junit.runner.RunWith;
Felipe Lemee88729d2016-08-17 16:43:01 -0700156import org.junit.runners.model.FrameworkMethod;
157import org.junit.runners.model.Statement;
Felipe Lemeef134662016-08-10 14:46:39 -0700158import org.mockito.ArgumentCaptor;
159import org.mockito.Mock;
160import org.mockito.MockitoAnnotations;
161import org.mockito.invocation.InvocationOnMock;
162import org.mockito.stubbing.Answer;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700163
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700164import java.io.File;
Felipe Lemee88729d2016-08-17 16:43:01 -0700165import java.io.FileOutputStream;
166import java.io.InputStream;
167import java.io.OutputStream;
168import java.lang.annotation.Annotation;
169import java.lang.annotation.ElementType;
170import java.lang.annotation.Retention;
171import java.lang.annotation.RetentionPolicy;
172import java.lang.annotation.Target;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600173import java.time.Clock;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600174import java.time.Instant;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600175import java.time.Period;
176import java.time.ZoneId;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700177import java.time.ZoneOffset;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600178import java.time.ZonedDateTime;
Mike Yuf9729752018-08-17 15:22:05 +0800179import java.util.ArrayList;
Felipe Lemee88729d2016-08-17 16:43:01 -0700180import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700181import java.util.Calendar;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600182import java.util.Iterator;
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700183import java.util.LinkedHashSet;
Felipe Lemeef134662016-08-10 14:46:39 -0700184import java.util.List;
Neil Fullerd5f0a392019-06-17 19:59:51 +0100185import java.util.TimeZone;
Felipe Lemeef134662016-08-10 14:46:39 -0700186import java.util.concurrent.CountDownLatch;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700187import java.util.concurrent.ExecutionException;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700188import java.util.concurrent.Future;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700189import java.util.concurrent.TimeUnit;
190import java.util.concurrent.TimeoutException;
Felipe Lemee88729d2016-08-17 16:43:01 -0700191import java.util.stream.Collectors;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700192
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700193/**
194 * Tests for {@link NetworkPolicyManagerService}.
195 */
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700196@RunWith(AndroidJUnit4.class)
Felipe Leme3d3308d2016-08-23 17:41:47 -0700197@MediumTest
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700198public class NetworkPolicyManagerServiceTest {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700199 private static final String TAG = "NetworkPolicyManagerServiceTest";
200
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700201 private static final long TEST_START = 1194220800000L;
202 private static final String TEST_IFACE = "test0";
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700203 private static final String TEST_SSID = "AndroidAP";
Jeff Sharkey2e471452018-01-19 18:02:47 +0900204 private static final String TEST_IMSI = "310210";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700205 private static final int TEST_SUB_ID = 42;
206 private static final int TEST_NET_ID = 24;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700207
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +0900208 private static NetworkTemplate sTemplateWifi = buildTemplateWifi(TEST_SSID);
209 private static NetworkTemplate sTemplateMobileAll = buildTemplateMobileAll(TEST_IMSI);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700210
Felipe Lemee88729d2016-08-17 16:43:01 -0700211 /**
212 * Path on assets where files used by {@link NetPolicyXml} are located.
213 */
214 private static final String NETPOLICY_DIR = "NetworkPolicyManagerServiceTest/netpolicy";
Neil Fullerd5f0a392019-06-17 19:59:51 +0100215 private static final String TIMEZONE_UTC = "UTC";
Felipe Lemee88729d2016-08-17 16:43:01 -0700216
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700217 private BroadcastInterceptingContext mServiceContext;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700218 private File mPolicyDir;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700219
Felipe Lemee88729d2016-08-17 16:43:01 -0700220 /**
221 * Relative path of the XML file that will be used as {@code netpolicy.xml}.
222 *
223 * <p>Typically set through a {@link NetPolicyXml} annotation in the test method.
224 */
225 private String mNetpolicyXml;
226
Felipe Lemeef134662016-08-10 14:46:39 -0700227 private @Mock IActivityManager mActivityManager;
Felipe Lemeef134662016-08-10 14:46:39 -0700228 private @Mock INetworkManagementService mNetworkManager;
Felipe Lemeef134662016-08-10 14:46:39 -0700229 private @Mock IConnectivityManager mConnManager;
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +0900230 private @Mock ConnectivityManager mConnectivityManager;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700231 private @Mock NotificationManager mNotifManager;
Felipe Lemeef134662016-08-10 14:46:39 -0700232 private @Mock PackageManager mPackageManager;
Felipe Leme3d3308d2016-08-23 17:41:47 -0700233 private @Mock IPackageManager mIpm;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700234 private @Mock SubscriptionManager mSubscriptionManager;
235 private @Mock CarrierConfigManager mCarrierConfigManager;
236 private @Mock TelephonyManager mTelephonyManager;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700237
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +0900238 private ArgumentCaptor<ConnectivityManager.NetworkCallback> mNetworkCallbackCaptor =
239 ArgumentCaptor.forClass(ConnectivityManager.NetworkCallback.class);
240
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700241 private ActivityManagerInternal mActivityManagerInternal;
242 private NetworkStatsManagerInternal mStatsService;
Sudheer Shankae7361852017-03-07 11:51:46 -0800243
Felipe Lemeef134662016-08-10 14:46:39 -0700244 private IUidObserver mUidObserver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700245 private INetworkManagementEventObserver mNetworkObserver;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700246
Felipe Lemeef134662016-08-10 14:46:39 -0700247 private NetworkPolicyListenerAnswer mPolicyListener;
248 private NetworkPolicyManagerService mService;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700249
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700250 /**
251 * In some of the tests while initializing NetworkPolicyManagerService,
252 * ACTION_RESTRICT_BACKGROUND_CHANGED is broadcasted. This is for capturing that broadcast.
253 */
254 private FutureIntent mFutureIntent;
255
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700256 private long mStartTime;
257 private long mElapsedRealtime;
258
Jeff Sharkeycae04a22012-03-22 15:18:52 -0700259 private static final int USER_ID = 0;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700260 private static final int FAKE_SUB_ID = 3737373;
261 private static final String FAKE_SUBSCRIBER_ID = "FAKE_SUB_ID";
262 private static final int DEFAULT_CYCLE_DAY = 1;
263 private static final int INVALID_CARRIER_CONFIG_VALUE = -9999;
264 private long mDefaultWarningBytes; // filled in with the actual default before tests are run
265 private long mDefaultLimitBytes; // filled in with the actual default before tests are run
Ammar Aijazib0941aa2019-04-26 18:39:50 -0700266 private PersistableBundle mCarrierConfig = CarrierConfigManager.getDefaultConfig();
Jeff Sharkeycae04a22012-03-22 15:18:52 -0700267
Felipe Lemee88729d2016-08-17 16:43:01 -0700268 private static final int APP_ID_A = android.os.Process.FIRST_APPLICATION_UID + 4;
269 private static final int APP_ID_B = android.os.Process.FIRST_APPLICATION_UID + 8;
270 private static final int APP_ID_C = android.os.Process.FIRST_APPLICATION_UID + 15;
271 private static final int APP_ID_D = android.os.Process.FIRST_APPLICATION_UID + 16;
272 private static final int APP_ID_E = android.os.Process.FIRST_APPLICATION_UID + 23;
273 private static final int APP_ID_F = android.os.Process.FIRST_APPLICATION_UID + 42;
Jeff Sharkeycae04a22012-03-22 15:18:52 -0700274
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700275 private static final int UID_A = UserHandle.getUid(USER_ID, APP_ID_A);
276 private static final int UID_B = UserHandle.getUid(USER_ID, APP_ID_B);
Felipe Lemee88729d2016-08-17 16:43:01 -0700277 private static final int UID_C = UserHandle.getUid(USER_ID, APP_ID_C);
278 private static final int UID_D = UserHandle.getUid(USER_ID, APP_ID_D);
279 private static final int UID_E = UserHandle.getUid(USER_ID, APP_ID_E);
280 private static final int UID_F = UserHandle.getUid(USER_ID, APP_ID_F);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700281
Felipe Lemeef134662016-08-10 14:46:39 -0700282 private static final String PKG_NAME_A = "name.is.A,pkg.A";
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700283 private static final String PKG_NAME_B = "name.is.B,pkg.B";
284 private static final String PKG_NAME_C = "name.is.C,pkg.C";
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700285
Felipe Lemee88729d2016-08-17 16:43:01 -0700286 public final @Rule NetPolicyMethodRule mNetPolicyXmlRule = new NetPolicyMethodRule();
287
Jeff Sharkey9911a282018-02-14 22:29:11 -0700288 private final Clock mClock = new SimpleClock(ZoneOffset.UTC) {
289 @Override
290 public long millis() {
291 return currentTimeMillis();
292 }
293 };
294
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700295 private void registerLocalServices() {
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700296 addLocalServiceMock(DeviceIdleController.LocalService.class);
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700297
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700298 final UsageStatsManagerInternal usageStats =
299 addLocalServiceMock(UsageStatsManagerInternal.class);
300 when(usageStats.getIdleUidsForUser(anyInt())).thenReturn(new int[]{});
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700301
Sudheer Shankae7361852017-03-07 11:51:46 -0800302 mActivityManagerInternal = addLocalServiceMock(ActivityManagerInternal.class);
jackqdyulei29c82ab2017-03-10 14:09:16 -0800303
304 final PowerSaveState state = new PowerSaveState.Builder()
305 .setBatterySaverEnabled(false).build();
306 final PowerManagerInternal pmInternal = addLocalServiceMock(PowerManagerInternal.class);
307 when(pmInternal.getLowPowerState(anyInt())).thenReturn(state);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700308
309 mStatsService = addLocalServiceMock(NetworkStatsManagerInternal.class);
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700310 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700311
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700312 @Before
313 public void callSystemReady() throws Exception {
Felipe Lemeef134662016-08-10 14:46:39 -0700314 MockitoAnnotations.initMocks(this);
315
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700316 final Context context = InstrumentationRegistry.getContext();
Felipe Lemeef134662016-08-10 14:46:39 -0700317
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700318 setCurrentTimeMillis(TEST_START);
319
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700320 registerLocalServices();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700321 // Intercept various broadcasts, and pretend that uids have packages.
322 // Also return mock service instances for a few critical services.
Felipe Lemeef134662016-08-10 14:46:39 -0700323 mServiceContext = new BroadcastInterceptingContext(context) {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700324 @Override
325 public PackageManager getPackageManager() {
Felipe Lemeef134662016-08-10 14:46:39 -0700326 return mPackageManager;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700327 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700328
329 @Override
330 public void startActivity(Intent intent) {
331 // ignored
332 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700333
334 @Override
335 public Object getSystemService(String name) {
336 switch (name) {
337 case Context.TELEPHONY_SUBSCRIPTION_SERVICE:
338 return mSubscriptionManager;
339 case Context.CARRIER_CONFIG_SERVICE:
340 return mCarrierConfigManager;
341 case Context.TELEPHONY_SERVICE:
342 return mTelephonyManager;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700343 case Context.NOTIFICATION_SERVICE:
344 return mNotifManager;
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +0900345 case Context.CONNECTIVITY_SERVICE:
346 return mConnectivityManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700347 default:
348 return super.getSystemService(name);
349 }
350 }
Jeff Sharkey2e471452018-01-19 18:02:47 +0900351
352 @Override
353 public void enforceCallingOrSelfPermission(String permission, String message) {
354 // Assume that we're AID_SYSTEM
355 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700356 };
357
Felipe Lemee88729d2016-08-17 16:43:01 -0700358 setNetpolicyXml(context);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700359
Felipe Lemeef134662016-08-10 14:46:39 -0700360 doAnswer(new Answer<Void>() {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700361
Felipe Lemeef134662016-08-10 14:46:39 -0700362 @Override
363 public Void answer(InvocationOnMock invocation) throws Throwable {
364 mUidObserver = (IUidObserver) invocation.getArguments()[0];
365 Log.d(TAG, "set mUidObserver to " + mUidObserver);
366 return null;
367 }
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800368 }).when(mActivityManager).registerUidObserver(any(), anyInt(),
Sudheer Shanka8ab22992018-11-29 00:08:58 -0800369 eq(NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE), any(String.class));
Felipe Lemeef134662016-08-10 14:46:39 -0700370
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700371 mFutureIntent = newRestrictBackgroundChangedFuture();
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700372 mService = new NetworkPolicyManagerService(mServiceContext, mActivityManager,
Jeff Sharkey9911a282018-02-14 22:29:11 -0700373 mNetworkManager, mIpm, mClock, mPolicyDir, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700374 mService.bindConnectivityManager(mConnManager);
Felipe Lemeef134662016-08-10 14:46:39 -0700375 mPolicyListener = new NetworkPolicyListenerAnswer(mService);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700376
Felipe Lemeef134662016-08-10 14:46:39 -0700377 // Sets some common expectations.
378 when(mPackageManager.getPackageInfo(anyString(), anyInt())).thenAnswer(
379 new Answer<PackageInfo>() {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700380
Felipe Lemeef134662016-08-10 14:46:39 -0700381 @Override
382 public PackageInfo answer(InvocationOnMock invocation) throws Throwable {
383 final String packageName = (String) invocation.getArguments()[0];
384 final PackageInfo info = new PackageInfo();
385 final Signature signature;
386 if ("android".equals(packageName)) {
387 signature = new Signature("F00D");
388 } else {
389 signature = new Signature("DEAD");
390 }
391 info.signatures = new Signature[] {
392 signature
393 };
394 return info;
395 }
396 });
397 when(mPackageManager.getApplicationInfoAsUser(anyString(), anyInt(), anyInt()))
398 .thenReturn(new ApplicationInfo());
399 when(mPackageManager.getPackagesForUid(UID_A)).thenReturn(new String[] {PKG_NAME_A});
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700400 when(mPackageManager.getPackagesForUid(UID_B)).thenReturn(new String[] {PKG_NAME_B});
401 when(mPackageManager.getPackagesForUid(UID_C)).thenReturn(new String[] {PKG_NAME_C});
402 when(mPackageManager.getApplicationInfo(eq(PKG_NAME_A), anyInt()))
403 .thenReturn(buildApplicationInfo(PKG_NAME_A));
404 when(mPackageManager.getApplicationInfo(eq(PKG_NAME_B), anyInt()))
405 .thenReturn(buildApplicationInfo(PKG_NAME_B));
406 when(mPackageManager.getApplicationInfo(eq(PKG_NAME_C), anyInt()))
407 .thenReturn(buildApplicationInfo(PKG_NAME_C));
Felipe Lemeef134662016-08-10 14:46:39 -0700408 when(mNetworkManager.isBandwidthControlEnabled()).thenReturn(true);
Sudheer Shanka543339f2017-07-28 15:18:07 -0700409 when(mNetworkManager.setDataSaverModeEnabled(anyBoolean())).thenReturn(true);
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +0900410 doNothing().when(mConnectivityManager)
411 .registerNetworkCallback(any(), mNetworkCallbackCaptor.capture());
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700412
Ammar Aijazib0941aa2019-04-26 18:39:50 -0700413 // Create the expected carrier config
414 mCarrierConfig.putBoolean(CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL, true);
415
Felipe Lemeef134662016-08-10 14:46:39 -0700416 // Prepare NPMS.
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800417 mService.systemReady(mService.networkScoreAndNetworkManagementServiceReady());
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700418
Felipe Lemeef134662016-08-10 14:46:39 -0700419 // catch INetworkManagementEventObserver during systemReady()
Felipe Leme3d3308d2016-08-23 17:41:47 -0700420 final ArgumentCaptor<INetworkManagementEventObserver> networkObserver =
Sudheer Shanka8ab22992018-11-29 00:08:58 -0800421 ArgumentCaptor.forClass(INetworkManagementEventObserver.class);
Felipe Lemeef134662016-08-10 14:46:39 -0700422 verify(mNetworkManager).registerObserver(networkObserver.capture());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700423 mNetworkObserver = networkObserver.getValue();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700424
425 NetworkPolicy defaultPolicy = mService.buildDefaultMobilePolicy(0, "");
426 mDefaultWarningBytes = defaultPolicy.warningBytes;
427 mDefaultLimitBytes = defaultPolicy.limitBytes;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700428 }
429
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700430 @After
431 public void removeFiles() throws Exception {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700432 for (File file : mPolicyDir.listFiles()) {
433 file.delete();
434 }
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700435 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700436
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700437 @After
438 public void unregisterLocalServices() throws Exception {
439 // Registered by NetworkPolicyManagerService's constructor.
Felipe Lemeef134662016-08-10 14:46:39 -0700440 LocalServices.removeServiceForTest(NetworkPolicyManagerInternal.class);
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700441
442 // Added in registerLocalServices()
443 LocalServices.removeServiceForTest(ActivityManagerInternal.class);
444 LocalServices.removeServiceForTest(PowerManagerInternal.class);
445 LocalServices.removeServiceForTest(DeviceIdleController.LocalService.class);
446 LocalServices.removeServiceForTest(UsageStatsManagerInternal.class);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700447 LocalServices.removeServiceForTest(NetworkStatsManagerInternal.class);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700448 }
449
Jeff Sharkey53313d72017-07-13 16:47:32 -0600450 @After
451 public void resetClock() throws Exception {
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600452 RecurrenceRule.sClock = Clock.systemDefaultZone();
Jeff Sharkey53313d72017-07-13 16:47:32 -0600453 }
454
Felipe Lemee88729d2016-08-17 16:43:01 -0700455 @Test
Felipe Leme3d3308d2016-08-23 17:41:47 -0700456 public void testTurnRestrictBackgroundOn() throws Exception {
457 assertRestrictBackgroundOff(); // Sanity check.
458 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
459 setRestrictBackground(true);
460 assertRestrictBackgroundChangedReceived(futureIntent, null);
461 }
462
463 @Test
464 @NetPolicyXml("restrict-background-on.xml")
465 public void testTurnRestrictBackgroundOff() throws Exception {
466 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700467 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700468 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
469 setRestrictBackground(false);
470 assertRestrictBackgroundChangedReceived(futureIntent, null);
471 }
472
473 /**
474 * Adds whitelist when restrict background is on - app should receive an intent.
475 */
476 @Test
477 @NetPolicyXml("restrict-background-on.xml")
478 public void testAddRestrictBackgroundWhitelist_restrictBackgroundOn() throws Exception {
479 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700480 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700481 addRestrictBackgroundWhitelist(true);
482 }
483
484 /**
485 * Adds whitelist when restrict background is off - app should not receive an intent.
486 */
487 @Test
488 public void testAddRestrictBackgroundWhitelist_restrictBackgroundOff() throws Exception {
489 assertRestrictBackgroundOff(); // Sanity check.
490 addRestrictBackgroundWhitelist(false);
491 }
492
493 private void addRestrictBackgroundWhitelist(boolean expectIntent) throws Exception {
Felipe Leme57e3d312016-08-23 14:42:52 -0700494 // Sanity checks.
495 assertWhitelistUids();
496 assertUidPolicy(UID_A, POLICY_NONE);
497
Felipe Leme3d3308d2016-08-23 17:41:47 -0700498 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700499 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700500
Felipe Leme57e3d312016-08-23 14:42:52 -0700501 mService.setUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700502
503 assertWhitelistUids(UID_A);
Felipe Leme57e3d312016-08-23 14:42:52 -0700504 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700505 mPolicyListener.waitAndVerify()
506 .onUidPoliciesChanged(APP_ID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700507 if (expectIntent) {
508 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
509 } else {
510 futureIntent.assertNotReceived();
511 }
512 }
513
514 /**
515 * Removes whitelist when restrict background is on - app should receive an intent.
516 */
517 @Test
518 @NetPolicyXml("uidA-whitelisted-restrict-background-on.xml")
519 public void testRemoveRestrictBackgroundWhitelist_restrictBackgroundOn() throws Exception {
520 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700521 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700522 removeRestrictBackgroundWhitelist(true);
523 }
524
525 /**
526 * Removes whitelist when restrict background is off - app should not receive an intent.
527 */
528 @Test
529 @NetPolicyXml("uidA-whitelisted-restrict-background-off.xml")
530 public void testRemoveRestrictBackgroundWhitelist_restrictBackgroundOff() throws Exception {
531 assertRestrictBackgroundOff(); // Sanity check.
532 removeRestrictBackgroundWhitelist(false);
533 }
534
jackqdyulei29c82ab2017-03-10 14:09:16 -0800535 @Test
536 public void testLowPowerModeObserver_ListenersRegistered()
537 throws Exception {
538 PowerManagerInternal pmInternal = LocalServices.getService(PowerManagerInternal.class);
539
540 verify(pmInternal, atLeast(2)).registerLowPowerModeObserver(any());
541 }
542
543 @Test
544 public void updateRestrictBackgroundByLowPowerMode_RestrictOnBeforeBsm_RestrictOnAfterBsm()
545 throws Exception {
546 setRestrictBackground(true);
547 PowerSaveState stateOn = new PowerSaveState.Builder()
548 .setGlobalBatterySaverEnabled(true)
549 .setBatterySaverEnabled(false)
550 .build();
551 mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
552
553 // RestrictBackground should be on even though battery saver want to turn it off
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700554 assertTrue(mService.getRestrictBackground());
jackqdyulei29c82ab2017-03-10 14:09:16 -0800555
556 PowerSaveState stateOff = new PowerSaveState.Builder()
557 .setGlobalBatterySaverEnabled(false)
558 .setBatterySaverEnabled(false)
559 .build();
560 mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
561
562 // RestrictBackground should be on, following its previous state
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700563 assertTrue(mService.getRestrictBackground());
jackqdyulei29c82ab2017-03-10 14:09:16 -0800564 }
565
566 @Test
567 public void updateRestrictBackgroundByLowPowerMode_RestrictOffBeforeBsm_RestrictOffAfterBsm()
568 throws Exception {
569 setRestrictBackground(false);
570 PowerSaveState stateOn = new PowerSaveState.Builder()
571 .setGlobalBatterySaverEnabled(true)
572 .setBatterySaverEnabled(true)
573 .build();
574
jackqdyulei29c82ab2017-03-10 14:09:16 -0800575 mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
576
577 // RestrictBackground should be turned on because of battery saver
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700578 assertTrue(mService.getRestrictBackground());
jackqdyulei29c82ab2017-03-10 14:09:16 -0800579
580 PowerSaveState stateOff = new PowerSaveState.Builder()
581 .setGlobalBatterySaverEnabled(false)
582 .setBatterySaverEnabled(false)
583 .build();
584 mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
585
586 // RestrictBackground should be off, following its previous state
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700587 assertFalse(mService.getRestrictBackground());
jackqdyulei29c82ab2017-03-10 14:09:16 -0800588 }
589
590 @Test
591 public void updateRestrictBackgroundByLowPowerMode_StatusChangedInBsm_DoNotRestore()
592 throws Exception {
593 setRestrictBackground(true);
594 PowerSaveState stateOn = new PowerSaveState.Builder()
595 .setGlobalBatterySaverEnabled(true)
596 .setBatterySaverEnabled(true)
597 .build();
598 mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
599
600 // RestrictBackground should still be on
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700601 assertTrue(mService.getRestrictBackground());
jackqdyulei29c82ab2017-03-10 14:09:16 -0800602
603 // User turns off RestrictBackground manually
604 setRestrictBackground(false);
605 PowerSaveState stateOff = new PowerSaveState.Builder().setBatterySaverEnabled(
606 false).build();
607 mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
608
609 // RestrictBackground should be off because user changes it manually
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700610 assertFalse(mService.getRestrictBackground());
jackqdyulei29c82ab2017-03-10 14:09:16 -0800611 }
612
Felipe Leme3d3308d2016-08-23 17:41:47 -0700613 private void removeRestrictBackgroundWhitelist(boolean expectIntent) throws Exception {
Felipe Leme57e3d312016-08-23 14:42:52 -0700614 // Sanity checks.
615 assertWhitelistUids(UID_A);
616 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
617
Felipe Leme3d3308d2016-08-23 17:41:47 -0700618 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700619 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700620
Felipe Leme57e3d312016-08-23 14:42:52 -0700621 mService.setUidPolicy(UID_A, POLICY_NONE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700622
623 assertWhitelistUids();
Felipe Leme57e3d312016-08-23 14:42:52 -0700624 assertUidPolicy(UID_A, POLICY_NONE);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700625 mPolicyListener.waitAndVerify().onUidPoliciesChanged(APP_ID_A, POLICY_NONE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700626 if (expectIntent) {
627 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
628 } else {
629 futureIntent.assertNotReceived();
630 }
631 }
632
633 /**
Felipe Leme57e3d312016-08-23 14:42:52 -0700634 * Adds blacklist when restrict background is on - app should not receive an intent.
Felipe Leme3d3308d2016-08-23 17:41:47 -0700635 */
636 @Test
637 @NetPolicyXml("restrict-background-on.xml")
638 public void testAddRestrictBackgroundBlacklist_restrictBackgroundOn() throws Exception {
639 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700640 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme57e3d312016-08-23 14:42:52 -0700641 addRestrictBackgroundBlacklist(false);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700642 }
643
644 /**
645 * Adds blacklist when restrict background is off - app should receive an intent.
646 */
647 @Test
648 public void testAddRestrictBackgroundBlacklist_restrictBackgroundOff() throws Exception {
649 assertRestrictBackgroundOff(); // Sanity check.
650 addRestrictBackgroundBlacklist(true);
651 }
652
653 private void addRestrictBackgroundBlacklist(boolean expectIntent) throws Exception {
654 assertUidPolicy(UID_A, POLICY_NONE); // Sanity check.
655 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700656 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700657
658 mService.setUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
659
660 assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700661 mPolicyListener.waitAndVerify()
662 .onUidPoliciesChanged(APP_ID_A, POLICY_REJECT_METERED_BACKGROUND);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700663 if (expectIntent) {
664 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
665 } else {
666 futureIntent.assertNotReceived();
667 }
668 }
669
670 /**
Felipe Leme57e3d312016-08-23 14:42:52 -0700671 * Removes blacklist when restrict background is on - app should not receive an intent.
Felipe Leme3d3308d2016-08-23 17:41:47 -0700672 */
673 @Test
674 @NetPolicyXml("uidA-blacklisted-restrict-background-on.xml")
675 public void testRemoveRestrictBackgroundBlacklist_restrictBackgroundOn() throws Exception {
676 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700677 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme57e3d312016-08-23 14:42:52 -0700678 removeRestrictBackgroundBlacklist(false);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700679 }
680
681 /**
682 * Removes blacklist when restrict background is off - app should receive an intent.
683 */
684 @Test
685 @NetPolicyXml("uidA-blacklisted-restrict-background-off.xml")
686 public void testRemoveRestrictBackgroundBlacklist_restrictBackgroundOff() throws Exception {
687 assertRestrictBackgroundOff(); // Sanity check.
688 removeRestrictBackgroundBlacklist(true);
689 }
690
691 private void removeRestrictBackgroundBlacklist(boolean expectIntent) throws Exception {
692 assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND); // Sanity check.
693 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700694 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700695
696 mService.setUidPolicy(UID_A, POLICY_NONE);
697
698 assertUidPolicy(UID_A, POLICY_NONE);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700699 mPolicyListener.waitAndVerify()
700 .onUidPoliciesChanged(APP_ID_A, POLICY_NONE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700701 if (expectIntent) {
702 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
703 } else {
704 futureIntent.assertNotReceived();
705 }
706 }
707
Felipe Leme51a63642016-08-30 12:15:09 -0700708 @Test
Felipe Lemec08ecdf2016-08-30 12:57:35 -0700709 @NetPolicyXml("uidA-blacklisted-restrict-background-on.xml")
Felipe Leme3d3308d2016-08-23 17:41:47 -0700710 public void testBlacklistedAppIsNotNotifiedWhenRestrictBackgroundIsOn() throws Exception {
711 // Sanity checks.
712 assertRestrictBackgroundOn();
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700713 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700714 assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
715
716 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
717 setRestrictBackground(true);
718 futureIntent.assertNotReceived();
719 }
720
Felipe Leme51a63642016-08-30 12:15:09 -0700721 @Test
Felipe Lemec08ecdf2016-08-30 12:57:35 -0700722 @NetPolicyXml("uidA-whitelisted-restrict-background-on.xml")
Felipe Leme3d3308d2016-08-23 17:41:47 -0700723 public void testWhitelistedAppIsNotNotifiedWhenRestrictBackgroundIsOn() throws Exception {
724 // Sanity checks.
Felipe Lemec08ecdf2016-08-30 12:57:35 -0700725 assertRestrictBackgroundOn();
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700726 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700727 assertWhitelistUids(UID_A);
728
729 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
730 setRestrictBackground(true);
731 futureIntent.assertNotReceived();
732 }
733
Andreas Gampe84d156b2016-09-03 10:50:38 -0700734 @Test
Felipe Leme57e3d312016-08-23 14:42:52 -0700735 @NetPolicyXml("uidA-whitelisted-restrict-background-on.xml")
736 public void testWhitelistedAppIsNotifiedWhenBlacklisted() throws Exception {
737 // Sanity checks.
738 assertRestrictBackgroundOn();
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700739 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme57e3d312016-08-23 14:42:52 -0700740 assertWhitelistUids(UID_A);
741
742 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
743 mService.setUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
744 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
745 }
746
Felipe Leme3d3308d2016-08-23 17:41:47 -0700747 @Test
Felipe Lemee88729d2016-08-17 16:43:01 -0700748 @NetPolicyXml("restrict-background-lists-whitelist-format.xml")
749 public void testRestrictBackgroundLists_whitelistFormat() throws Exception {
Felipe Leme46b451f2016-08-19 08:46:17 -0700750 restrictBackgroundListsTest();
751 }
752
753 @Test
754 @NetPolicyXml("restrict-background-lists-uid-policy-format.xml")
755 public void testRestrictBackgroundLists_uidPolicyFormat() throws Exception {
756 restrictBackgroundListsTest();
757 }
758
759 private void restrictBackgroundListsTest() throws Exception {
Felipe Leme8546a442016-08-23 09:38:20 -0700760 // UIds that are whitelisted.
Felipe Leme46b451f2016-08-19 08:46:17 -0700761 assertWhitelistUids(UID_A, UID_B, UID_C);
762 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
763 assertUidPolicy(UID_B, POLICY_ALLOW_METERED_BACKGROUND);
764 assertUidPolicy(UID_C, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Lemee88729d2016-08-17 16:43:01 -0700765
Felipe Leme8546a442016-08-23 09:38:20 -0700766 // UIDs that are blacklisted.
Felipe Lemee88729d2016-08-17 16:43:01 -0700767 assertUidPolicy(UID_D, POLICY_NONE);
768 assertUidPolicy(UID_E, POLICY_REJECT_METERED_BACKGROUND);
Felipe Leme8546a442016-08-23 09:38:20 -0700769
770 // UIDS that have legacy policies.
Felipe Leme46b451f2016-08-19 08:46:17 -0700771 assertUidPolicy(UID_F, 2); // POLICY_ALLOW_BACKGROUND_BATTERY_SAVE
772
773 // Remove whitelist.
Felipe Leme57e3d312016-08-23 14:42:52 -0700774 mService.setUidPolicy(UID_A, POLICY_NONE);
Felipe Leme46b451f2016-08-19 08:46:17 -0700775 assertUidPolicy(UID_A, POLICY_NONE);
776 assertWhitelistUids(UID_B, UID_C);
777
778 // Add whitelist when blacklisted.
Felipe Leme57e3d312016-08-23 14:42:52 -0700779 mService.setUidPolicy(UID_E, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme46b451f2016-08-19 08:46:17 -0700780 assertUidPolicy(UID_E, POLICY_ALLOW_METERED_BACKGROUND);
781 assertWhitelistUids(UID_B, UID_C, UID_E);
782
783 // Add blacklist when whitelisted.
784 mService.setUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND);
785 assertUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND);
786 assertWhitelistUids(UID_C, UID_E);
787 }
788
789 /**
790 * Tests scenario where an UID had {@code restrict-background} and {@code uid-policy} tags.
791 */
792 @Test
793 @NetPolicyXml("restrict-background-lists-mixed-format.xml")
794 public void testRestrictBackgroundLists_mixedFormat() throws Exception {
795 assertWhitelistUids(UID_A, UID_C, UID_D);
796 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme57e3d312016-08-23 14:42:52 -0700797 assertUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND); // Blacklist prevails.
Felipe Leme46b451f2016-08-19 08:46:17 -0700798 assertUidPolicy(UID_C, (POLICY_ALLOW_METERED_BACKGROUND | 2));
799 assertUidPolicy(UID_D, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Lemee88729d2016-08-17 16:43:01 -0700800 }
801
Felipe Leme6f51a0a2016-08-24 15:11:51 -0700802 @Test
803 @NetPolicyXml("uids-with-mixed-policies.xml")
804 public void testGetUidsWithPolicy() throws Exception {
Felipe Leme03f90292016-09-08 18:10:32 -0700805 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_NONE));
Felipe Leme6f51a0a2016-08-24 15:11:51 -0700806 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND),
807 UID_B, UID_D);
808 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_ALLOW_METERED_BACKGROUND),
809 UID_E, UID_F);
810 // Legacy (POLICY_ALLOW_BACKGROUND_BATTERY_SAVE)
811 assertContainsInAnyOrder(mService.getUidsWithPolicy(2),
812 UID_C, UID_D, UID_F);
813 }
814
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700815 // NOTE: testPolicyChangeTriggersListener() is too superficial, they
Felipe Lemeef134662016-08-10 14:46:39 -0700816 // don't check for side-effects (like calls to NetworkManagementService) neither cover all
817 // different modes (Data Saver, Battery Saver, Doze, App idle, etc...).
818 // These scenarios are extensively tested on CTS' HostsideRestrictBackgroundNetworkTests.
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700819 @Test
Felipe Lemeef134662016-08-10 14:46:39 -0700820 public void testUidForeground() throws Exception {
821 // push all uids into background
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700822 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE, 0);
823 callOnUidStateChanged(UID_B, ActivityManager.PROCESS_STATE_SERVICE, 0);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700824 assertFalse(mService.isUidForeground(UID_A));
825 assertFalse(mService.isUidForeground(UID_B));
826
Felipe Lemeef134662016-08-10 14:46:39 -0700827 // push one of the uids into foreground
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700828 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_TOP, 0);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700829 assertTrue(mService.isUidForeground(UID_A));
830 assertFalse(mService.isUidForeground(UID_B));
831
832 // and swap another uid into foreground
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700833 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE, 0);
834 callOnUidStateChanged(UID_B, ActivityManager.PROCESS_STATE_TOP, 0);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700835 assertFalse(mService.isUidForeground(UID_A));
836 assertTrue(mService.isUidForeground(UID_B));
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700837 }
838
Kweku Adamsa9e55bc2018-11-19 14:59:15 -0800839 @Test
840 public void testAppIdleTempWhitelisting() throws Exception {
841 mService.setAppIdleWhitelist(UID_A, true);
842 mService.setAppIdleWhitelist(UID_B, false);
843 int[] whitelistedIds = mService.getAppIdleWhitelist();
844 assertTrue(Arrays.binarySearch(whitelistedIds, UID_A) >= 0);
845 assertTrue(Arrays.binarySearch(whitelistedIds, UID_B) < 0);
846 assertFalse(mService.isUidIdle(UID_A));
847 // Can't currently guarantee UID_B's app idle state.
848 // TODO: expand with multiple app idle states.
849 }
850
Jeff Sharkey53313d72017-07-13 16:47:32 -0600851 private static long computeLastCycleBoundary(long currentTime, NetworkPolicy policy) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600852 RecurrenceRule.sClock = Clock.fixed(Instant.ofEpochMilli(currentTime),
853 ZoneId.systemDefault());
Jeff Sharkey0fc6d032018-03-30 16:25:11 -0600854 final Iterator<Range<ZonedDateTime>> it = policy.cycleIterator();
Jeff Sharkey53313d72017-07-13 16:47:32 -0600855 while (it.hasNext()) {
Jeff Sharkey0fc6d032018-03-30 16:25:11 -0600856 final Range<ZonedDateTime> cycle = it.next();
857 if (cycle.getLower().toInstant().toEpochMilli() < currentTime) {
858 return cycle.getLower().toInstant().toEpochMilli();
Jeff Sharkey53313d72017-07-13 16:47:32 -0600859 }
860 }
861 throw new IllegalStateException(
862 "Failed to find current cycle for " + policy + " at " + currentTime);
863 }
864
865 private static long computeNextCycleBoundary(long currentTime, NetworkPolicy policy) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600866 RecurrenceRule.sClock = Clock.fixed(Instant.ofEpochMilli(currentTime),
867 ZoneId.systemDefault());
Jeff Sharkey0fc6d032018-03-30 16:25:11 -0600868 return policy.cycleIterator().next().getUpper().toInstant().toEpochMilli();
Jeff Sharkey53313d72017-07-13 16:47:32 -0600869 }
870
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700871 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700872 public void testLastCycleBoundaryThisMonth() throws Exception {
873 // assume cycle day of "5th", which should be in same month
874 final long currentTime = parseTime("2007-11-14T00:00:00.000Z");
875 final long expectedCycle = parseTime("2007-11-05T00:00:00.000Z");
876
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700877 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800878 sTemplateWifi, 5, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700879 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700880 assertTimeEquals(expectedCycle, actualCycle);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700881 }
882
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700883 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700884 public void testLastCycleBoundaryLastMonth() throws Exception {
885 // assume cycle day of "20th", which should be in last month
886 final long currentTime = parseTime("2007-11-14T00:00:00.000Z");
887 final long expectedCycle = parseTime("2007-10-20T00:00:00.000Z");
888
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700889 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800890 sTemplateWifi, 20, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700891 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700892 assertTimeEquals(expectedCycle, actualCycle);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700893 }
894
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700895 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700896 public void testLastCycleBoundaryThisMonthFebruary() throws Exception {
897 // assume cycle day of "30th" in february; should go to january
898 final long currentTime = parseTime("2007-02-14T00:00:00.000Z");
899 final long expectedCycle = parseTime("2007-01-30T00:00:00.000Z");
900
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700901 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800902 sTemplateWifi, 30, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700903 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700904 assertTimeEquals(expectedCycle, actualCycle);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700905 }
906
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700907 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700908 public void testLastCycleBoundaryLastMonthFebruary() throws Exception {
909 // assume cycle day of "30th" in february, which should clamp
910 final long currentTime = parseTime("2007-03-14T00:00:00.000Z");
Jeff Sharkey53313d72017-07-13 16:47:32 -0600911 final long expectedCycle = parseTime("2007-02-28T23:59:59.999Z");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700912
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700913 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800914 sTemplateWifi, 30, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700915 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700916 assertTimeEquals(expectedCycle, actualCycle);
917 }
918
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700919 @Test
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800920 public void testCycleBoundaryLeapYear() throws Exception {
921 final NetworkPolicy policy = new NetworkPolicy(
922 sTemplateWifi, 29, TIMEZONE_UTC, 1024L, 1024L, false);
923
924 assertTimeEquals(parseTime("2012-01-29T00:00:00.000Z"),
925 computeNextCycleBoundary(parseTime("2012-01-14T00:00:00.000Z"), policy));
926 assertTimeEquals(parseTime("2012-02-29T00:00:00.000Z"),
927 computeNextCycleBoundary(parseTime("2012-02-14T00:00:00.000Z"), policy));
928 assertTimeEquals(parseTime("2012-02-29T00:00:00.000Z"),
929 computeLastCycleBoundary(parseTime("2012-03-14T00:00:00.000Z"), policy));
930 assertTimeEquals(parseTime("2012-03-29T00:00:00.000Z"),
931 computeNextCycleBoundary(parseTime("2012-03-14T00:00:00.000Z"), policy));
932
933 assertTimeEquals(parseTime("2007-01-29T00:00:00.000Z"),
934 computeNextCycleBoundary(parseTime("2007-01-14T00:00:00.000Z"), policy));
Jeff Sharkey53313d72017-07-13 16:47:32 -0600935 assertTimeEquals(parseTime("2007-02-28T23:59:59.999Z"),
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800936 computeNextCycleBoundary(parseTime("2007-02-14T00:00:00.000Z"), policy));
Jeff Sharkey53313d72017-07-13 16:47:32 -0600937 assertTimeEquals(parseTime("2007-02-28T23:59:59.999Z"),
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800938 computeLastCycleBoundary(parseTime("2007-03-14T00:00:00.000Z"), policy));
939 assertTimeEquals(parseTime("2007-03-29T00:00:00.000Z"),
940 computeNextCycleBoundary(parseTime("2007-03-14T00:00:00.000Z"), policy));
941 }
942
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700943 @Test
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800944 public void testNextCycleTimezoneAfterUtc() throws Exception {
945 // US/Central is UTC-6
946 final NetworkPolicy policy = new NetworkPolicy(
947 sTemplateWifi, 10, "US/Central", 1024L, 1024L, false);
948 assertTimeEquals(parseTime("2012-01-10T06:00:00.000Z"),
949 computeNextCycleBoundary(parseTime("2012-01-05T00:00:00.000Z"), policy));
950 }
951
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700952 @Test
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800953 public void testNextCycleTimezoneBeforeUtc() throws Exception {
954 // Israel is UTC+2
955 final NetworkPolicy policy = new NetworkPolicy(
956 sTemplateWifi, 10, "Israel", 1024L, 1024L, false);
957 assertTimeEquals(parseTime("2012-01-09T22:00:00.000Z"),
958 computeNextCycleBoundary(parseTime("2012-01-05T00:00:00.000Z"), policy));
959 }
960
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700961 @Test
Jeff Sharkey15399052013-01-15 14:15:53 -0800962 public void testCycleTodayJanuary() throws Exception {
963 final NetworkPolicy policy = new NetworkPolicy(
964 sTemplateWifi, 14, "US/Pacific", 1024L, 1024L, false);
965
966 assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
967 computeNextCycleBoundary(parseTime("2013-01-13T23:59:59.000-08:00"), policy));
968 assertTimeEquals(parseTime("2013-02-14T00:00:00.000-08:00"),
969 computeNextCycleBoundary(parseTime("2013-01-14T00:00:01.000-08:00"), policy));
970 assertTimeEquals(parseTime("2013-02-14T00:00:00.000-08:00"),
971 computeNextCycleBoundary(parseTime("2013-01-14T15:11:00.000-08:00"), policy));
972
973 assertTimeEquals(parseTime("2012-12-14T00:00:00.000-08:00"),
974 computeLastCycleBoundary(parseTime("2013-01-13T23:59:59.000-08:00"), policy));
975 assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
976 computeLastCycleBoundary(parseTime("2013-01-14T00:00:01.000-08:00"), policy));
977 assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
978 computeLastCycleBoundary(parseTime("2013-01-14T15:11:00.000-08:00"), policy));
979 }
980
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700981 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700982 public void testNetworkPolicyAppliedCycleLastMonth() throws Exception {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700983 NetworkState[] state = null;
984 NetworkStats stats = null;
985
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700986 final int CYCLE_DAY = 15;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600987 final long NOW = parseTime("2007-03-10T00:00Z");
988 final long CYCLE_START = parseTime("2007-02-15T00:00Z");
989 final long CYCLE_END = parseTime("2007-03-15T00:00Z");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700990
Jeff Sharkey53313d72017-07-13 16:47:32 -0600991 setCurrentTimeMillis(NOW);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700992
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700993 // first, pretend that wifi network comes online. no policy active,
994 // which means we shouldn't push limit to interface.
995 state = new NetworkState[] { buildWifi() };
Felipe Lemeef134662016-08-10 14:46:39 -0700996 when(mConnManager.getAllNetworkState()).thenReturn(state);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700997
Felipe Lemeef134662016-08-10 14:46:39 -0700998 mPolicyListener.expect().onMeteredIfacesChanged(any());
Erik Klinef851d6d2015-04-20 16:03:48 +0900999 mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION));
Felipe Lemeef134662016-08-10 14:46:39 -07001000 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(any());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001001
1002 // now change cycle to be on 15th, and test in early march, to verify we
1003 // pick cycle day in previous month.
Felipe Lemeef134662016-08-10 14:46:39 -07001004 when(mConnManager.getAllNetworkState()).thenReturn(state);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001005
1006 // pretend that 512 bytes total have happened
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001007 stats = new NetworkStats(getElapsedRealtime(), 1)
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001008 .addIfaceValues(TEST_IFACE, 256L, 2L, 256L, 2L);
Jeff Sharkey53313d72017-07-13 16:47:32 -06001009 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, CYCLE_START, CYCLE_END))
Felipe Lemeef134662016-08-10 14:46:39 -07001010 .thenReturn(stats.getTotalBytes());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001011
Felipe Lemeef134662016-08-10 14:46:39 -07001012 mPolicyListener.expect().onMeteredIfacesChanged(any());
Jeff Sharkey163e6442011-10-31 16:37:52 -07001013 setNetworkPolicies(new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001014 sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, 1 * MB_IN_BYTES, 2 * MB_IN_BYTES, false));
Felipe Lemeef134662016-08-10 14:46:39 -07001015 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
1016
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001017 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
1018 (2 * MB_IN_BYTES) - 512);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001019 }
1020
Felipe Leme9f27e7a2016-08-12 15:19:40 -07001021 @Test
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001022 public void testNotificationWarningLimitSnooze() throws Exception {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001023 // Create a place to store fake usage
1024 final NetworkStatsHistory history = new NetworkStatsHistory(TimeUnit.HOURS.toMillis(1));
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001025 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001026 when(mStatsService.getNetworkTotalBytes(any(), anyLong(), anyLong()))
1027 .thenAnswer(new Answer<Long>() {
1028 @Override
1029 public Long answer(InvocationOnMock invocation) throws Throwable {
1030 final NetworkStatsHistory.Entry entry = history.getValues(
1031 invocation.getArgument(1), invocation.getArgument(2), null);
1032 return entry.rxBytes + entry.txBytes;
1033 }
1034 });
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001035 when(mStatsService.getNetworkUidBytes(any(), anyLong(), anyLong()))
1036 .thenAnswer(new Answer<NetworkStats>() {
1037 @Override
1038 public NetworkStats answer(InvocationOnMock invocation) throws Throwable {
1039 return stats;
1040 }
1041 });
Jeff Sharkey2e471452018-01-19 18:02:47 +09001042
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001043 // Get active mobile network in place
1044 expectMobileDefaults();
1045 mService.updateNetworks();
1046
1047 // Define simple data plan
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001048 final SubscriptionPlan plan = buildMonthlyDataPlan(
1049 ZonedDateTime.parse("2015-11-01T00:00:00.00Z"), DataUnit.MEGABYTES.toBytes(1800));
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001050 mService.setSubscriptionPlans(TEST_SUB_ID, new SubscriptionPlan[] { plan },
Jeff Sharkey2e471452018-01-19 18:02:47 +09001051 mServiceContext.getOpPackageName());
1052
Jeff Sharkey2e471452018-01-19 18:02:47 +09001053 // We're 20% through the month (6 days)
1054 final long start = parseTime("2015-11-01T00:00Z");
1055 final long end = parseTime("2015-11-07T00:00Z");
1056 setCurrentTimeMillis(end);
1057
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001058 // Normal usage means no notification
1059 {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001060 history.clear();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001061 history.recordData(start, end,
1062 new NetworkStats.Entry(DataUnit.MEGABYTES.toBytes(360), 0L, 0L, 0L, 0));
1063
1064 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1065 expectMobileDefaults();
1066
1067 mService.updateNetworks();
1068
1069 verify(mTelephonyManager, atLeastOnce()).setPolicyDataEnabled(true, TEST_SUB_ID);
1070 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
1071 DataUnit.MEGABYTES.toBytes(1800 - 360));
1072 verify(mNotifManager, never()).notifyAsUser(any(), anyInt(), any(), any());
1073 }
1074
1075 // Push over warning
1076 {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001077 history.clear();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001078 history.recordData(start, end,
1079 new NetworkStats.Entry(DataUnit.MEGABYTES.toBytes(1799), 0L, 0L, 0L, 0));
1080
1081 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1082 expectMobileDefaults();
1083
1084 mService.updateNetworks();
1085
1086 verify(mTelephonyManager, atLeastOnce()).setPolicyDataEnabled(true, TEST_SUB_ID);
1087 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
1088 DataUnit.MEGABYTES.toBytes(1800 - 1799));
1089 verify(mNotifManager, atLeastOnce()).notifyAsUser(any(), eq(TYPE_WARNING),
1090 isA(Notification.class), eq(UserHandle.ALL));
1091 }
1092
Ammar Aijazib0941aa2019-04-26 18:39:50 -07001093 // Push over warning, but with a config that isn't from an identified carrier
1094 {
1095 history.clear();
1096 history.recordData(start, end,
1097 new NetworkStats.Entry(DataUnit.MEGABYTES.toBytes(1799), 0L, 0L, 0L, 0));
1098
1099 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1100 expectMobileDefaults();
1101 expectDefaultCarrierConfig();
1102
1103 mService.updateNetworks();
1104
1105 verify(mTelephonyManager, atLeastOnce()).setPolicyDataEnabled(true, TEST_SUB_ID);
1106 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
1107 DataUnit.MEGABYTES.toBytes(1800 - 1799));
1108 // Since this isn't from the identified carrier, there should be no notifications
1109 verify(mNotifManager, never()).notifyAsUser(any(), anyInt(), any(), any());
1110 }
1111
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001112 // Push over limit
1113 {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001114 history.clear();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001115 history.recordData(start, end,
1116 new NetworkStats.Entry(DataUnit.MEGABYTES.toBytes(1810), 0L, 0L, 0L, 0));
1117
1118 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1119 expectMobileDefaults();
1120
1121 mService.updateNetworks();
1122
1123 verify(mTelephonyManager, atLeastOnce()).setPolicyDataEnabled(false, TEST_SUB_ID);
1124 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE, 1);
1125 verify(mNotifManager, atLeastOnce()).notifyAsUser(any(), eq(TYPE_LIMIT),
1126 isA(Notification.class), eq(UserHandle.ALL));
1127 }
1128
1129 // Snooze limit
1130 {
1131 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1132 expectMobileDefaults();
1133
1134 mService.snoozeLimit(NetworkTemplate.buildTemplateMobileAll(TEST_IMSI));
1135 mService.updateNetworks();
1136
1137 verify(mTelephonyManager, atLeastOnce()).setPolicyDataEnabled(true, TEST_SUB_ID);
1138 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
1139 Long.MAX_VALUE);
1140 verify(mNotifManager, atLeastOnce()).notifyAsUser(any(), eq(TYPE_LIMIT_SNOOZED),
1141 isA(Notification.class), eq(UserHandle.ALL));
1142 }
1143 }
1144
1145 @Test
1146 public void testNotificationRapid() throws Exception {
1147 // Create a place to store fake usage
1148 final NetworkStatsHistory history = new NetworkStatsHistory(TimeUnit.HOURS.toMillis(1));
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001149 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001150 when(mStatsService.getNetworkTotalBytes(any(), anyLong(), anyLong()))
1151 .thenAnswer(new Answer<Long>() {
1152 @Override
1153 public Long answer(InvocationOnMock invocation) throws Throwable {
1154 final NetworkStatsHistory.Entry entry = history.getValues(
1155 invocation.getArgument(1), invocation.getArgument(2), null);
1156 return entry.rxBytes + entry.txBytes;
1157 }
1158 });
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001159 when(mStatsService.getNetworkUidBytes(any(), anyLong(), anyLong()))
1160 .thenAnswer(new Answer<NetworkStats>() {
1161 @Override
1162 public NetworkStats answer(InvocationOnMock invocation) throws Throwable {
1163 return stats;
1164 }
1165 });
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001166
1167 // Get active mobile network in place
1168 expectMobileDefaults();
1169 mService.updateNetworks();
1170
1171 // Define simple data plan which gives us effectively 60MB/day
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001172 final SubscriptionPlan plan = buildMonthlyDataPlan(
1173 ZonedDateTime.parse("2015-11-01T00:00:00.00Z"), DataUnit.MEGABYTES.toBytes(1800));
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001174 mService.setSubscriptionPlans(TEST_SUB_ID, new SubscriptionPlan[] { plan },
1175 mServiceContext.getOpPackageName());
1176
1177 // We're 20% through the month (6 days)
1178 final long start = parseTime("2015-11-01T00:00Z");
1179 final long end = parseTime("2015-11-07T00:00Z");
1180 setCurrentTimeMillis(end);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001181
1182 // Using 20% data in 20% time is normal
Jeff Sharkey2e471452018-01-19 18:02:47 +09001183 {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001184 history.clear();
Jeff Sharkey2e471452018-01-19 18:02:47 +09001185 history.recordData(start, end,
1186 new NetworkStats.Entry(DataUnit.MEGABYTES.toBytes(360), 0L, 0L, 0L, 0));
1187
1188 reset(mNotifManager);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001189 mService.updateNetworks();
1190 verify(mNotifManager, never()).notifyAsUser(any(), anyInt(), any(), any());
Jeff Sharkey2e471452018-01-19 18:02:47 +09001191 }
1192
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001193 // Using 80% data in 20% time is alarming; but spread equally among
1194 // three UIDs means we get generic alert
Jeff Sharkey2e471452018-01-19 18:02:47 +09001195 {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001196 history.clear();
Jeff Sharkey2e471452018-01-19 18:02:47 +09001197 history.recordData(start, end,
1198 new NetworkStats.Entry(DataUnit.MEGABYTES.toBytes(1440), 0L, 0L, 0L, 0));
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001199 stats.clear();
1200 stats.addValues(IFACE_ALL, UID_A, SET_ALL, TAG_ALL,
1201 DataUnit.MEGABYTES.toBytes(480), 0, 0, 0, 0);
1202 stats.addValues(IFACE_ALL, UID_B, SET_ALL, TAG_ALL,
1203 DataUnit.MEGABYTES.toBytes(480), 0, 0, 0, 0);
1204 stats.addValues(IFACE_ALL, UID_C, SET_ALL, TAG_ALL,
1205 DataUnit.MEGABYTES.toBytes(480), 0, 0, 0, 0);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001206
1207 reset(mNotifManager);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001208 mService.updateNetworks();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001209
1210 final ArgumentCaptor<Notification> notif = ArgumentCaptor.forClass(Notification.class);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001211 verify(mNotifManager, atLeastOnce()).notifyAsUser(any(), eq(TYPE_RAPID),
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001212 notif.capture(), eq(UserHandle.ALL));
1213
1214 final String text = notif.getValue().extras.getCharSequence(Notification.EXTRA_TEXT)
1215 .toString();
1216 assertFalse(text.contains(PKG_NAME_A));
1217 assertFalse(text.contains(PKG_NAME_B));
1218 assertFalse(text.contains(PKG_NAME_C));
1219 }
1220
1221 // Using 80% data in 20% time is alarming; but mostly done by one UID
1222 // means we get specific alert
1223 {
1224 history.clear();
1225 history.recordData(start, end,
1226 new NetworkStats.Entry(DataUnit.MEGABYTES.toBytes(1440), 0L, 0L, 0L, 0));
1227 stats.clear();
1228 stats.addValues(IFACE_ALL, UID_A, SET_ALL, TAG_ALL,
1229 DataUnit.MEGABYTES.toBytes(960), 0, 0, 0, 0);
1230 stats.addValues(IFACE_ALL, UID_B, SET_ALL, TAG_ALL,
1231 DataUnit.MEGABYTES.toBytes(480), 0, 0, 0, 0);
1232
1233 reset(mNotifManager);
1234 mService.updateNetworks();
1235
1236 final ArgumentCaptor<Notification> notif = ArgumentCaptor.forClass(Notification.class);
1237 verify(mNotifManager, atLeastOnce()).notifyAsUser(any(), eq(TYPE_RAPID),
1238 notif.capture(), eq(UserHandle.ALL));
1239
1240 final String text = notif.getValue().extras.getCharSequence(Notification.EXTRA_TEXT)
1241 .toString();
1242 assertTrue(text.contains(PKG_NAME_A));
1243 assertFalse(text.contains(PKG_NAME_B));
1244 assertFalse(text.contains(PKG_NAME_C));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001245 }
1246 }
1247
1248 @Test
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001249 public void testMeteredNetworkWithoutLimit() throws Exception {
1250 NetworkState[] state = null;
1251 NetworkStats stats = null;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001252
1253 final long TIME_FEB_15 = 1171497600000L;
1254 final long TIME_MAR_10 = 1173484800000L;
1255 final int CYCLE_DAY = 15;
1256
1257 setCurrentTimeMillis(TIME_MAR_10);
1258
1259 // bring up wifi network with metered policy
1260 state = new NetworkState[] { buildWifi() };
1261 stats = new NetworkStats(getElapsedRealtime(), 1)
1262 .addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L);
1263
1264 {
Felipe Lemeef134662016-08-10 14:46:39 -07001265 when(mConnManager.getAllNetworkState()).thenReturn(state);
1266 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15,
1267 currentTimeMillis())).thenReturn(stats.getTotalBytes());
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001268
Felipe Lemeef134662016-08-10 14:46:39 -07001269 mPolicyListener.expect().onMeteredIfacesChanged(any());
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001270 setNetworkPolicies(new NetworkPolicy(
1271 sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, WARNING_DISABLED, LIMIT_DISABLED,
1272 true));
Felipe Lemeef134662016-08-10 14:46:39 -07001273 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
1274
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001275 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
1276 Long.MAX_VALUE);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001277 }
1278 }
1279
Sudheer Shankae7361852017-03-07 11:51:46 -08001280 @Test
1281 public void testOnUidStateChanged_notifyAMS() throws Exception {
1282 final long procStateSeq = 222;
Sudheer Shankaed25ce62017-03-29 20:46:30 -07001283 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE, procStateSeq);
Sudheer Shankae7361852017-03-07 11:51:46 -08001284 verify(mActivityManagerInternal).notifyNetworkPolicyRulesUpdated(UID_A, procStateSeq);
Sudheer Shankae7361852017-03-07 11:51:46 -08001285 }
1286
Sudheer Shankaed25ce62017-03-29 20:46:30 -07001287 private void callOnUidStateChanged(int uid, int procState, long procStateSeq)
1288 throws Exception {
1289 mUidObserver.onUidStateChanged(uid, procState, procStateSeq);
1290 final CountDownLatch latch = new CountDownLatch(1);
1291 mService.mUidEventHandler.post(() -> {
1292 latch.countDown();
1293 });
1294 latch.await(2, TimeUnit.SECONDS);
1295 }
1296
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001297 private void assertCycleDayAsExpected(PersistableBundle config, int carrierCycleDay,
1298 boolean expectValid) {
1299 config.putInt(KEY_MONTHLY_DATA_CYCLE_DAY_INT, carrierCycleDay);
1300 int actualCycleDay = mService.getCycleDayFromCarrierConfig(config,
1301 INVALID_CARRIER_CONFIG_VALUE);
1302 if (expectValid) {
1303 assertEquals(carrierCycleDay, actualCycleDay);
1304 } else {
1305 // INVALID_CARRIER_CONFIG_VALUE is returned for invalid values
1306 assertEquals(INVALID_CARRIER_CONFIG_VALUE, actualCycleDay);
1307 }
1308 }
1309
1310 @Test
1311 public void testGetCycleDayFromCarrierConfig() {
1312 PersistableBundle config = CarrierConfigManager.getDefaultConfig();
1313 final Calendar cal = Calendar.getInstance();
1314 int actualCycleDay;
1315
1316 config.putInt(KEY_MONTHLY_DATA_CYCLE_DAY_INT, DATA_CYCLE_USE_PLATFORM_DEFAULT);
1317 actualCycleDay = mService.getCycleDayFromCarrierConfig(config, DEFAULT_CYCLE_DAY);
1318 assertEquals(DEFAULT_CYCLE_DAY, actualCycleDay);
1319
1320 // null config returns a default value
1321 actualCycleDay = mService.getCycleDayFromCarrierConfig(null, DEFAULT_CYCLE_DAY);
1322 assertEquals(DEFAULT_CYCLE_DAY, actualCycleDay);
1323
1324 // Sane, non-default values
1325 assertCycleDayAsExpected(config, 1, true);
1326 assertCycleDayAsExpected(config, cal.getMaximum(Calendar.DAY_OF_MONTH), true);
1327 assertCycleDayAsExpected(config, cal.getMinimum(Calendar.DAY_OF_MONTH), true);
1328
1329 // Invalid values
1330 assertCycleDayAsExpected(config, 0, false);
1331 assertCycleDayAsExpected(config, DATA_CYCLE_THRESHOLD_DISABLED, false);
1332 assertCycleDayAsExpected(config, cal.getMaximum(Calendar.DAY_OF_MONTH) + 1, false);
1333 assertCycleDayAsExpected(config, cal.getMinimum(Calendar.DAY_OF_MONTH) - 5, false);
1334 }
1335
1336 private void assertWarningBytesAsExpected(PersistableBundle config, long carrierWarningBytes,
1337 long expected) {
1338 config.putLong(KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, carrierWarningBytes);
1339 long actualWarning = mService.getWarningBytesFromCarrierConfig(config,
1340 INVALID_CARRIER_CONFIG_VALUE);
1341 assertEquals(expected, actualWarning);
1342 }
1343
1344 @Test
1345 public void testGetWarningBytesFromCarrierConfig() {
1346 PersistableBundle config = CarrierConfigManager.getDefaultConfig();
1347 long actualWarningBytes;
1348
1349 assertWarningBytesAsExpected(config, DATA_CYCLE_USE_PLATFORM_DEFAULT,
1350 mDefaultWarningBytes);
1351 assertWarningBytesAsExpected(config, DATA_CYCLE_THRESHOLD_DISABLED, WARNING_DISABLED);
1352 assertWarningBytesAsExpected(config, 0, 0);
1353 // not a valid value
1354 assertWarningBytesAsExpected(config, -1000, INVALID_CARRIER_CONFIG_VALUE);
1355
1356 // null config returns a default value
1357 actualWarningBytes = mService.getWarningBytesFromCarrierConfig(null, mDefaultWarningBytes);
1358 assertEquals(mDefaultWarningBytes, actualWarningBytes);
1359 }
1360
1361 private void assertLimitBytesAsExpected(PersistableBundle config, long carrierWarningBytes,
1362 long expected) {
1363 config.putLong(KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG, carrierWarningBytes);
1364 long actualWarning = mService.getLimitBytesFromCarrierConfig(config,
1365 INVALID_CARRIER_CONFIG_VALUE);
1366 assertEquals(expected, actualWarning);
1367 }
1368
1369 @Test
1370 public void testGetLimitBytesFromCarrierConfig() {
1371 PersistableBundle config = CarrierConfigManager.getDefaultConfig();
1372 long actualLimitBytes;
1373
1374 assertLimitBytesAsExpected(config, DATA_CYCLE_USE_PLATFORM_DEFAULT,
1375 mDefaultLimitBytes);
1376 assertLimitBytesAsExpected(config, DATA_CYCLE_THRESHOLD_DISABLED, LIMIT_DISABLED);
1377 assertLimitBytesAsExpected(config, 0, 0);
1378 // not a valid value
1379 assertLimitBytesAsExpected(config, -1000, INVALID_CARRIER_CONFIG_VALUE);
1380
1381 // null config returns a default value
1382 actualLimitBytes = mService.getWarningBytesFromCarrierConfig(null, mDefaultLimitBytes);
1383 assertEquals(mDefaultLimitBytes, actualLimitBytes);
1384 }
1385
1386 private PersistableBundle setupUpdateMobilePolicyCycleTests() throws RemoteException {
1387 when(mConnManager.getAllNetworkState()).thenReturn(new NetworkState[0]);
1388 when(mSubscriptionManager.getActiveSubscriptionIdList()).thenReturn(new int[]{FAKE_SUB_ID});
1389 when(mTelephonyManager.getSubscriberId(FAKE_SUB_ID)).thenReturn(FAKE_SUBSCRIBER_ID);
1390 PersistableBundle bundle = CarrierConfigManager.getDefaultConfig();
1391 when(mCarrierConfigManager.getConfigForSubId(FAKE_SUB_ID)).thenReturn(bundle);
1392 setNetworkPolicies(buildDefaultFakeMobilePolicy());
1393 return bundle;
1394 }
1395
1396 @Test
1397 public void testUpdateMobilePolicyCycleWithNullConfig() throws RemoteException {
1398 when(mConnManager.getAllNetworkState()).thenReturn(new NetworkState[0]);
1399 when(mSubscriptionManager.getActiveSubscriptionIdList()).thenReturn(new int[]{FAKE_SUB_ID});
1400 when(mTelephonyManager.getSubscriberId(FAKE_SUB_ID)).thenReturn(FAKE_SUBSCRIBER_ID);
1401 when(mCarrierConfigManager.getConfigForSubId(FAKE_SUB_ID)).thenReturn(null);
1402 setNetworkPolicies(buildDefaultFakeMobilePolicy());
1403 // smoke test to make sure no errors are raised
1404 mServiceContext.sendBroadcast(
1405 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1406 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1407 );
1408 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1409 true);
1410 }
1411
1412 @Test
1413 public void testUpdateMobilePolicyCycleWithInvalidConfig() throws RemoteException {
1414 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1415 // Test with an invalid CarrierConfig, there should be no changes or crashes.
1416 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, -100);
1417 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, -100);
1418 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG, -100);
1419 mServiceContext.sendBroadcast(
1420 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1421 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1422 );
1423
1424 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1425 true);
1426 }
1427
1428 @Test
1429 public void testUpdateMobilePolicyCycleWithDefaultConfig() throws RemoteException {
1430 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1431 // Test that we respect the platform values when told to
1432 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT,
1433 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1434 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1435 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1436 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1437 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1438 mServiceContext.sendBroadcast(
1439 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1440 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1441 );
1442
1443 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1444 true);
1445 }
1446
1447 @Test
1448 public void testUpdateMobilePolicyCycleWithUserOverrides() throws RemoteException {
1449 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1450
1451 // inferred = false implies that a user manually modified this policy.
1452 NetworkPolicy policy = buildDefaultFakeMobilePolicy();
1453 policy.inferred = false;
1454 setNetworkPolicies(policy);
1455
1456 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1457 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, 9999);
1458 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1459 DATA_CYCLE_THRESHOLD_DISABLED);
1460 mServiceContext.sendBroadcast(
1461 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1462 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1463 );
1464
1465 // The policy still shouldn't change, because we don't want to overwrite user settings.
1466 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1467 false);
1468 }
1469
1470 @Test
1471 public void testUpdateMobilePolicyCycleUpdatesDataCycle() throws RemoteException {
1472 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1473
1474 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1475 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, 9999);
1476 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG, 9999);
1477 mServiceContext.sendBroadcast(
1478 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1479 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1480 );
1481
1482 assertNetworkPolicyEquals(31, 9999, 9999, true);
1483 }
1484
1485 @Test
1486 public void testUpdateMobilePolicyCycleDisableThresholds() throws RemoteException {
1487 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1488
1489 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1490 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1491 DATA_CYCLE_THRESHOLD_DISABLED);
1492 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1493 DATA_CYCLE_THRESHOLD_DISABLED);
1494 mServiceContext.sendBroadcast(
1495 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1496 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1497 );
1498
1499 assertNetworkPolicyEquals(31, WARNING_DISABLED, LIMIT_DISABLED, true);
1500 }
1501
1502 @Test
1503 public void testUpdateMobilePolicyCycleRevertsToDefault() throws RemoteException {
1504 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1505
1506 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1507 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1508 DATA_CYCLE_THRESHOLD_DISABLED);
1509 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1510 DATA_CYCLE_THRESHOLD_DISABLED);
1511 mServiceContext.sendBroadcast(
1512 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1513 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1514 );
1515 assertNetworkPolicyEquals(31, WARNING_DISABLED, LIMIT_DISABLED, true);
1516
1517 // If the user switches carriers to one that doesn't use a CarrierConfig, we should revert
1518 // to the default data limit and warning. The cycle date doesn't need to revert as it's
1519 // arbitrary anyways.
1520 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT,
1521 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1522 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1523 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1524 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1525 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1526 mServiceContext.sendBroadcast(
1527 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1528 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1529 );
1530
1531 assertNetworkPolicyEquals(31, mDefaultWarningBytes, mDefaultLimitBytes,
1532 true);
1533 }
1534
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001535 @Test
1536 public void testOpportunisticQuota() throws Exception {
1537 final Network net = new Network(TEST_NET_ID);
1538 final NetworkPolicyManagerInternal internal = LocalServices
1539 .getService(NetworkPolicyManagerInternal.class);
1540
1541 // Create a place to store fake usage
1542 final NetworkStatsHistory history = new NetworkStatsHistory(TimeUnit.HOURS.toMillis(1));
1543 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 0);
1544 when(mStatsService.getNetworkTotalBytes(any(), anyLong(), anyLong()))
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001545 .thenAnswer(invocation -> {
1546 final NetworkStatsHistory.Entry entry = history.getValues(
1547 invocation.getArgument(1), invocation.getArgument(2), null);
1548 return entry.rxBytes + entry.txBytes;
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001549 });
1550 when(mStatsService.getNetworkUidBytes(any(), anyLong(), anyLong()))
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001551 .thenReturn(stats);
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001552
1553 // Get active mobile network in place
1554 expectMobileDefaults();
1555 mService.updateNetworks();
1556
1557 // We're 20% through the month (6 days)
1558 final long start = parseTime("2015-11-01T00:00Z");
1559 final long end = parseTime("2015-11-07T00:00Z");
1560 setCurrentTimeMillis(end);
1561
1562 // Get some data usage in place
1563 history.clear();
1564 history.recordData(start, end,
1565 new NetworkStats.Entry(DataUnit.MEGABYTES.toBytes(360), 0L, 0L, 0L, 0));
1566
1567 // No data plan
1568 {
1569 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1570 expectMobileDefaults();
1571
1572 mService.updateNetworks();
1573
1574 // No quotas
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001575 assertEquals(OPPORTUNISTIC_QUOTA_UNKNOWN,
1576 internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_JOBS));
1577 assertEquals(OPPORTUNISTIC_QUOTA_UNKNOWN,
1578 internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_MULTIPATH));
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001579 }
1580
1581 // Limited data plan
1582 {
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001583 final SubscriptionPlan plan = buildMonthlyDataPlan(
1584 ZonedDateTime.parse("2015-11-01T00:00:00.00Z"),
1585 DataUnit.MEGABYTES.toBytes(1800));
1586 mService.setSubscriptionPlans(TEST_SUB_ID, new SubscriptionPlan[]{plan},
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001587 mServiceContext.getOpPackageName());
1588
1589 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1590 expectMobileDefaults();
1591
1592 mService.updateNetworks();
1593
1594 // We have 1440MB and 24 days left, which is 60MB/day; assuming 10%
1595 // for quota split equally between two types gives 3MB.
1596 assertEquals(DataUnit.MEGABYTES.toBytes(3),
1597 internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_JOBS));
1598 assertEquals(DataUnit.MEGABYTES.toBytes(3),
1599 internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_MULTIPATH));
1600 }
1601
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001602 // Limited data plan, over quota
1603 {
1604 final SubscriptionPlan plan = buildMonthlyDataPlan(
1605 ZonedDateTime.parse("2015-11-01T00:00:00.00Z"),
1606 DataUnit.MEGABYTES.toBytes(100));
1607 mService.setSubscriptionPlans(TEST_SUB_ID, new SubscriptionPlan[]{plan},
1608 mServiceContext.getOpPackageName());
1609
1610 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1611 expectMobileDefaults();
1612
1613 mService.updateNetworks();
1614
1615 assertEquals(0L, internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_JOBS));
1616 assertEquals(0L, internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_MULTIPATH));
1617 }
1618
1619 // Roaming
1620 {
1621 final SubscriptionPlan plan = buildMonthlyDataPlan(
1622 ZonedDateTime.parse("2015-11-01T00:00:00.00Z"), BYTES_UNLIMITED);
1623 mService.setSubscriptionPlans(TEST_SUB_ID, new SubscriptionPlan[]{plan},
1624 mServiceContext.getOpPackageName());
1625
1626 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1627 expectMobileDefaults();
1628 expectNetworkState(true /* roaming */);
1629
1630 mService.updateNetworks();
1631
1632 assertEquals(0L, internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_JOBS));
1633 assertEquals(0L, internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_MULTIPATH));
1634 }
1635
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001636 // Unlimited data plan
1637 {
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001638 final SubscriptionPlan plan = buildMonthlyDataPlan(
1639 ZonedDateTime.parse("2015-11-01T00:00:00.00Z"), BYTES_UNLIMITED);
1640 mService.setSubscriptionPlans(TEST_SUB_ID, new SubscriptionPlan[]{plan},
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001641 mServiceContext.getOpPackageName());
1642
1643 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1644 expectMobileDefaults();
1645
1646 mService.updateNetworks();
1647
1648 // 20MB/day, split equally between two types gives 10MB.
1649 assertEquals(DataUnit.MEBIBYTES.toBytes(10),
1650 internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_JOBS));
1651 assertEquals(DataUnit.MEBIBYTES.toBytes(10),
1652 internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_MULTIPATH));
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001653
1654 // Capabilities change to roaming
1655 final ConnectivityManager.NetworkCallback callback = mNetworkCallbackCaptor.getValue();
1656 assertNotNull(callback);
1657 expectNetworkState(true /* roaming */);
1658 callback.onCapabilitiesChanged(
1659 new Network(TEST_NET_ID),
1660 buildNetworkCapabilities(TEST_SUB_ID, true /* roaming */));
1661
1662 assertEquals(0, internal.getSubscriptionOpportunisticQuota(
1663 new Network(TEST_NET_ID), NetworkPolicyManagerInternal.QUOTA_TYPE_MULTIPATH));
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001664 }
1665 }
1666
Annie Meng20b4d842018-05-18 15:00:49 +01001667 /**
1668 * Test that policy set of {null, NetworkPolicy, null} does not crash and restores the valid
1669 * NetworkPolicy.
1670 */
1671 @Test
1672 public void testSetNetworkPolicies_withNullPolicies_doesNotThrow() {
1673 NetworkPolicy[] policies = new NetworkPolicy[3];
1674 policies[1] = buildDefaultFakeMobilePolicy();
1675 setNetworkPolicies(policies);
1676
1677 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1678 true);
1679 }
1680
Mike Yuf9729752018-08-17 15:22:05 +08001681 /**
1682 * Exhaustively test isUidNetworkingBlocked to output the expected results based on external
1683 * conditions.
1684 */
1685 @Test
1686 public void testIsUidNetworkingBlocked() {
1687 final ArrayList<Pair<Boolean, Integer>> expectedBlockedStates = new ArrayList<>();
1688
1689 // Metered network. Data saver on.
1690 expectedBlockedStates.add(new Pair<>(true, RULE_NONE));
1691 expectedBlockedStates.add(new Pair<>(false, RULE_ALLOW_METERED));
1692 expectedBlockedStates.add(new Pair<>(false, RULE_TEMPORARY_ALLOW_METERED));
1693 expectedBlockedStates.add(new Pair<>(true, RULE_REJECT_METERED));
1694 expectedBlockedStates.add(new Pair<>(true, RULE_ALLOW_ALL));
1695 expectedBlockedStates.add(new Pair<>(true, RULE_REJECT_ALL));
1696 verifyNetworkBlockedState(
1697 true /* metered */, true /* backgroundRestricted */, expectedBlockedStates);
1698 expectedBlockedStates.clear();
1699
1700 // Metered network. Data saver off.
1701 expectedBlockedStates.add(new Pair<>(false, RULE_NONE));
1702 expectedBlockedStates.add(new Pair<>(false, RULE_ALLOW_METERED));
1703 expectedBlockedStates.add(new Pair<>(false, RULE_TEMPORARY_ALLOW_METERED));
1704 expectedBlockedStates.add(new Pair<>(true, RULE_REJECT_METERED));
1705 expectedBlockedStates.add(new Pair<>(false, RULE_ALLOW_ALL));
1706 expectedBlockedStates.add(new Pair<>(true, RULE_REJECT_ALL));
1707 verifyNetworkBlockedState(
1708 true /* metered */, false /* backgroundRestricted */, expectedBlockedStates);
1709 expectedBlockedStates.clear();
1710
1711 // Non-metered network. Data saver on.
1712 expectedBlockedStates.add(new Pair<>(false, RULE_NONE));
1713 expectedBlockedStates.add(new Pair<>(false, RULE_ALLOW_METERED));
1714 expectedBlockedStates.add(new Pair<>(false, RULE_TEMPORARY_ALLOW_METERED));
1715 expectedBlockedStates.add(new Pair<>(false, RULE_REJECT_METERED));
1716 expectedBlockedStates.add(new Pair<>(false, RULE_ALLOW_ALL));
1717 expectedBlockedStates.add(new Pair<>(true, RULE_REJECT_ALL));
1718 verifyNetworkBlockedState(
1719 false /* metered */, true /* backgroundRestricted */, expectedBlockedStates);
1720
1721 // Non-metered network. Data saver off. The result is the same as previous case since
1722 // the network is blocked only for RULE_REJECT_ALL regardless of data saver.
1723 verifyNetworkBlockedState(
1724 false /* metered */, false /* backgroundRestricted */, expectedBlockedStates);
1725 expectedBlockedStates.clear();
1726 }
1727
1728 private void verifyNetworkBlockedState(boolean metered, boolean backgroundRestricted,
1729 ArrayList<Pair<Boolean, Integer>> expectedBlockedStateForRules) {
1730 final NetworkPolicyManagerInternal npmi = LocalServices
1731 .getService(NetworkPolicyManagerInternal.class);
1732
1733 for (Pair<Boolean, Integer> pair : expectedBlockedStateForRules) {
1734 final boolean expectedResult = pair.first;
1735 final int rule = pair.second;
1736 assertEquals(formatBlockedStateError(UID_A, rule, metered, backgroundRestricted),
1737 expectedResult,
1738 npmi.isUidNetworkingBlocked(UID_A, rule, metered, backgroundRestricted));
1739 assertFalse(formatBlockedStateError(SYSTEM_UID, rule, metered, backgroundRestricted),
1740 npmi.isUidNetworkingBlocked(SYSTEM_UID, rule, metered, backgroundRestricted));
1741 }
1742 }
1743
1744 private String formatBlockedStateError(int uid, int rule, boolean metered,
1745 boolean backgroundRestricted) {
1746 return String.format(
1747 "Unexpected BlockedState: (uid=%d, rule=%s, metered=%b, backgroundRestricted=%b)",
1748 uid, uidRulesToString(rule), metered, backgroundRestricted);
1749 }
1750
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001751 private SubscriptionPlan buildMonthlyDataPlan(ZonedDateTime start, long limitBytes) {
1752 return SubscriptionPlan.Builder
1753 .createRecurringMonthly(start)
1754 .setDataLimit(limitBytes, LIMIT_BEHAVIOR_DISABLED)
1755 .build();
1756 }
1757
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001758 private ApplicationInfo buildApplicationInfo(String label) {
1759 final ApplicationInfo ai = new ApplicationInfo();
1760 ai.nonLocalizedLabel = label;
1761 return ai;
1762 }
1763
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001764 private NetworkInfo buildNetworkInfo() {
1765 final NetworkInfo ni = new NetworkInfo(ConnectivityManager.TYPE_MOBILE,
1766 TelephonyManager.NETWORK_TYPE_LTE, null, null);
1767 ni.setDetailedState(NetworkInfo.DetailedState.CONNECTED, null, null);
1768 return ni;
1769 }
1770
1771 private LinkProperties buildLinkProperties(String iface) {
1772 final LinkProperties lp = new LinkProperties();
1773 lp.setInterfaceName(iface);
1774 return lp;
1775 }
1776
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001777 private NetworkCapabilities buildNetworkCapabilities(int subId, boolean roaming) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001778 final NetworkCapabilities nc = new NetworkCapabilities();
1779 nc.addTransportType(TRANSPORT_CELLULAR);
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001780 if (!roaming) {
1781 nc.addCapability(NET_CAPABILITY_NOT_ROAMING);
1782 }
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001783 nc.setNetworkSpecifier(new StringNetworkSpecifier(String.valueOf(subId)));
1784 return nc;
1785 }
1786
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001787 private NetworkPolicy buildDefaultFakeMobilePolicy() {
1788 NetworkPolicy p = mService.buildDefaultMobilePolicy(FAKE_SUB_ID, FAKE_SUBSCRIBER_ID);
1789 // set a deterministic cycle date
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001790 p.cycleRule = new RecurrenceRule(
1791 p.cycleRule.start.withDayOfMonth(DEFAULT_CYCLE_DAY),
1792 p.cycleRule.end, Period.ofMonths(1));
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001793 return p;
1794 }
1795
1796 private static NetworkPolicy buildFakeMobilePolicy(int cycleDay, long warningBytes,
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001797 long limitBytes, boolean inferred) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001798 final NetworkTemplate template = buildTemplateMobileAll(FAKE_SUBSCRIBER_ID);
Neil Fullerd5f0a392019-06-17 19:59:51 +01001799 return new NetworkPolicy(template, cycleDay, TimeZone.getDefault().getID(), warningBytes,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001800 limitBytes, SNOOZE_NEVER, SNOOZE_NEVER, true, inferred);
1801 }
1802
1803 private void assertNetworkPolicyEquals(int expectedCycleDay, long expectedWarningBytes,
1804 long expectedLimitBytes, boolean expectedInferred) {
1805 NetworkPolicy[] policies = mService.getNetworkPolicies(
1806 mServiceContext.getOpPackageName());
1807 assertEquals("Unexpected number of network policies", 1, policies.length);
1808 NetworkPolicy actualPolicy = policies[0];
1809 NetworkPolicy expectedPolicy = buildFakeMobilePolicy(expectedCycleDay, expectedWarningBytes,
1810 expectedLimitBytes, expectedInferred);
1811 assertEquals(expectedPolicy, actualPolicy);
1812 }
1813
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001814 private static long parseTime(String time) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06001815 return ZonedDateTime.parse(time).toInstant().toEpochMilli();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001816 }
1817
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07001818 private void setNetworkPolicies(NetworkPolicy... policies) {
1819 mService.setNetworkPolicies(policies);
1820 }
1821
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001822 private static NetworkState buildWifi() {
1823 final NetworkInfo info = new NetworkInfo(TYPE_WIFI, 0, null, null);
1824 info.setDetailedState(DetailedState.CONNECTED, null, null);
1825 final LinkProperties prop = new LinkProperties();
1826 prop.setInterfaceName(TEST_IFACE);
Stephen Chena1c92b72017-02-06 13:18:11 -08001827 final NetworkCapabilities networkCapabilities = new NetworkCapabilities();
1828 return new NetworkState(info, prop, networkCapabilities, null, null, TEST_SSID);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001829 }
1830
Felipe Leme3d3308d2016-08-23 17:41:47 -07001831 private void expectHasInternetPermission(int uid, boolean hasIt) throws Exception {
1832 when(mIpm.checkUidPermission(Manifest.permission.INTERNET, uid)).thenReturn(
1833 hasIt ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED);
1834 }
1835
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001836 private void expectNetworkState(boolean roaming) throws Exception {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001837 when(mCarrierConfigManager.getConfigForSubId(eq(TEST_SUB_ID)))
Ammar Aijazib0941aa2019-04-26 18:39:50 -07001838 .thenReturn(mCarrierConfig);
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001839 when(mConnManager.getAllNetworkState()).thenReturn(new NetworkState[] {
1840 new NetworkState(buildNetworkInfo(),
1841 buildLinkProperties(TEST_IFACE),
1842 buildNetworkCapabilities(TEST_SUB_ID, roaming),
1843 new Network(TEST_NET_ID), TEST_IMSI, null)
1844 });
1845 }
1846
Ammar Aijazib0941aa2019-04-26 18:39:50 -07001847 private void expectDefaultCarrierConfig() throws Exception {
1848 when(mCarrierConfigManager.getConfigForSubId(eq(TEST_SUB_ID)))
1849 .thenReturn(CarrierConfigManager.getDefaultConfig());
1850 }
1851
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001852 private void expectMobileDefaults() throws Exception {
1853 when(mSubscriptionManager.getActiveSubscriptionIdList()).thenReturn(
1854 new int[] { TEST_SUB_ID });
1855 when(mTelephonyManager.getSubscriberId(TEST_SUB_ID)).thenReturn(TEST_IMSI);
Ammar Aijazib0941aa2019-04-26 18:39:50 -07001856 doNothing().when(mTelephonyManager).setPolicyDataEnabled(anyBoolean(), anyInt());
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001857 expectNetworkState(false /* roaming */);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001858 }
1859
Felipe Lemeef134662016-08-10 14:46:39 -07001860 private void verifyAdvisePersistThreshold() throws Exception {
1861 verify(mStatsService).advisePersistThreshold(anyLong());
Jeff Sharkey0cf6de02012-05-04 15:03:30 -07001862 }
1863
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001864 private static class TestAbstractFuture<T> extends AbstractFuture<T> {
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001865 @Override
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001866 public T get() throws InterruptedException, ExecutionException {
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001867 try {
1868 return get(5, TimeUnit.SECONDS);
1869 } catch (TimeoutException e) {
1870 throw new RuntimeException(e);
1871 }
1872 }
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001873 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001874
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -07001875 private static void assertTimeEquals(long expected, long actual) {
1876 if (expected != actual) {
1877 fail("expected " + formatTime(expected) + " but was actually " + formatTime(actual));
1878 }
1879 }
1880
1881 private static String formatTime(long millis) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06001882 return Instant.ofEpochMilli(millis) + " [" + millis + "]";
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -07001883 }
1884
1885 private static void assertEqualsFuzzy(long expected, long actual, long fuzzy) {
1886 final long low = expected - fuzzy;
1887 final long high = expected + fuzzy;
1888 if (actual < low || actual > high) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06001889 fail("value " + formatTime(actual) + " is outside [" + formatTime(low) + ","
1890 + formatTime(high) + "]");
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -07001891 }
1892 }
1893
1894 private static void assertUnique(LinkedHashSet<Long> seen, Long value) {
1895 if (!seen.add(value)) {
1896 fail("found duplicate time " + value + " in series " + seen.toString());
1897 }
1898 }
1899
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001900 private static void assertNotificationType(int expected, String actualTag) {
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001901 assertEquals("notification type mismatch for '" + actualTag + "'",
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001902 Integer.toString(expected), actualTag.substring(actualTag.lastIndexOf(':') + 1));
1903 }
1904
Felipe Lemee88729d2016-08-17 16:43:01 -07001905 private void assertUidPolicy(int uid, int expected) {
1906 final int actual = mService.getUidPolicy(uid);
1907 if (expected != actual) {
1908 fail("Wrong policy for UID " + uid + ": expected " + uidPoliciesToString(expected)
1909 + ", actual " + uidPoliciesToString(actual));
1910 }
1911 }
1912
Felipe Leme46b451f2016-08-19 08:46:17 -07001913 private void assertWhitelistUids(int... uids) {
Felipe Leme57e3d312016-08-23 14:42:52 -07001914 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_ALLOW_METERED_BACKGROUND), uids);
Felipe Leme46b451f2016-08-19 08:46:17 -07001915 }
1916
Felipe Leme3d3308d2016-08-23 17:41:47 -07001917 private void assertRestrictBackgroundOn() throws Exception {
1918 assertTrue("restrictBackground should be set", mService.getRestrictBackground());
1919 }
1920
1921 private void assertRestrictBackgroundOff() throws Exception {
1922 assertFalse("restrictBackground should not be set", mService.getRestrictBackground());
1923 }
1924
1925 private FutureIntent newRestrictBackgroundChangedFuture() {
1926 return mServiceContext
1927 .nextBroadcastIntent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
1928 }
1929
1930 private void assertRestrictBackgroundChangedReceived(Future<Intent> future,
1931 String expectedPackage) throws Exception {
1932 final String action = ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED;
1933 final Intent intent = future.get(5, TimeUnit.SECONDS);
1934 assertNotNull("Didn't get a " + action + "intent in 5 seconds");
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001935 assertEquals("Wrong package on " + action + " intent",
1936 expectedPackage, intent.getPackage());
Felipe Leme3d3308d2016-08-23 17:41:47 -07001937 }
1938
Felipe Lemee88729d2016-08-17 16:43:01 -07001939 // TODO: replace by Truth, Hamcrest, or a similar tool.
1940 private void assertContainsInAnyOrder(int[] actual, int...expected) {
1941 final StringBuilder errors = new StringBuilder();
1942 if (actual.length != expected.length) {
1943 errors.append("\tsize does not match\n");
1944 }
1945 final List<Integer> actualList =
1946 Arrays.stream(actual).boxed().collect(Collectors.<Integer>toList());
1947 final List<Integer> expectedList =
1948 Arrays.stream(expected).boxed().collect(Collectors.<Integer>toList());
1949 if (!actualList.containsAll(expectedList)) {
1950 errors.append("\tmissing elements on actual list\n");
1951 }
1952 if (!expectedList.containsAll(actualList)) {
1953 errors.append("\tmissing elements on expected list\n");
1954 }
1955 if (errors.length() > 0) {
1956 fail("assertContainsInAnyOrder(expected=" + Arrays.toString(expected)
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001957 + ", actual=" + Arrays.toString(actual) + ") failed: \n" + errors);
Felipe Lemee88729d2016-08-17 16:43:01 -07001958 }
1959 }
1960
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001961 private long getElapsedRealtime() {
1962 return mElapsedRealtime;
1963 }
1964
1965 private void setCurrentTimeMillis(long currentTimeMillis) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001966 RecurrenceRule.sClock = Clock.fixed(Instant.ofEpochMilli(currentTimeMillis),
1967 ZoneId.systemDefault());
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001968 mStartTime = currentTimeMillis;
1969 mElapsedRealtime = 0L;
1970 }
1971
1972 private long currentTimeMillis() {
1973 return mStartTime + mElapsedRealtime;
1974 }
1975
1976 private void incrementCurrentTime(long duration) {
1977 mElapsedRealtime += duration;
1978 }
1979
Felipe Leme3d3308d2016-08-23 17:41:47 -07001980 private FutureIntent mRestrictBackgroundChanged;
1981
1982 private void setRestrictBackground(boolean flag) throws Exception {
Felipe Leme3d3308d2016-08-23 17:41:47 -07001983 mService.setRestrictBackground(flag);
1984 // Sanity check.
1985 assertEquals("restrictBackground not set", flag, mService.getRestrictBackground());
1986 }
1987
Felipe Lemeef134662016-08-10 14:46:39 -07001988 /**
1989 * Creates a mock and registers it to {@link LocalServices}.
1990 */
Felipe Leme9f27e7a2016-08-12 15:19:40 -07001991 private static <T> T addLocalServiceMock(Class<T> clazz) {
Felipe Lemeef134662016-08-10 14:46:39 -07001992 final T mock = mock(clazz);
Felipe Lemeef134662016-08-10 14:46:39 -07001993 LocalServices.addService(clazz, mock);
Felipe Lemeef134662016-08-10 14:46:39 -07001994 return mock;
1995 }
1996
1997 /**
Felipe Lemeef134662016-08-10 14:46:39 -07001998 * Custom Mockito answer used to verify async {@link INetworkPolicyListener} calls.
1999 *
2000 * <p>Typical usage:
2001 * <pre><code>
2002 * mPolicyListener.expect().someCallback(any());
2003 * // do something on objects under test
2004 * mPolicyListener.waitAndVerify().someCallback(eq(expectedValue));
2005 * </code></pre>
2006 */
2007 final class NetworkPolicyListenerAnswer implements Answer<Void> {
2008 private CountDownLatch latch;
2009 private final INetworkPolicyListener listener;
2010
2011 NetworkPolicyListenerAnswer(NetworkPolicyManagerService service) {
2012 this.listener = mock(INetworkPolicyListener.class);
2013 // RemoteCallbackList needs a binder to use as key
2014 when(listener.asBinder()).thenReturn(new Binder());
2015 service.registerListener(listener);
2016 }
2017
2018 @Override
2019 public Void answer(InvocationOnMock invocation) throws Throwable {
Sudheer Shanka8ab22992018-11-29 00:08:58 -08002020 Log.d(TAG, "counting down on answer: " + invocation);
Felipe Lemeef134662016-08-10 14:46:39 -07002021 latch.countDown();
2022 return null;
2023 }
2024
2025 INetworkPolicyListener expect() {
2026 assertNull("expect() called before waitAndVerify()", latch);
2027 latch = new CountDownLatch(1);
2028 return doAnswer(this).when(listener);
2029 }
2030
2031 INetworkPolicyListener waitAndVerify() {
2032 assertNotNull("waitAndVerify() called before expect()", latch);
2033 try {
2034 assertTrue("callback not called in 5 seconds", latch.await(5, TimeUnit.SECONDS));
2035 } catch (InterruptedException e) {
2036 fail("Thread interrupted before callback called");
2037 } finally {
2038 latch = null;
2039 }
2040 return verify(listener, atLeastOnce());
2041 }
Felipe Leme3d3308d2016-08-23 17:41:47 -07002042
2043 INetworkPolicyListener verifyNotCalled() {
2044 return verify(listener, never());
2045 }
2046
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002047 }
Felipe Lemee88729d2016-08-17 16:43:01 -07002048
2049 private void setNetpolicyXml(Context context) throws Exception {
2050 mPolicyDir = context.getFilesDir();
2051 if (mPolicyDir.exists()) {
2052 IoUtils.deleteContents(mPolicyDir);
2053 }
2054 if (!TextUtils.isEmpty(mNetpolicyXml)) {
2055 final String assetPath = NETPOLICY_DIR + "/" + mNetpolicyXml;
2056 final File netConfigFile = new File(mPolicyDir, "netpolicy.xml");
2057 Log.d(TAG, "Creating " + netConfigFile + " from asset " + assetPath);
Sudheer Shanka8ab22992018-11-29 00:08:58 -08002058 try (InputStream in = context.getResources().getAssets().open(assetPath);
2059 OutputStream out = new FileOutputStream(netConfigFile)) {
Felipe Lemee88729d2016-08-17 16:43:01 -07002060 Streams.copy(in, out);
2061 }
2062 }
2063 }
2064
2065 /**
2066 * Annotation used to define the relative path of the {@code netpolicy.xml} file.
2067 */
2068 @Retention(RetentionPolicy.RUNTIME)
2069 @Target(ElementType.METHOD)
2070 public @interface NetPolicyXml {
Sudheer Shanka8ab22992018-11-29 00:08:58 -08002071 String value() default "";
Felipe Lemee88729d2016-08-17 16:43:01 -07002072 }
2073
2074 /**
2075 * Rule used to set {@code mNetPolicyXml} according to the {@link NetPolicyXml} annotation.
2076 */
2077 public static class NetPolicyMethodRule implements MethodRule {
2078
2079 @Override
2080 public Statement apply(Statement base, FrameworkMethod method, Object target) {
2081 for (Annotation annotation : method.getAnnotations()) {
2082 if ((annotation instanceof NetPolicyXml)) {
2083 final String path = ((NetPolicyXml) annotation).value();
2084 if (!path.isEmpty()) {
2085 ((NetworkPolicyManagerServiceTest) target).mNetpolicyXml = path;
2086 break;
2087 }
2088 }
2089 }
2090 return base;
2091 }
2092 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002093}