blob: 49c22a355f3d4a2f4fdf99e8f64d5239a88e11de [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;
Sudheer Shanka2d1ab902019-10-12 15:01:44 -0700116import android.os.Handler;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700117import android.os.INetworkManagementService;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700118import android.os.PersistableBundle;
Felipe Lemeef134662016-08-10 14:46:39 -0700119import android.os.PowerManagerInternal;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800120import android.os.PowerSaveState;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700121import android.os.RemoteException;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700122import android.os.SimpleClock;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700123import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700124import android.os.UserHandle;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700125import android.telephony.CarrierConfigManager;
126import android.telephony.SubscriptionManager;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900127import android.telephony.SubscriptionPlan;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700128import android.telephony.TelephonyManager;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700129import android.test.suitebuilder.annotation.MediumTest;
Felipe Lemee88729d2016-08-17 16:43:01 -0700130import android.text.TextUtils;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900131import android.util.DataUnit;
Felipe Lemeef134662016-08-10 14:46:39 -0700132import android.util.Log;
Mike Yuf9729752018-08-17 15:22:05 +0800133import android.util.Pair;
Jeff Sharkey0fc6d032018-03-30 16:25:11 -0600134import android.util.Range;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600135import android.util.RecurrenceRule;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700136
Brett Chabota26eda92018-07-23 13:08:30 -0700137import androidx.test.InstrumentationRegistry;
138import androidx.test.runner.AndroidJUnit4;
139
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700140import com.android.internal.telephony.PhoneConstants;
Lorenzo Colitti281a17c2016-10-28 12:56:03 +0900141import com.android.internal.util.test.BroadcastInterceptingContext;
142import com.android.internal.util.test.BroadcastInterceptingContext.FutureIntent;
Sudheer Shanka8ab22992018-11-29 00:08:58 -0800143import com.android.server.DeviceIdleController;
144import com.android.server.LocalServices;
Felipe Lemeef134662016-08-10 14:46:39 -0700145
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700146import com.google.common.util.concurrent.AbstractFuture;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700147
Kweku Adamsa9e55bc2018-11-19 14:59:15 -0800148import libcore.io.IoUtils;
149import libcore.io.Streams;
150
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700151import org.junit.After;
152import org.junit.Before;
Felipe Lemee88729d2016-08-17 16:43:01 -0700153import org.junit.Rule;
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700154import org.junit.Test;
Felipe Lemee88729d2016-08-17 16:43:01 -0700155import org.junit.rules.MethodRule;
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700156import org.junit.runner.RunWith;
Felipe Lemee88729d2016-08-17 16:43:01 -0700157import org.junit.runners.model.FrameworkMethod;
158import org.junit.runners.model.Statement;
Felipe Lemeef134662016-08-10 14:46:39 -0700159import org.mockito.ArgumentCaptor;
160import org.mockito.Mock;
161import org.mockito.MockitoAnnotations;
162import org.mockito.invocation.InvocationOnMock;
163import org.mockito.stubbing.Answer;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700164
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700165import java.io.File;
Felipe Lemee88729d2016-08-17 16:43:01 -0700166import java.io.FileOutputStream;
167import java.io.InputStream;
168import java.io.OutputStream;
169import java.lang.annotation.Annotation;
170import java.lang.annotation.ElementType;
171import java.lang.annotation.Retention;
172import java.lang.annotation.RetentionPolicy;
173import java.lang.annotation.Target;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600174import java.time.Clock;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600175import java.time.Instant;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600176import java.time.Period;
177import java.time.ZoneId;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700178import java.time.ZoneOffset;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600179import java.time.ZonedDateTime;
Mike Yuf9729752018-08-17 15:22:05 +0800180import java.util.ArrayList;
Felipe Lemee88729d2016-08-17 16:43:01 -0700181import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700182import java.util.Calendar;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600183import java.util.Iterator;
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700184import java.util.LinkedHashSet;
Felipe Lemeef134662016-08-10 14:46:39 -0700185import java.util.List;
Neil Fullerd5f0a392019-06-17 19:59:51 +0100186import java.util.TimeZone;
Felipe Lemeef134662016-08-10 14:46:39 -0700187import java.util.concurrent.CountDownLatch;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700188import java.util.concurrent.ExecutionException;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700189import java.util.concurrent.Future;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700190import java.util.concurrent.TimeUnit;
191import java.util.concurrent.TimeoutException;
Felipe Lemee88729d2016-08-17 16:43:01 -0700192import java.util.stream.Collectors;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700193
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700194/**
195 * Tests for {@link NetworkPolicyManagerService}.
196 */
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700197@RunWith(AndroidJUnit4.class)
Felipe Leme3d3308d2016-08-23 17:41:47 -0700198@MediumTest
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700199public class NetworkPolicyManagerServiceTest {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700200 private static final String TAG = "NetworkPolicyManagerServiceTest";
201
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700202 private static final long TEST_START = 1194220800000L;
203 private static final String TEST_IFACE = "test0";
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700204 private static final String TEST_SSID = "AndroidAP";
Jeff Sharkey2e471452018-01-19 18:02:47 +0900205 private static final String TEST_IMSI = "310210";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700206 private static final int TEST_SUB_ID = 42;
207 private static final int TEST_NET_ID = 24;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700208
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +0900209 private static NetworkTemplate sTemplateWifi = buildTemplateWifi(TEST_SSID);
210 private static NetworkTemplate sTemplateMobileAll = buildTemplateMobileAll(TEST_IMSI);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700211
Felipe Lemee88729d2016-08-17 16:43:01 -0700212 /**
213 * Path on assets where files used by {@link NetPolicyXml} are located.
214 */
215 private static final String NETPOLICY_DIR = "NetworkPolicyManagerServiceTest/netpolicy";
Neil Fullerd5f0a392019-06-17 19:59:51 +0100216 private static final String TIMEZONE_UTC = "UTC";
Felipe Lemee88729d2016-08-17 16:43:01 -0700217
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700218 private BroadcastInterceptingContext mServiceContext;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700219 private File mPolicyDir;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700220
Felipe Lemee88729d2016-08-17 16:43:01 -0700221 /**
222 * Relative path of the XML file that will be used as {@code netpolicy.xml}.
223 *
224 * <p>Typically set through a {@link NetPolicyXml} annotation in the test method.
225 */
226 private String mNetpolicyXml;
227
Felipe Lemeef134662016-08-10 14:46:39 -0700228 private @Mock IActivityManager mActivityManager;
Felipe Lemeef134662016-08-10 14:46:39 -0700229 private @Mock INetworkManagementService mNetworkManager;
Felipe Lemeef134662016-08-10 14:46:39 -0700230 private @Mock IConnectivityManager mConnManager;
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +0900231 private @Mock ConnectivityManager mConnectivityManager;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700232 private @Mock NotificationManager mNotifManager;
Felipe Lemeef134662016-08-10 14:46:39 -0700233 private @Mock PackageManager mPackageManager;
Felipe Leme3d3308d2016-08-23 17:41:47 -0700234 private @Mock IPackageManager mIpm;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700235 private @Mock SubscriptionManager mSubscriptionManager;
236 private @Mock CarrierConfigManager mCarrierConfigManager;
237 private @Mock TelephonyManager mTelephonyManager;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700238
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +0900239 private ArgumentCaptor<ConnectivityManager.NetworkCallback> mNetworkCallbackCaptor =
240 ArgumentCaptor.forClass(ConnectivityManager.NetworkCallback.class);
241
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700242 private ActivityManagerInternal mActivityManagerInternal;
243 private NetworkStatsManagerInternal mStatsService;
Sudheer Shankae7361852017-03-07 11:51:46 -0800244
Felipe Lemeef134662016-08-10 14:46:39 -0700245 private IUidObserver mUidObserver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700246 private INetworkManagementEventObserver mNetworkObserver;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700247
Felipe Lemeef134662016-08-10 14:46:39 -0700248 private NetworkPolicyListenerAnswer mPolicyListener;
249 private NetworkPolicyManagerService mService;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700250
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700251 /**
252 * In some of the tests while initializing NetworkPolicyManagerService,
253 * ACTION_RESTRICT_BACKGROUND_CHANGED is broadcasted. This is for capturing that broadcast.
254 */
255 private FutureIntent mFutureIntent;
256
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700257 private long mStartTime;
258 private long mElapsedRealtime;
259
Jeff Sharkeycae04a22012-03-22 15:18:52 -0700260 private static final int USER_ID = 0;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700261 private static final int FAKE_SUB_ID = 3737373;
262 private static final String FAKE_SUBSCRIBER_ID = "FAKE_SUB_ID";
263 private static final int DEFAULT_CYCLE_DAY = 1;
264 private static final int INVALID_CARRIER_CONFIG_VALUE = -9999;
265 private long mDefaultWarningBytes; // filled in with the actual default before tests are run
266 private long mDefaultLimitBytes; // filled in with the actual default before tests are run
Ammar Aijazib0941aa2019-04-26 18:39:50 -0700267 private PersistableBundle mCarrierConfig = CarrierConfigManager.getDefaultConfig();
Jeff Sharkeycae04a22012-03-22 15:18:52 -0700268
Felipe Lemee88729d2016-08-17 16:43:01 -0700269 private static final int APP_ID_A = android.os.Process.FIRST_APPLICATION_UID + 4;
270 private static final int APP_ID_B = android.os.Process.FIRST_APPLICATION_UID + 8;
271 private static final int APP_ID_C = android.os.Process.FIRST_APPLICATION_UID + 15;
272 private static final int APP_ID_D = android.os.Process.FIRST_APPLICATION_UID + 16;
273 private static final int APP_ID_E = android.os.Process.FIRST_APPLICATION_UID + 23;
274 private static final int APP_ID_F = android.os.Process.FIRST_APPLICATION_UID + 42;
Jeff Sharkeycae04a22012-03-22 15:18:52 -0700275
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700276 private static final int UID_A = UserHandle.getUid(USER_ID, APP_ID_A);
277 private static final int UID_B = UserHandle.getUid(USER_ID, APP_ID_B);
Felipe Lemee88729d2016-08-17 16:43:01 -0700278 private static final int UID_C = UserHandle.getUid(USER_ID, APP_ID_C);
279 private static final int UID_D = UserHandle.getUid(USER_ID, APP_ID_D);
280 private static final int UID_E = UserHandle.getUid(USER_ID, APP_ID_E);
281 private static final int UID_F = UserHandle.getUid(USER_ID, APP_ID_F);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700282
Felipe Lemeef134662016-08-10 14:46:39 -0700283 private static final String PKG_NAME_A = "name.is.A,pkg.A";
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700284 private static final String PKG_NAME_B = "name.is.B,pkg.B";
285 private static final String PKG_NAME_C = "name.is.C,pkg.C";
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700286
Felipe Lemee88729d2016-08-17 16:43:01 -0700287 public final @Rule NetPolicyMethodRule mNetPolicyXmlRule = new NetPolicyMethodRule();
288
Jeff Sharkey9911a282018-02-14 22:29:11 -0700289 private final Clock mClock = new SimpleClock(ZoneOffset.UTC) {
290 @Override
291 public long millis() {
292 return currentTimeMillis();
293 }
294 };
295
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700296 private void registerLocalServices() {
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700297 addLocalServiceMock(DeviceIdleController.LocalService.class);
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700298
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700299 final UsageStatsManagerInternal usageStats =
300 addLocalServiceMock(UsageStatsManagerInternal.class);
301 when(usageStats.getIdleUidsForUser(anyInt())).thenReturn(new int[]{});
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700302
Sudheer Shankae7361852017-03-07 11:51:46 -0800303 mActivityManagerInternal = addLocalServiceMock(ActivityManagerInternal.class);
jackqdyulei29c82ab2017-03-10 14:09:16 -0800304
305 final PowerSaveState state = new PowerSaveState.Builder()
306 .setBatterySaverEnabled(false).build();
307 final PowerManagerInternal pmInternal = addLocalServiceMock(PowerManagerInternal.class);
308 when(pmInternal.getLowPowerState(anyInt())).thenReturn(state);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700309
310 mStatsService = addLocalServiceMock(NetworkStatsManagerInternal.class);
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700311 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700312
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700313 @Before
314 public void callSystemReady() throws Exception {
Felipe Lemeef134662016-08-10 14:46:39 -0700315 MockitoAnnotations.initMocks(this);
316
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700317 final Context context = InstrumentationRegistry.getContext();
Felipe Lemeef134662016-08-10 14:46:39 -0700318
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700319 setCurrentTimeMillis(TEST_START);
320
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700321 registerLocalServices();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700322 // Intercept various broadcasts, and pretend that uids have packages.
323 // Also return mock service instances for a few critical services.
Felipe Lemeef134662016-08-10 14:46:39 -0700324 mServiceContext = new BroadcastInterceptingContext(context) {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700325 @Override
326 public PackageManager getPackageManager() {
Felipe Lemeef134662016-08-10 14:46:39 -0700327 return mPackageManager;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700328 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700329
330 @Override
331 public void startActivity(Intent intent) {
332 // ignored
333 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700334
335 @Override
336 public Object getSystemService(String name) {
337 switch (name) {
338 case Context.TELEPHONY_SUBSCRIPTION_SERVICE:
339 return mSubscriptionManager;
340 case Context.CARRIER_CONFIG_SERVICE:
341 return mCarrierConfigManager;
342 case Context.TELEPHONY_SERVICE:
343 return mTelephonyManager;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700344 case Context.NOTIFICATION_SERVICE:
345 return mNotifManager;
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +0900346 case Context.CONNECTIVITY_SERVICE:
347 return mConnectivityManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700348 default:
349 return super.getSystemService(name);
350 }
351 }
Jeff Sharkey2e471452018-01-19 18:02:47 +0900352
353 @Override
354 public void enforceCallingOrSelfPermission(String permission, String message) {
355 // Assume that we're AID_SYSTEM
356 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700357 };
358
Felipe Lemee88729d2016-08-17 16:43:01 -0700359 setNetpolicyXml(context);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700360
Felipe Lemeef134662016-08-10 14:46:39 -0700361 doAnswer(new Answer<Void>() {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700362
Felipe Lemeef134662016-08-10 14:46:39 -0700363 @Override
364 public Void answer(InvocationOnMock invocation) throws Throwable {
365 mUidObserver = (IUidObserver) invocation.getArguments()[0];
366 Log.d(TAG, "set mUidObserver to " + mUidObserver);
367 return null;
368 }
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800369 }).when(mActivityManager).registerUidObserver(any(), anyInt(),
Sudheer Shanka8ab22992018-11-29 00:08:58 -0800370 eq(NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE), any(String.class));
Felipe Lemeef134662016-08-10 14:46:39 -0700371
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700372 mFutureIntent = newRestrictBackgroundChangedFuture();
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700373 mService = new NetworkPolicyManagerService(mServiceContext, mActivityManager,
Jeff Sharkey9911a282018-02-14 22:29:11 -0700374 mNetworkManager, mIpm, mClock, mPolicyDir, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700375 mService.bindConnectivityManager(mConnManager);
Felipe Lemeef134662016-08-10 14:46:39 -0700376 mPolicyListener = new NetworkPolicyListenerAnswer(mService);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700377
Felipe Lemeef134662016-08-10 14:46:39 -0700378 // Sets some common expectations.
379 when(mPackageManager.getPackageInfo(anyString(), anyInt())).thenAnswer(
380 new Answer<PackageInfo>() {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700381
Felipe Lemeef134662016-08-10 14:46:39 -0700382 @Override
383 public PackageInfo answer(InvocationOnMock invocation) throws Throwable {
384 final String packageName = (String) invocation.getArguments()[0];
385 final PackageInfo info = new PackageInfo();
386 final Signature signature;
387 if ("android".equals(packageName)) {
388 signature = new Signature("F00D");
389 } else {
390 signature = new Signature("DEAD");
391 }
392 info.signatures = new Signature[] {
393 signature
394 };
395 return info;
396 }
397 });
398 when(mPackageManager.getApplicationInfoAsUser(anyString(), anyInt(), anyInt()))
399 .thenReturn(new ApplicationInfo());
400 when(mPackageManager.getPackagesForUid(UID_A)).thenReturn(new String[] {PKG_NAME_A});
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700401 when(mPackageManager.getPackagesForUid(UID_B)).thenReturn(new String[] {PKG_NAME_B});
402 when(mPackageManager.getPackagesForUid(UID_C)).thenReturn(new String[] {PKG_NAME_C});
403 when(mPackageManager.getApplicationInfo(eq(PKG_NAME_A), anyInt()))
404 .thenReturn(buildApplicationInfo(PKG_NAME_A));
405 when(mPackageManager.getApplicationInfo(eq(PKG_NAME_B), anyInt()))
406 .thenReturn(buildApplicationInfo(PKG_NAME_B));
407 when(mPackageManager.getApplicationInfo(eq(PKG_NAME_C), anyInt()))
408 .thenReturn(buildApplicationInfo(PKG_NAME_C));
Felipe Lemeef134662016-08-10 14:46:39 -0700409 when(mNetworkManager.isBandwidthControlEnabled()).thenReturn(true);
Sudheer Shanka543339f2017-07-28 15:18:07 -0700410 when(mNetworkManager.setDataSaverModeEnabled(anyBoolean())).thenReturn(true);
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +0900411 doNothing().when(mConnectivityManager)
412 .registerNetworkCallback(any(), mNetworkCallbackCaptor.capture());
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700413
Ammar Aijazib0941aa2019-04-26 18:39:50 -0700414 // Create the expected carrier config
415 mCarrierConfig.putBoolean(CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL, true);
416
Felipe Lemeef134662016-08-10 14:46:39 -0700417 // Prepare NPMS.
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800418 mService.systemReady(mService.networkScoreAndNetworkManagementServiceReady());
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700419
Felipe Lemeef134662016-08-10 14:46:39 -0700420 // catch INetworkManagementEventObserver during systemReady()
Felipe Leme3d3308d2016-08-23 17:41:47 -0700421 final ArgumentCaptor<INetworkManagementEventObserver> networkObserver =
Sudheer Shanka8ab22992018-11-29 00:08:58 -0800422 ArgumentCaptor.forClass(INetworkManagementEventObserver.class);
Felipe Lemeef134662016-08-10 14:46:39 -0700423 verify(mNetworkManager).registerObserver(networkObserver.capture());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700424 mNetworkObserver = networkObserver.getValue();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700425
426 NetworkPolicy defaultPolicy = mService.buildDefaultMobilePolicy(0, "");
427 mDefaultWarningBytes = defaultPolicy.warningBytes;
428 mDefaultLimitBytes = defaultPolicy.limitBytes;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700429 }
430
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700431 @After
432 public void removeFiles() throws Exception {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700433 for (File file : mPolicyDir.listFiles()) {
434 file.delete();
435 }
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700436 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700437
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700438 @After
439 public void unregisterLocalServices() throws Exception {
440 // Registered by NetworkPolicyManagerService's constructor.
Felipe Lemeef134662016-08-10 14:46:39 -0700441 LocalServices.removeServiceForTest(NetworkPolicyManagerInternal.class);
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700442
443 // Added in registerLocalServices()
444 LocalServices.removeServiceForTest(ActivityManagerInternal.class);
445 LocalServices.removeServiceForTest(PowerManagerInternal.class);
446 LocalServices.removeServiceForTest(DeviceIdleController.LocalService.class);
447 LocalServices.removeServiceForTest(UsageStatsManagerInternal.class);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700448 LocalServices.removeServiceForTest(NetworkStatsManagerInternal.class);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700449 }
450
Jeff Sharkey53313d72017-07-13 16:47:32 -0600451 @After
452 public void resetClock() throws Exception {
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600453 RecurrenceRule.sClock = Clock.systemDefaultZone();
Jeff Sharkey53313d72017-07-13 16:47:32 -0600454 }
455
Felipe Lemee88729d2016-08-17 16:43:01 -0700456 @Test
Felipe Leme3d3308d2016-08-23 17:41:47 -0700457 public void testTurnRestrictBackgroundOn() throws Exception {
458 assertRestrictBackgroundOff(); // Sanity check.
459 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
460 setRestrictBackground(true);
461 assertRestrictBackgroundChangedReceived(futureIntent, null);
462 }
463
464 @Test
465 @NetPolicyXml("restrict-background-on.xml")
466 public void testTurnRestrictBackgroundOff() throws Exception {
467 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700468 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700469 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
470 setRestrictBackground(false);
471 assertRestrictBackgroundChangedReceived(futureIntent, null);
472 }
473
474 /**
475 * Adds whitelist when restrict background is on - app should receive an intent.
476 */
477 @Test
478 @NetPolicyXml("restrict-background-on.xml")
479 public void testAddRestrictBackgroundWhitelist_restrictBackgroundOn() throws Exception {
480 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700481 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700482 addRestrictBackgroundWhitelist(true);
483 }
484
485 /**
486 * Adds whitelist when restrict background is off - app should not receive an intent.
487 */
488 @Test
489 public void testAddRestrictBackgroundWhitelist_restrictBackgroundOff() throws Exception {
490 assertRestrictBackgroundOff(); // Sanity check.
491 addRestrictBackgroundWhitelist(false);
492 }
493
494 private void addRestrictBackgroundWhitelist(boolean expectIntent) throws Exception {
Felipe Leme57e3d312016-08-23 14:42:52 -0700495 // Sanity checks.
496 assertWhitelistUids();
497 assertUidPolicy(UID_A, POLICY_NONE);
498
Felipe Leme3d3308d2016-08-23 17:41:47 -0700499 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700500 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700501
Felipe Leme57e3d312016-08-23 14:42:52 -0700502 mService.setUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700503
504 assertWhitelistUids(UID_A);
Felipe Leme57e3d312016-08-23 14:42:52 -0700505 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700506 mPolicyListener.waitAndVerify()
507 .onUidPoliciesChanged(APP_ID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700508 if (expectIntent) {
509 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
510 } else {
511 futureIntent.assertNotReceived();
512 }
513 }
514
515 /**
516 * Removes whitelist when restrict background is on - app should receive an intent.
517 */
518 @Test
519 @NetPolicyXml("uidA-whitelisted-restrict-background-on.xml")
520 public void testRemoveRestrictBackgroundWhitelist_restrictBackgroundOn() throws Exception {
521 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700522 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700523 removeRestrictBackgroundWhitelist(true);
524 }
525
526 /**
527 * Removes whitelist when restrict background is off - app should not receive an intent.
528 */
529 @Test
530 @NetPolicyXml("uidA-whitelisted-restrict-background-off.xml")
531 public void testRemoveRestrictBackgroundWhitelist_restrictBackgroundOff() throws Exception {
532 assertRestrictBackgroundOff(); // Sanity check.
533 removeRestrictBackgroundWhitelist(false);
534 }
535
jackqdyulei29c82ab2017-03-10 14:09:16 -0800536 @Test
537 public void testLowPowerModeObserver_ListenersRegistered()
538 throws Exception {
539 PowerManagerInternal pmInternal = LocalServices.getService(PowerManagerInternal.class);
540
541 verify(pmInternal, atLeast(2)).registerLowPowerModeObserver(any());
542 }
543
544 @Test
545 public void updateRestrictBackgroundByLowPowerMode_RestrictOnBeforeBsm_RestrictOnAfterBsm()
546 throws Exception {
547 setRestrictBackground(true);
548 PowerSaveState stateOn = new PowerSaveState.Builder()
549 .setGlobalBatterySaverEnabled(true)
550 .setBatterySaverEnabled(false)
551 .build();
552 mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
553
554 // RestrictBackground should be on even though battery saver want to turn it off
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700555 assertTrue(mService.getRestrictBackground());
jackqdyulei29c82ab2017-03-10 14:09:16 -0800556
557 PowerSaveState stateOff = new PowerSaveState.Builder()
558 .setGlobalBatterySaverEnabled(false)
559 .setBatterySaverEnabled(false)
560 .build();
561 mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
562
563 // RestrictBackground should be on, following its previous state
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700564 assertTrue(mService.getRestrictBackground());
jackqdyulei29c82ab2017-03-10 14:09:16 -0800565 }
566
567 @Test
568 public void updateRestrictBackgroundByLowPowerMode_RestrictOffBeforeBsm_RestrictOffAfterBsm()
569 throws Exception {
570 setRestrictBackground(false);
571 PowerSaveState stateOn = new PowerSaveState.Builder()
572 .setGlobalBatterySaverEnabled(true)
573 .setBatterySaverEnabled(true)
574 .build();
575
jackqdyulei29c82ab2017-03-10 14:09:16 -0800576 mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
577
578 // RestrictBackground should be turned on because of battery saver
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700579 assertTrue(mService.getRestrictBackground());
jackqdyulei29c82ab2017-03-10 14:09:16 -0800580
581 PowerSaveState stateOff = new PowerSaveState.Builder()
582 .setGlobalBatterySaverEnabled(false)
583 .setBatterySaverEnabled(false)
584 .build();
585 mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
586
587 // RestrictBackground should be off, following its previous state
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700588 assertFalse(mService.getRestrictBackground());
jackqdyulei29c82ab2017-03-10 14:09:16 -0800589 }
590
591 @Test
592 public void updateRestrictBackgroundByLowPowerMode_StatusChangedInBsm_DoNotRestore()
593 throws Exception {
594 setRestrictBackground(true);
595 PowerSaveState stateOn = new PowerSaveState.Builder()
596 .setGlobalBatterySaverEnabled(true)
597 .setBatterySaverEnabled(true)
598 .build();
599 mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
600
601 // RestrictBackground should still be on
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700602 assertTrue(mService.getRestrictBackground());
jackqdyulei29c82ab2017-03-10 14:09:16 -0800603
604 // User turns off RestrictBackground manually
605 setRestrictBackground(false);
606 PowerSaveState stateOff = new PowerSaveState.Builder().setBatterySaverEnabled(
607 false).build();
608 mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
609
610 // RestrictBackground should be off because user changes it manually
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700611 assertFalse(mService.getRestrictBackground());
jackqdyulei29c82ab2017-03-10 14:09:16 -0800612 }
613
Felipe Leme3d3308d2016-08-23 17:41:47 -0700614 private void removeRestrictBackgroundWhitelist(boolean expectIntent) throws Exception {
Felipe Leme57e3d312016-08-23 14:42:52 -0700615 // Sanity checks.
616 assertWhitelistUids(UID_A);
617 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
618
Felipe Leme3d3308d2016-08-23 17:41:47 -0700619 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700620 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700621
Felipe Leme57e3d312016-08-23 14:42:52 -0700622 mService.setUidPolicy(UID_A, POLICY_NONE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700623
624 assertWhitelistUids();
Felipe Leme57e3d312016-08-23 14:42:52 -0700625 assertUidPolicy(UID_A, POLICY_NONE);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700626 mPolicyListener.waitAndVerify().onUidPoliciesChanged(APP_ID_A, POLICY_NONE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700627 if (expectIntent) {
628 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
629 } else {
630 futureIntent.assertNotReceived();
631 }
632 }
633
634 /**
Felipe Leme57e3d312016-08-23 14:42:52 -0700635 * Adds blacklist when restrict background is on - app should not receive an intent.
Felipe Leme3d3308d2016-08-23 17:41:47 -0700636 */
637 @Test
638 @NetPolicyXml("restrict-background-on.xml")
639 public void testAddRestrictBackgroundBlacklist_restrictBackgroundOn() throws Exception {
640 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700641 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme57e3d312016-08-23 14:42:52 -0700642 addRestrictBackgroundBlacklist(false);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700643 }
644
645 /**
646 * Adds blacklist when restrict background is off - app should receive an intent.
647 */
648 @Test
649 public void testAddRestrictBackgroundBlacklist_restrictBackgroundOff() throws Exception {
650 assertRestrictBackgroundOff(); // Sanity check.
651 addRestrictBackgroundBlacklist(true);
652 }
653
654 private void addRestrictBackgroundBlacklist(boolean expectIntent) throws Exception {
655 assertUidPolicy(UID_A, POLICY_NONE); // Sanity check.
656 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700657 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700658
659 mService.setUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
660
661 assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700662 mPolicyListener.waitAndVerify()
663 .onUidPoliciesChanged(APP_ID_A, POLICY_REJECT_METERED_BACKGROUND);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700664 if (expectIntent) {
665 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
666 } else {
667 futureIntent.assertNotReceived();
668 }
669 }
670
671 /**
Felipe Leme57e3d312016-08-23 14:42:52 -0700672 * Removes blacklist when restrict background is on - app should not receive an intent.
Felipe Leme3d3308d2016-08-23 17:41:47 -0700673 */
674 @Test
675 @NetPolicyXml("uidA-blacklisted-restrict-background-on.xml")
676 public void testRemoveRestrictBackgroundBlacklist_restrictBackgroundOn() throws Exception {
677 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700678 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme57e3d312016-08-23 14:42:52 -0700679 removeRestrictBackgroundBlacklist(false);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700680 }
681
682 /**
683 * Removes blacklist when restrict background is off - app should receive an intent.
684 */
685 @Test
686 @NetPolicyXml("uidA-blacklisted-restrict-background-off.xml")
687 public void testRemoveRestrictBackgroundBlacklist_restrictBackgroundOff() throws Exception {
688 assertRestrictBackgroundOff(); // Sanity check.
689 removeRestrictBackgroundBlacklist(true);
690 }
691
692 private void removeRestrictBackgroundBlacklist(boolean expectIntent) throws Exception {
693 assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND); // Sanity check.
694 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700695 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700696
697 mService.setUidPolicy(UID_A, POLICY_NONE);
698
699 assertUidPolicy(UID_A, POLICY_NONE);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700700 mPolicyListener.waitAndVerify()
701 .onUidPoliciesChanged(APP_ID_A, POLICY_NONE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700702 if (expectIntent) {
703 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
704 } else {
705 futureIntent.assertNotReceived();
706 }
707 }
708
Felipe Leme51a63642016-08-30 12:15:09 -0700709 @Test
Felipe Lemec08ecdf2016-08-30 12:57:35 -0700710 @NetPolicyXml("uidA-blacklisted-restrict-background-on.xml")
Felipe Leme3d3308d2016-08-23 17:41:47 -0700711 public void testBlacklistedAppIsNotNotifiedWhenRestrictBackgroundIsOn() throws Exception {
712 // Sanity checks.
713 assertRestrictBackgroundOn();
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700714 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700715 assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
716
717 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
718 setRestrictBackground(true);
719 futureIntent.assertNotReceived();
720 }
721
Felipe Leme51a63642016-08-30 12:15:09 -0700722 @Test
Felipe Lemec08ecdf2016-08-30 12:57:35 -0700723 @NetPolicyXml("uidA-whitelisted-restrict-background-on.xml")
Felipe Leme3d3308d2016-08-23 17:41:47 -0700724 public void testWhitelistedAppIsNotNotifiedWhenRestrictBackgroundIsOn() throws Exception {
725 // Sanity checks.
Felipe Lemec08ecdf2016-08-30 12:57:35 -0700726 assertRestrictBackgroundOn();
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700727 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700728 assertWhitelistUids(UID_A);
729
730 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
731 setRestrictBackground(true);
732 futureIntent.assertNotReceived();
733 }
734
Andreas Gampe84d156b2016-09-03 10:50:38 -0700735 @Test
Felipe Leme57e3d312016-08-23 14:42:52 -0700736 @NetPolicyXml("uidA-whitelisted-restrict-background-on.xml")
737 public void testWhitelistedAppIsNotifiedWhenBlacklisted() throws Exception {
738 // Sanity checks.
739 assertRestrictBackgroundOn();
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700740 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme57e3d312016-08-23 14:42:52 -0700741 assertWhitelistUids(UID_A);
742
743 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
744 mService.setUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
745 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
746 }
747
Felipe Leme3d3308d2016-08-23 17:41:47 -0700748 @Test
Felipe Lemee88729d2016-08-17 16:43:01 -0700749 @NetPolicyXml("restrict-background-lists-whitelist-format.xml")
750 public void testRestrictBackgroundLists_whitelistFormat() throws Exception {
Felipe Leme46b451f2016-08-19 08:46:17 -0700751 restrictBackgroundListsTest();
752 }
753
754 @Test
755 @NetPolicyXml("restrict-background-lists-uid-policy-format.xml")
756 public void testRestrictBackgroundLists_uidPolicyFormat() throws Exception {
757 restrictBackgroundListsTest();
758 }
759
760 private void restrictBackgroundListsTest() throws Exception {
Felipe Leme8546a442016-08-23 09:38:20 -0700761 // UIds that are whitelisted.
Felipe Leme46b451f2016-08-19 08:46:17 -0700762 assertWhitelistUids(UID_A, UID_B, UID_C);
763 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
764 assertUidPolicy(UID_B, POLICY_ALLOW_METERED_BACKGROUND);
765 assertUidPolicy(UID_C, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Lemee88729d2016-08-17 16:43:01 -0700766
Felipe Leme8546a442016-08-23 09:38:20 -0700767 // UIDs that are blacklisted.
Felipe Lemee88729d2016-08-17 16:43:01 -0700768 assertUidPolicy(UID_D, POLICY_NONE);
769 assertUidPolicy(UID_E, POLICY_REJECT_METERED_BACKGROUND);
Felipe Leme8546a442016-08-23 09:38:20 -0700770
771 // UIDS that have legacy policies.
Felipe Leme46b451f2016-08-19 08:46:17 -0700772 assertUidPolicy(UID_F, 2); // POLICY_ALLOW_BACKGROUND_BATTERY_SAVE
773
774 // Remove whitelist.
Felipe Leme57e3d312016-08-23 14:42:52 -0700775 mService.setUidPolicy(UID_A, POLICY_NONE);
Felipe Leme46b451f2016-08-19 08:46:17 -0700776 assertUidPolicy(UID_A, POLICY_NONE);
777 assertWhitelistUids(UID_B, UID_C);
778
779 // Add whitelist when blacklisted.
Felipe Leme57e3d312016-08-23 14:42:52 -0700780 mService.setUidPolicy(UID_E, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme46b451f2016-08-19 08:46:17 -0700781 assertUidPolicy(UID_E, POLICY_ALLOW_METERED_BACKGROUND);
782 assertWhitelistUids(UID_B, UID_C, UID_E);
783
784 // Add blacklist when whitelisted.
785 mService.setUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND);
786 assertUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND);
787 assertWhitelistUids(UID_C, UID_E);
788 }
789
790 /**
791 * Tests scenario where an UID had {@code restrict-background} and {@code uid-policy} tags.
792 */
793 @Test
794 @NetPolicyXml("restrict-background-lists-mixed-format.xml")
795 public void testRestrictBackgroundLists_mixedFormat() throws Exception {
796 assertWhitelistUids(UID_A, UID_C, UID_D);
797 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme57e3d312016-08-23 14:42:52 -0700798 assertUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND); // Blacklist prevails.
Felipe Leme46b451f2016-08-19 08:46:17 -0700799 assertUidPolicy(UID_C, (POLICY_ALLOW_METERED_BACKGROUND | 2));
800 assertUidPolicy(UID_D, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Lemee88729d2016-08-17 16:43:01 -0700801 }
802
Felipe Leme6f51a0a2016-08-24 15:11:51 -0700803 @Test
804 @NetPolicyXml("uids-with-mixed-policies.xml")
805 public void testGetUidsWithPolicy() throws Exception {
Felipe Leme03f90292016-09-08 18:10:32 -0700806 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_NONE));
Felipe Leme6f51a0a2016-08-24 15:11:51 -0700807 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND),
808 UID_B, UID_D);
809 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_ALLOW_METERED_BACKGROUND),
810 UID_E, UID_F);
811 // Legacy (POLICY_ALLOW_BACKGROUND_BATTERY_SAVE)
812 assertContainsInAnyOrder(mService.getUidsWithPolicy(2),
813 UID_C, UID_D, UID_F);
814 }
815
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700816 // NOTE: testPolicyChangeTriggersListener() is too superficial, they
Felipe Lemeef134662016-08-10 14:46:39 -0700817 // don't check for side-effects (like calls to NetworkManagementService) neither cover all
818 // different modes (Data Saver, Battery Saver, Doze, App idle, etc...).
819 // These scenarios are extensively tested on CTS' HostsideRestrictBackgroundNetworkTests.
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700820 @Test
Felipe Lemeef134662016-08-10 14:46:39 -0700821 public void testUidForeground() throws Exception {
822 // push all uids into background
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700823 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE, 0);
824 callOnUidStateChanged(UID_B, ActivityManager.PROCESS_STATE_SERVICE, 0);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700825 assertFalse(mService.isUidForeground(UID_A));
826 assertFalse(mService.isUidForeground(UID_B));
827
Felipe Lemeef134662016-08-10 14:46:39 -0700828 // push one of the uids into foreground
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700829 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_TOP, 0);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700830 assertTrue(mService.isUidForeground(UID_A));
831 assertFalse(mService.isUidForeground(UID_B));
832
833 // and swap another uid into foreground
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700834 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE, 0);
835 callOnUidStateChanged(UID_B, ActivityManager.PROCESS_STATE_TOP, 0);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700836 assertFalse(mService.isUidForeground(UID_A));
837 assertTrue(mService.isUidForeground(UID_B));
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700838 }
839
Kweku Adamsa9e55bc2018-11-19 14:59:15 -0800840 @Test
841 public void testAppIdleTempWhitelisting() throws Exception {
842 mService.setAppIdleWhitelist(UID_A, true);
843 mService.setAppIdleWhitelist(UID_B, false);
844 int[] whitelistedIds = mService.getAppIdleWhitelist();
845 assertTrue(Arrays.binarySearch(whitelistedIds, UID_A) >= 0);
846 assertTrue(Arrays.binarySearch(whitelistedIds, UID_B) < 0);
847 assertFalse(mService.isUidIdle(UID_A));
848 // Can't currently guarantee UID_B's app idle state.
849 // TODO: expand with multiple app idle states.
850 }
851
Jeff Sharkey53313d72017-07-13 16:47:32 -0600852 private static long computeLastCycleBoundary(long currentTime, NetworkPolicy policy) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600853 RecurrenceRule.sClock = Clock.fixed(Instant.ofEpochMilli(currentTime),
854 ZoneId.systemDefault());
Jeff Sharkey0fc6d032018-03-30 16:25:11 -0600855 final Iterator<Range<ZonedDateTime>> it = policy.cycleIterator();
Jeff Sharkey53313d72017-07-13 16:47:32 -0600856 while (it.hasNext()) {
Jeff Sharkey0fc6d032018-03-30 16:25:11 -0600857 final Range<ZonedDateTime> cycle = it.next();
858 if (cycle.getLower().toInstant().toEpochMilli() < currentTime) {
859 return cycle.getLower().toInstant().toEpochMilli();
Jeff Sharkey53313d72017-07-13 16:47:32 -0600860 }
861 }
862 throw new IllegalStateException(
863 "Failed to find current cycle for " + policy + " at " + currentTime);
864 }
865
866 private static long computeNextCycleBoundary(long currentTime, NetworkPolicy policy) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600867 RecurrenceRule.sClock = Clock.fixed(Instant.ofEpochMilli(currentTime),
868 ZoneId.systemDefault());
Jeff Sharkey0fc6d032018-03-30 16:25:11 -0600869 return policy.cycleIterator().next().getUpper().toInstant().toEpochMilli();
Jeff Sharkey53313d72017-07-13 16:47:32 -0600870 }
871
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700872 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700873 public void testLastCycleBoundaryThisMonth() throws Exception {
874 // assume cycle day of "5th", which should be in same month
875 final long currentTime = parseTime("2007-11-14T00:00:00.000Z");
876 final long expectedCycle = parseTime("2007-11-05T00:00:00.000Z");
877
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700878 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800879 sTemplateWifi, 5, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700880 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700881 assertTimeEquals(expectedCycle, actualCycle);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700882 }
883
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700884 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700885 public void testLastCycleBoundaryLastMonth() throws Exception {
886 // assume cycle day of "20th", which should be in last month
887 final long currentTime = parseTime("2007-11-14T00:00:00.000Z");
888 final long expectedCycle = parseTime("2007-10-20T00:00:00.000Z");
889
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700890 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800891 sTemplateWifi, 20, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700892 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700893 assertTimeEquals(expectedCycle, actualCycle);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700894 }
895
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700896 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700897 public void testLastCycleBoundaryThisMonthFebruary() throws Exception {
898 // assume cycle day of "30th" in february; should go to january
899 final long currentTime = parseTime("2007-02-14T00:00:00.000Z");
900 final long expectedCycle = parseTime("2007-01-30T00:00:00.000Z");
901
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700902 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800903 sTemplateWifi, 30, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700904 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700905 assertTimeEquals(expectedCycle, actualCycle);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700906 }
907
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700908 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700909 public void testLastCycleBoundaryLastMonthFebruary() throws Exception {
910 // assume cycle day of "30th" in february, which should clamp
911 final long currentTime = parseTime("2007-03-14T00:00:00.000Z");
Jeff Sharkey53313d72017-07-13 16:47:32 -0600912 final long expectedCycle = parseTime("2007-02-28T23:59:59.999Z");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700913
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700914 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800915 sTemplateWifi, 30, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700916 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700917 assertTimeEquals(expectedCycle, actualCycle);
918 }
919
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700920 @Test
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800921 public void testCycleBoundaryLeapYear() throws Exception {
922 final NetworkPolicy policy = new NetworkPolicy(
923 sTemplateWifi, 29, TIMEZONE_UTC, 1024L, 1024L, false);
924
925 assertTimeEquals(parseTime("2012-01-29T00:00:00.000Z"),
926 computeNextCycleBoundary(parseTime("2012-01-14T00:00:00.000Z"), policy));
927 assertTimeEquals(parseTime("2012-02-29T00:00:00.000Z"),
928 computeNextCycleBoundary(parseTime("2012-02-14T00:00:00.000Z"), policy));
929 assertTimeEquals(parseTime("2012-02-29T00:00:00.000Z"),
930 computeLastCycleBoundary(parseTime("2012-03-14T00:00:00.000Z"), policy));
931 assertTimeEquals(parseTime("2012-03-29T00:00:00.000Z"),
932 computeNextCycleBoundary(parseTime("2012-03-14T00:00:00.000Z"), policy));
933
934 assertTimeEquals(parseTime("2007-01-29T00:00:00.000Z"),
935 computeNextCycleBoundary(parseTime("2007-01-14T00:00:00.000Z"), policy));
Jeff Sharkey53313d72017-07-13 16:47:32 -0600936 assertTimeEquals(parseTime("2007-02-28T23:59:59.999Z"),
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800937 computeNextCycleBoundary(parseTime("2007-02-14T00:00:00.000Z"), policy));
Jeff Sharkey53313d72017-07-13 16:47:32 -0600938 assertTimeEquals(parseTime("2007-02-28T23:59:59.999Z"),
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800939 computeLastCycleBoundary(parseTime("2007-03-14T00:00:00.000Z"), policy));
940 assertTimeEquals(parseTime("2007-03-29T00:00:00.000Z"),
941 computeNextCycleBoundary(parseTime("2007-03-14T00:00:00.000Z"), policy));
942 }
943
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700944 @Test
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800945 public void testNextCycleTimezoneAfterUtc() throws Exception {
946 // US/Central is UTC-6
947 final NetworkPolicy policy = new NetworkPolicy(
948 sTemplateWifi, 10, "US/Central", 1024L, 1024L, false);
949 assertTimeEquals(parseTime("2012-01-10T06:00:00.000Z"),
950 computeNextCycleBoundary(parseTime("2012-01-05T00:00:00.000Z"), policy));
951 }
952
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700953 @Test
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800954 public void testNextCycleTimezoneBeforeUtc() throws Exception {
955 // Israel is UTC+2
956 final NetworkPolicy policy = new NetworkPolicy(
957 sTemplateWifi, 10, "Israel", 1024L, 1024L, false);
958 assertTimeEquals(parseTime("2012-01-09T22:00:00.000Z"),
959 computeNextCycleBoundary(parseTime("2012-01-05T00:00:00.000Z"), policy));
960 }
961
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700962 @Test
Jeff Sharkey15399052013-01-15 14:15:53 -0800963 public void testCycleTodayJanuary() throws Exception {
964 final NetworkPolicy policy = new NetworkPolicy(
965 sTemplateWifi, 14, "US/Pacific", 1024L, 1024L, false);
966
967 assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
968 computeNextCycleBoundary(parseTime("2013-01-13T23:59:59.000-08:00"), policy));
969 assertTimeEquals(parseTime("2013-02-14T00:00:00.000-08:00"),
970 computeNextCycleBoundary(parseTime("2013-01-14T00:00:01.000-08:00"), policy));
971 assertTimeEquals(parseTime("2013-02-14T00:00:00.000-08:00"),
972 computeNextCycleBoundary(parseTime("2013-01-14T15:11:00.000-08:00"), policy));
973
974 assertTimeEquals(parseTime("2012-12-14T00:00:00.000-08:00"),
975 computeLastCycleBoundary(parseTime("2013-01-13T23:59:59.000-08:00"), policy));
976 assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
977 computeLastCycleBoundary(parseTime("2013-01-14T00:00:01.000-08:00"), policy));
978 assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
979 computeLastCycleBoundary(parseTime("2013-01-14T15:11:00.000-08:00"), policy));
980 }
981
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700982 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700983 public void testNetworkPolicyAppliedCycleLastMonth() throws Exception {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700984 NetworkState[] state = null;
985 NetworkStats stats = null;
986
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700987 final int CYCLE_DAY = 15;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600988 final long NOW = parseTime("2007-03-10T00:00Z");
989 final long CYCLE_START = parseTime("2007-02-15T00:00Z");
990 final long CYCLE_END = parseTime("2007-03-15T00:00Z");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700991
Jeff Sharkey53313d72017-07-13 16:47:32 -0600992 setCurrentTimeMillis(NOW);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700993
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700994 // first, pretend that wifi network comes online. no policy active,
995 // which means we shouldn't push limit to interface.
996 state = new NetworkState[] { buildWifi() };
Felipe Lemeef134662016-08-10 14:46:39 -0700997 when(mConnManager.getAllNetworkState()).thenReturn(state);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700998
Felipe Lemeef134662016-08-10 14:46:39 -0700999 mPolicyListener.expect().onMeteredIfacesChanged(any());
Erik Klinef851d6d2015-04-20 16:03:48 +09001000 mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION));
Felipe Lemeef134662016-08-10 14:46:39 -07001001 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(any());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001002
1003 // now change cycle to be on 15th, and test in early march, to verify we
1004 // pick cycle day in previous month.
Felipe Lemeef134662016-08-10 14:46:39 -07001005 when(mConnManager.getAllNetworkState()).thenReturn(state);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001006
1007 // pretend that 512 bytes total have happened
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001008 stats = new NetworkStats(getElapsedRealtime(), 1)
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001009 .addIfaceValues(TEST_IFACE, 256L, 2L, 256L, 2L);
Jeff Sharkey53313d72017-07-13 16:47:32 -06001010 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, CYCLE_START, CYCLE_END))
Felipe Lemeef134662016-08-10 14:46:39 -07001011 .thenReturn(stats.getTotalBytes());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001012
Felipe Lemeef134662016-08-10 14:46:39 -07001013 mPolicyListener.expect().onMeteredIfacesChanged(any());
Jeff Sharkey163e6442011-10-31 16:37:52 -07001014 setNetworkPolicies(new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001015 sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, 1 * MB_IN_BYTES, 2 * MB_IN_BYTES, false));
Felipe Lemeef134662016-08-10 14:46:39 -07001016 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
1017
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001018 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
1019 (2 * MB_IN_BYTES) - 512);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001020 }
1021
Felipe Leme9f27e7a2016-08-12 15:19:40 -07001022 @Test
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001023 public void testNotificationWarningLimitSnooze() throws Exception {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001024 // Create a place to store fake usage
1025 final NetworkStatsHistory history = new NetworkStatsHistory(TimeUnit.HOURS.toMillis(1));
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001026 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001027 when(mStatsService.getNetworkTotalBytes(any(), anyLong(), anyLong()))
1028 .thenAnswer(new Answer<Long>() {
1029 @Override
1030 public Long answer(InvocationOnMock invocation) throws Throwable {
1031 final NetworkStatsHistory.Entry entry = history.getValues(
1032 invocation.getArgument(1), invocation.getArgument(2), null);
1033 return entry.rxBytes + entry.txBytes;
1034 }
1035 });
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001036 when(mStatsService.getNetworkUidBytes(any(), anyLong(), anyLong()))
1037 .thenAnswer(new Answer<NetworkStats>() {
1038 @Override
1039 public NetworkStats answer(InvocationOnMock invocation) throws Throwable {
1040 return stats;
1041 }
1042 });
Jeff Sharkey2e471452018-01-19 18:02:47 +09001043
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001044 // Get active mobile network in place
1045 expectMobileDefaults();
1046 mService.updateNetworks();
1047
1048 // Define simple data plan
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001049 final SubscriptionPlan plan = buildMonthlyDataPlan(
1050 ZonedDateTime.parse("2015-11-01T00:00:00.00Z"), DataUnit.MEGABYTES.toBytes(1800));
Sudheer Shanka2d1ab902019-10-12 15:01:44 -07001051 setSubscriptionPlans(TEST_SUB_ID, new SubscriptionPlan[] { plan },
Jeff Sharkey2e471452018-01-19 18:02:47 +09001052 mServiceContext.getOpPackageName());
1053
Jeff Sharkey2e471452018-01-19 18:02:47 +09001054 // We're 20% through the month (6 days)
1055 final long start = parseTime("2015-11-01T00:00Z");
1056 final long end = parseTime("2015-11-07T00:00Z");
1057 setCurrentTimeMillis(end);
1058
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001059 // Normal usage means no notification
1060 {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001061 history.clear();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001062 history.recordData(start, end,
1063 new NetworkStats.Entry(DataUnit.MEGABYTES.toBytes(360), 0L, 0L, 0L, 0));
1064
1065 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1066 expectMobileDefaults();
1067
1068 mService.updateNetworks();
1069
1070 verify(mTelephonyManager, atLeastOnce()).setPolicyDataEnabled(true, TEST_SUB_ID);
1071 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
1072 DataUnit.MEGABYTES.toBytes(1800 - 360));
1073 verify(mNotifManager, never()).notifyAsUser(any(), anyInt(), any(), any());
1074 }
1075
1076 // Push over warning
1077 {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001078 history.clear();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001079 history.recordData(start, end,
1080 new NetworkStats.Entry(DataUnit.MEGABYTES.toBytes(1799), 0L, 0L, 0L, 0));
1081
1082 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1083 expectMobileDefaults();
1084
1085 mService.updateNetworks();
1086
1087 verify(mTelephonyManager, atLeastOnce()).setPolicyDataEnabled(true, TEST_SUB_ID);
1088 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
1089 DataUnit.MEGABYTES.toBytes(1800 - 1799));
1090 verify(mNotifManager, atLeastOnce()).notifyAsUser(any(), eq(TYPE_WARNING),
1091 isA(Notification.class), eq(UserHandle.ALL));
1092 }
1093
Ammar Aijazib0941aa2019-04-26 18:39:50 -07001094 // Push over warning, but with a config that isn't from an identified carrier
1095 {
1096 history.clear();
1097 history.recordData(start, end,
1098 new NetworkStats.Entry(DataUnit.MEGABYTES.toBytes(1799), 0L, 0L, 0L, 0));
1099
1100 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1101 expectMobileDefaults();
1102 expectDefaultCarrierConfig();
1103
1104 mService.updateNetworks();
1105
1106 verify(mTelephonyManager, atLeastOnce()).setPolicyDataEnabled(true, TEST_SUB_ID);
1107 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
1108 DataUnit.MEGABYTES.toBytes(1800 - 1799));
1109 // Since this isn't from the identified carrier, there should be no notifications
1110 verify(mNotifManager, never()).notifyAsUser(any(), anyInt(), any(), any());
1111 }
1112
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001113 // Push over limit
1114 {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001115 history.clear();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001116 history.recordData(start, end,
1117 new NetworkStats.Entry(DataUnit.MEGABYTES.toBytes(1810), 0L, 0L, 0L, 0));
1118
1119 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1120 expectMobileDefaults();
1121
1122 mService.updateNetworks();
1123
1124 verify(mTelephonyManager, atLeastOnce()).setPolicyDataEnabled(false, TEST_SUB_ID);
1125 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE, 1);
1126 verify(mNotifManager, atLeastOnce()).notifyAsUser(any(), eq(TYPE_LIMIT),
1127 isA(Notification.class), eq(UserHandle.ALL));
1128 }
1129
1130 // Snooze limit
1131 {
1132 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1133 expectMobileDefaults();
1134
1135 mService.snoozeLimit(NetworkTemplate.buildTemplateMobileAll(TEST_IMSI));
1136 mService.updateNetworks();
1137
1138 verify(mTelephonyManager, atLeastOnce()).setPolicyDataEnabled(true, TEST_SUB_ID);
1139 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
1140 Long.MAX_VALUE);
1141 verify(mNotifManager, atLeastOnce()).notifyAsUser(any(), eq(TYPE_LIMIT_SNOOZED),
1142 isA(Notification.class), eq(UserHandle.ALL));
1143 }
1144 }
1145
1146 @Test
1147 public void testNotificationRapid() throws Exception {
1148 // Create a place to store fake usage
1149 final NetworkStatsHistory history = new NetworkStatsHistory(TimeUnit.HOURS.toMillis(1));
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001150 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001151 when(mStatsService.getNetworkTotalBytes(any(), anyLong(), anyLong()))
1152 .thenAnswer(new Answer<Long>() {
1153 @Override
1154 public Long answer(InvocationOnMock invocation) throws Throwable {
1155 final NetworkStatsHistory.Entry entry = history.getValues(
1156 invocation.getArgument(1), invocation.getArgument(2), null);
1157 return entry.rxBytes + entry.txBytes;
1158 }
1159 });
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001160 when(mStatsService.getNetworkUidBytes(any(), anyLong(), anyLong()))
1161 .thenAnswer(new Answer<NetworkStats>() {
1162 @Override
1163 public NetworkStats answer(InvocationOnMock invocation) throws Throwable {
1164 return stats;
1165 }
1166 });
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001167
1168 // Get active mobile network in place
1169 expectMobileDefaults();
1170 mService.updateNetworks();
1171
1172 // Define simple data plan which gives us effectively 60MB/day
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001173 final SubscriptionPlan plan = buildMonthlyDataPlan(
1174 ZonedDateTime.parse("2015-11-01T00:00:00.00Z"), DataUnit.MEGABYTES.toBytes(1800));
Sudheer Shanka2d1ab902019-10-12 15:01:44 -07001175 setSubscriptionPlans(TEST_SUB_ID, new SubscriptionPlan[] { plan },
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001176 mServiceContext.getOpPackageName());
1177
1178 // We're 20% through the month (6 days)
1179 final long start = parseTime("2015-11-01T00:00Z");
1180 final long end = parseTime("2015-11-07T00:00Z");
1181 setCurrentTimeMillis(end);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001182
1183 // Using 20% data in 20% time is normal
Jeff Sharkey2e471452018-01-19 18:02:47 +09001184 {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001185 history.clear();
Jeff Sharkey2e471452018-01-19 18:02:47 +09001186 history.recordData(start, end,
1187 new NetworkStats.Entry(DataUnit.MEGABYTES.toBytes(360), 0L, 0L, 0L, 0));
1188
1189 reset(mNotifManager);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001190 mService.updateNetworks();
1191 verify(mNotifManager, never()).notifyAsUser(any(), anyInt(), any(), any());
Jeff Sharkey2e471452018-01-19 18:02:47 +09001192 }
1193
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001194 // Using 80% data in 20% time is alarming; but spread equally among
1195 // three UIDs means we get generic alert
Jeff Sharkey2e471452018-01-19 18:02:47 +09001196 {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001197 history.clear();
Jeff Sharkey2e471452018-01-19 18:02:47 +09001198 history.recordData(start, end,
1199 new NetworkStats.Entry(DataUnit.MEGABYTES.toBytes(1440), 0L, 0L, 0L, 0));
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001200 stats.clear();
1201 stats.addValues(IFACE_ALL, UID_A, SET_ALL, TAG_ALL,
1202 DataUnit.MEGABYTES.toBytes(480), 0, 0, 0, 0);
1203 stats.addValues(IFACE_ALL, UID_B, SET_ALL, TAG_ALL,
1204 DataUnit.MEGABYTES.toBytes(480), 0, 0, 0, 0);
1205 stats.addValues(IFACE_ALL, UID_C, SET_ALL, TAG_ALL,
1206 DataUnit.MEGABYTES.toBytes(480), 0, 0, 0, 0);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001207
1208 reset(mNotifManager);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001209 mService.updateNetworks();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001210
1211 final ArgumentCaptor<Notification> notif = ArgumentCaptor.forClass(Notification.class);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001212 verify(mNotifManager, atLeastOnce()).notifyAsUser(any(), eq(TYPE_RAPID),
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001213 notif.capture(), eq(UserHandle.ALL));
1214
1215 final String text = notif.getValue().extras.getCharSequence(Notification.EXTRA_TEXT)
1216 .toString();
1217 assertFalse(text.contains(PKG_NAME_A));
1218 assertFalse(text.contains(PKG_NAME_B));
1219 assertFalse(text.contains(PKG_NAME_C));
1220 }
1221
1222 // Using 80% data in 20% time is alarming; but mostly done by one UID
1223 // means we get specific alert
1224 {
1225 history.clear();
1226 history.recordData(start, end,
1227 new NetworkStats.Entry(DataUnit.MEGABYTES.toBytes(1440), 0L, 0L, 0L, 0));
1228 stats.clear();
1229 stats.addValues(IFACE_ALL, UID_A, SET_ALL, TAG_ALL,
1230 DataUnit.MEGABYTES.toBytes(960), 0, 0, 0, 0);
1231 stats.addValues(IFACE_ALL, UID_B, SET_ALL, TAG_ALL,
1232 DataUnit.MEGABYTES.toBytes(480), 0, 0, 0, 0);
1233
1234 reset(mNotifManager);
1235 mService.updateNetworks();
1236
1237 final ArgumentCaptor<Notification> notif = ArgumentCaptor.forClass(Notification.class);
1238 verify(mNotifManager, atLeastOnce()).notifyAsUser(any(), eq(TYPE_RAPID),
1239 notif.capture(), eq(UserHandle.ALL));
1240
1241 final String text = notif.getValue().extras.getCharSequence(Notification.EXTRA_TEXT)
1242 .toString();
1243 assertTrue(text.contains(PKG_NAME_A));
1244 assertFalse(text.contains(PKG_NAME_B));
1245 assertFalse(text.contains(PKG_NAME_C));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001246 }
1247 }
1248
1249 @Test
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001250 public void testMeteredNetworkWithoutLimit() throws Exception {
1251 NetworkState[] state = null;
1252 NetworkStats stats = null;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001253
1254 final long TIME_FEB_15 = 1171497600000L;
1255 final long TIME_MAR_10 = 1173484800000L;
1256 final int CYCLE_DAY = 15;
1257
1258 setCurrentTimeMillis(TIME_MAR_10);
1259
1260 // bring up wifi network with metered policy
1261 state = new NetworkState[] { buildWifi() };
1262 stats = new NetworkStats(getElapsedRealtime(), 1)
1263 .addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L);
1264
1265 {
Felipe Lemeef134662016-08-10 14:46:39 -07001266 when(mConnManager.getAllNetworkState()).thenReturn(state);
1267 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15,
1268 currentTimeMillis())).thenReturn(stats.getTotalBytes());
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001269
Felipe Lemeef134662016-08-10 14:46:39 -07001270 mPolicyListener.expect().onMeteredIfacesChanged(any());
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001271 setNetworkPolicies(new NetworkPolicy(
1272 sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, WARNING_DISABLED, LIMIT_DISABLED,
1273 true));
Felipe Lemeef134662016-08-10 14:46:39 -07001274 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
1275
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001276 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
1277 Long.MAX_VALUE);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001278 }
1279 }
1280
Sudheer Shankae7361852017-03-07 11:51:46 -08001281 @Test
1282 public void testOnUidStateChanged_notifyAMS() throws Exception {
1283 final long procStateSeq = 222;
Sudheer Shankaed25ce62017-03-29 20:46:30 -07001284 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE, procStateSeq);
Sudheer Shankae7361852017-03-07 11:51:46 -08001285 verify(mActivityManagerInternal).notifyNetworkPolicyRulesUpdated(UID_A, procStateSeq);
Sudheer Shankae7361852017-03-07 11:51:46 -08001286 }
1287
Sudheer Shankaed25ce62017-03-29 20:46:30 -07001288 private void callOnUidStateChanged(int uid, int procState, long procStateSeq)
1289 throws Exception {
1290 mUidObserver.onUidStateChanged(uid, procState, procStateSeq);
1291 final CountDownLatch latch = new CountDownLatch(1);
1292 mService.mUidEventHandler.post(() -> {
1293 latch.countDown();
1294 });
1295 latch.await(2, TimeUnit.SECONDS);
1296 }
1297
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001298 private void assertCycleDayAsExpected(PersistableBundle config, int carrierCycleDay,
1299 boolean expectValid) {
1300 config.putInt(KEY_MONTHLY_DATA_CYCLE_DAY_INT, carrierCycleDay);
1301 int actualCycleDay = mService.getCycleDayFromCarrierConfig(config,
1302 INVALID_CARRIER_CONFIG_VALUE);
1303 if (expectValid) {
1304 assertEquals(carrierCycleDay, actualCycleDay);
1305 } else {
1306 // INVALID_CARRIER_CONFIG_VALUE is returned for invalid values
1307 assertEquals(INVALID_CARRIER_CONFIG_VALUE, actualCycleDay);
1308 }
1309 }
1310
1311 @Test
1312 public void testGetCycleDayFromCarrierConfig() {
1313 PersistableBundle config = CarrierConfigManager.getDefaultConfig();
1314 final Calendar cal = Calendar.getInstance();
1315 int actualCycleDay;
1316
1317 config.putInt(KEY_MONTHLY_DATA_CYCLE_DAY_INT, DATA_CYCLE_USE_PLATFORM_DEFAULT);
1318 actualCycleDay = mService.getCycleDayFromCarrierConfig(config, DEFAULT_CYCLE_DAY);
1319 assertEquals(DEFAULT_CYCLE_DAY, actualCycleDay);
1320
1321 // null config returns a default value
1322 actualCycleDay = mService.getCycleDayFromCarrierConfig(null, DEFAULT_CYCLE_DAY);
1323 assertEquals(DEFAULT_CYCLE_DAY, actualCycleDay);
1324
1325 // Sane, non-default values
1326 assertCycleDayAsExpected(config, 1, true);
1327 assertCycleDayAsExpected(config, cal.getMaximum(Calendar.DAY_OF_MONTH), true);
1328 assertCycleDayAsExpected(config, cal.getMinimum(Calendar.DAY_OF_MONTH), true);
1329
1330 // Invalid values
1331 assertCycleDayAsExpected(config, 0, false);
1332 assertCycleDayAsExpected(config, DATA_CYCLE_THRESHOLD_DISABLED, false);
1333 assertCycleDayAsExpected(config, cal.getMaximum(Calendar.DAY_OF_MONTH) + 1, false);
1334 assertCycleDayAsExpected(config, cal.getMinimum(Calendar.DAY_OF_MONTH) - 5, false);
1335 }
1336
1337 private void assertWarningBytesAsExpected(PersistableBundle config, long carrierWarningBytes,
1338 long expected) {
1339 config.putLong(KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, carrierWarningBytes);
1340 long actualWarning = mService.getWarningBytesFromCarrierConfig(config,
1341 INVALID_CARRIER_CONFIG_VALUE);
1342 assertEquals(expected, actualWarning);
1343 }
1344
1345 @Test
1346 public void testGetWarningBytesFromCarrierConfig() {
1347 PersistableBundle config = CarrierConfigManager.getDefaultConfig();
1348 long actualWarningBytes;
1349
1350 assertWarningBytesAsExpected(config, DATA_CYCLE_USE_PLATFORM_DEFAULT,
1351 mDefaultWarningBytes);
1352 assertWarningBytesAsExpected(config, DATA_CYCLE_THRESHOLD_DISABLED, WARNING_DISABLED);
1353 assertWarningBytesAsExpected(config, 0, 0);
1354 // not a valid value
1355 assertWarningBytesAsExpected(config, -1000, INVALID_CARRIER_CONFIG_VALUE);
1356
1357 // null config returns a default value
1358 actualWarningBytes = mService.getWarningBytesFromCarrierConfig(null, mDefaultWarningBytes);
1359 assertEquals(mDefaultWarningBytes, actualWarningBytes);
1360 }
1361
1362 private void assertLimitBytesAsExpected(PersistableBundle config, long carrierWarningBytes,
1363 long expected) {
1364 config.putLong(KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG, carrierWarningBytes);
1365 long actualWarning = mService.getLimitBytesFromCarrierConfig(config,
1366 INVALID_CARRIER_CONFIG_VALUE);
1367 assertEquals(expected, actualWarning);
1368 }
1369
1370 @Test
1371 public void testGetLimitBytesFromCarrierConfig() {
1372 PersistableBundle config = CarrierConfigManager.getDefaultConfig();
1373 long actualLimitBytes;
1374
1375 assertLimitBytesAsExpected(config, DATA_CYCLE_USE_PLATFORM_DEFAULT,
1376 mDefaultLimitBytes);
1377 assertLimitBytesAsExpected(config, DATA_CYCLE_THRESHOLD_DISABLED, LIMIT_DISABLED);
1378 assertLimitBytesAsExpected(config, 0, 0);
1379 // not a valid value
1380 assertLimitBytesAsExpected(config, -1000, INVALID_CARRIER_CONFIG_VALUE);
1381
1382 // null config returns a default value
1383 actualLimitBytes = mService.getWarningBytesFromCarrierConfig(null, mDefaultLimitBytes);
1384 assertEquals(mDefaultLimitBytes, actualLimitBytes);
1385 }
1386
1387 private PersistableBundle setupUpdateMobilePolicyCycleTests() throws RemoteException {
1388 when(mConnManager.getAllNetworkState()).thenReturn(new NetworkState[0]);
1389 when(mSubscriptionManager.getActiveSubscriptionIdList()).thenReturn(new int[]{FAKE_SUB_ID});
1390 when(mTelephonyManager.getSubscriberId(FAKE_SUB_ID)).thenReturn(FAKE_SUBSCRIBER_ID);
Sudheer Shanka2d1ab902019-10-12 15:01:44 -07001391 when(mTelephonyManager.createForSubscriptionId(FAKE_SUB_ID))
1392 .thenReturn(mock(TelephonyManager.class));
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001393 PersistableBundle bundle = CarrierConfigManager.getDefaultConfig();
1394 when(mCarrierConfigManager.getConfigForSubId(FAKE_SUB_ID)).thenReturn(bundle);
1395 setNetworkPolicies(buildDefaultFakeMobilePolicy());
1396 return bundle;
1397 }
1398
1399 @Test
1400 public void testUpdateMobilePolicyCycleWithNullConfig() throws RemoteException {
1401 when(mConnManager.getAllNetworkState()).thenReturn(new NetworkState[0]);
1402 when(mSubscriptionManager.getActiveSubscriptionIdList()).thenReturn(new int[]{FAKE_SUB_ID});
1403 when(mTelephonyManager.getSubscriberId(FAKE_SUB_ID)).thenReturn(FAKE_SUBSCRIBER_ID);
Sudheer Shanka2d1ab902019-10-12 15:01:44 -07001404 when(mTelephonyManager.createForSubscriptionId(FAKE_SUB_ID))
1405 .thenReturn(mock(TelephonyManager.class));
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001406 when(mCarrierConfigManager.getConfigForSubId(FAKE_SUB_ID)).thenReturn(null);
1407 setNetworkPolicies(buildDefaultFakeMobilePolicy());
1408 // smoke test to make sure no errors are raised
1409 mServiceContext.sendBroadcast(
1410 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1411 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1412 );
1413 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1414 true);
1415 }
1416
1417 @Test
1418 public void testUpdateMobilePolicyCycleWithInvalidConfig() throws RemoteException {
1419 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1420 // Test with an invalid CarrierConfig, there should be no changes or crashes.
1421 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, -100);
1422 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, -100);
1423 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG, -100);
1424 mServiceContext.sendBroadcast(
1425 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1426 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1427 );
1428
1429 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1430 true);
1431 }
1432
1433 @Test
1434 public void testUpdateMobilePolicyCycleWithDefaultConfig() throws RemoteException {
1435 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1436 // Test that we respect the platform values when told to
1437 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT,
1438 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1439 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1440 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1441 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1442 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1443 mServiceContext.sendBroadcast(
1444 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1445 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1446 );
1447
1448 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1449 true);
1450 }
1451
1452 @Test
1453 public void testUpdateMobilePolicyCycleWithUserOverrides() throws RemoteException {
1454 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1455
1456 // inferred = false implies that a user manually modified this policy.
1457 NetworkPolicy policy = buildDefaultFakeMobilePolicy();
1458 policy.inferred = false;
1459 setNetworkPolicies(policy);
1460
1461 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1462 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, 9999);
1463 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1464 DATA_CYCLE_THRESHOLD_DISABLED);
1465 mServiceContext.sendBroadcast(
1466 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1467 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1468 );
1469
1470 // The policy still shouldn't change, because we don't want to overwrite user settings.
1471 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1472 false);
1473 }
1474
1475 @Test
1476 public void testUpdateMobilePolicyCycleUpdatesDataCycle() throws RemoteException {
1477 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1478
1479 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1480 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, 9999);
1481 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG, 9999);
1482 mServiceContext.sendBroadcast(
1483 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1484 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1485 );
1486
1487 assertNetworkPolicyEquals(31, 9999, 9999, true);
1488 }
1489
1490 @Test
1491 public void testUpdateMobilePolicyCycleDisableThresholds() throws RemoteException {
1492 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1493
1494 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1495 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1496 DATA_CYCLE_THRESHOLD_DISABLED);
1497 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1498 DATA_CYCLE_THRESHOLD_DISABLED);
1499 mServiceContext.sendBroadcast(
1500 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1501 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1502 );
1503
1504 assertNetworkPolicyEquals(31, WARNING_DISABLED, LIMIT_DISABLED, true);
1505 }
1506
1507 @Test
1508 public void testUpdateMobilePolicyCycleRevertsToDefault() throws RemoteException {
1509 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1510
1511 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1512 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1513 DATA_CYCLE_THRESHOLD_DISABLED);
1514 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1515 DATA_CYCLE_THRESHOLD_DISABLED);
1516 mServiceContext.sendBroadcast(
1517 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1518 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1519 );
1520 assertNetworkPolicyEquals(31, WARNING_DISABLED, LIMIT_DISABLED, true);
1521
1522 // If the user switches carriers to one that doesn't use a CarrierConfig, we should revert
1523 // to the default data limit and warning. The cycle date doesn't need to revert as it's
1524 // arbitrary anyways.
1525 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT,
1526 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1527 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1528 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1529 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1530 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1531 mServiceContext.sendBroadcast(
1532 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1533 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1534 );
1535
1536 assertNetworkPolicyEquals(31, mDefaultWarningBytes, mDefaultLimitBytes,
1537 true);
1538 }
1539
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001540 @Test
1541 public void testOpportunisticQuota() throws Exception {
1542 final Network net = new Network(TEST_NET_ID);
1543 final NetworkPolicyManagerInternal internal = LocalServices
1544 .getService(NetworkPolicyManagerInternal.class);
1545
1546 // Create a place to store fake usage
1547 final NetworkStatsHistory history = new NetworkStatsHistory(TimeUnit.HOURS.toMillis(1));
1548 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 0);
1549 when(mStatsService.getNetworkTotalBytes(any(), anyLong(), anyLong()))
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001550 .thenAnswer(invocation -> {
1551 final NetworkStatsHistory.Entry entry = history.getValues(
1552 invocation.getArgument(1), invocation.getArgument(2), null);
1553 return entry.rxBytes + entry.txBytes;
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001554 });
1555 when(mStatsService.getNetworkUidBytes(any(), anyLong(), anyLong()))
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001556 .thenReturn(stats);
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001557
1558 // Get active mobile network in place
1559 expectMobileDefaults();
1560 mService.updateNetworks();
1561
1562 // We're 20% through the month (6 days)
1563 final long start = parseTime("2015-11-01T00:00Z");
1564 final long end = parseTime("2015-11-07T00:00Z");
1565 setCurrentTimeMillis(end);
1566
1567 // Get some data usage in place
1568 history.clear();
1569 history.recordData(start, end,
1570 new NetworkStats.Entry(DataUnit.MEGABYTES.toBytes(360), 0L, 0L, 0L, 0));
1571
1572 // No data plan
1573 {
1574 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1575 expectMobileDefaults();
1576
1577 mService.updateNetworks();
1578
1579 // No quotas
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001580 assertEquals(OPPORTUNISTIC_QUOTA_UNKNOWN,
1581 internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_JOBS));
1582 assertEquals(OPPORTUNISTIC_QUOTA_UNKNOWN,
1583 internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_MULTIPATH));
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001584 }
1585
1586 // Limited data plan
1587 {
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001588 final SubscriptionPlan plan = buildMonthlyDataPlan(
1589 ZonedDateTime.parse("2015-11-01T00:00:00.00Z"),
1590 DataUnit.MEGABYTES.toBytes(1800));
Sudheer Shanka2d1ab902019-10-12 15:01:44 -07001591 setSubscriptionPlans(TEST_SUB_ID, new SubscriptionPlan[]{plan},
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001592 mServiceContext.getOpPackageName());
1593
1594 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1595 expectMobileDefaults();
1596
1597 mService.updateNetworks();
1598
1599 // We have 1440MB and 24 days left, which is 60MB/day; assuming 10%
1600 // for quota split equally between two types gives 3MB.
1601 assertEquals(DataUnit.MEGABYTES.toBytes(3),
1602 internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_JOBS));
1603 assertEquals(DataUnit.MEGABYTES.toBytes(3),
1604 internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_MULTIPATH));
1605 }
1606
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001607 // Limited data plan, over quota
1608 {
1609 final SubscriptionPlan plan = buildMonthlyDataPlan(
1610 ZonedDateTime.parse("2015-11-01T00:00:00.00Z"),
1611 DataUnit.MEGABYTES.toBytes(100));
Sudheer Shanka2d1ab902019-10-12 15:01:44 -07001612 setSubscriptionPlans(TEST_SUB_ID, new SubscriptionPlan[]{plan},
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001613 mServiceContext.getOpPackageName());
1614
1615 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1616 expectMobileDefaults();
1617
1618 mService.updateNetworks();
1619
1620 assertEquals(0L, internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_JOBS));
1621 assertEquals(0L, internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_MULTIPATH));
1622 }
1623
1624 // Roaming
1625 {
1626 final SubscriptionPlan plan = buildMonthlyDataPlan(
1627 ZonedDateTime.parse("2015-11-01T00:00:00.00Z"), BYTES_UNLIMITED);
Sudheer Shanka2d1ab902019-10-12 15:01:44 -07001628 setSubscriptionPlans(TEST_SUB_ID, new SubscriptionPlan[]{plan},
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001629 mServiceContext.getOpPackageName());
1630
1631 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1632 expectMobileDefaults();
1633 expectNetworkState(true /* roaming */);
1634
1635 mService.updateNetworks();
1636
1637 assertEquals(0L, internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_JOBS));
1638 assertEquals(0L, internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_MULTIPATH));
1639 }
1640
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001641 // Unlimited data plan
1642 {
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001643 final SubscriptionPlan plan = buildMonthlyDataPlan(
1644 ZonedDateTime.parse("2015-11-01T00:00:00.00Z"), BYTES_UNLIMITED);
Sudheer Shanka2d1ab902019-10-12 15:01:44 -07001645 setSubscriptionPlans(TEST_SUB_ID, new SubscriptionPlan[]{plan},
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001646 mServiceContext.getOpPackageName());
1647
1648 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1649 expectMobileDefaults();
1650
1651 mService.updateNetworks();
1652
1653 // 20MB/day, split equally between two types gives 10MB.
1654 assertEquals(DataUnit.MEBIBYTES.toBytes(10),
1655 internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_JOBS));
1656 assertEquals(DataUnit.MEBIBYTES.toBytes(10),
1657 internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_MULTIPATH));
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001658
1659 // Capabilities change to roaming
1660 final ConnectivityManager.NetworkCallback callback = mNetworkCallbackCaptor.getValue();
1661 assertNotNull(callback);
1662 expectNetworkState(true /* roaming */);
1663 callback.onCapabilitiesChanged(
1664 new Network(TEST_NET_ID),
1665 buildNetworkCapabilities(TEST_SUB_ID, true /* roaming */));
1666
1667 assertEquals(0, internal.getSubscriptionOpportunisticQuota(
1668 new Network(TEST_NET_ID), NetworkPolicyManagerInternal.QUOTA_TYPE_MULTIPATH));
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001669 }
1670 }
1671
Annie Meng20b4d842018-05-18 15:00:49 +01001672 /**
1673 * Test that policy set of {null, NetworkPolicy, null} does not crash and restores the valid
1674 * NetworkPolicy.
1675 */
1676 @Test
1677 public void testSetNetworkPolicies_withNullPolicies_doesNotThrow() {
1678 NetworkPolicy[] policies = new NetworkPolicy[3];
1679 policies[1] = buildDefaultFakeMobilePolicy();
1680 setNetworkPolicies(policies);
1681
1682 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1683 true);
1684 }
1685
Mike Yuf9729752018-08-17 15:22:05 +08001686 /**
1687 * Exhaustively test isUidNetworkingBlocked to output the expected results based on external
1688 * conditions.
1689 */
1690 @Test
1691 public void testIsUidNetworkingBlocked() {
1692 final ArrayList<Pair<Boolean, Integer>> expectedBlockedStates = new ArrayList<>();
1693
1694 // Metered network. Data saver on.
1695 expectedBlockedStates.add(new Pair<>(true, RULE_NONE));
1696 expectedBlockedStates.add(new Pair<>(false, RULE_ALLOW_METERED));
1697 expectedBlockedStates.add(new Pair<>(false, RULE_TEMPORARY_ALLOW_METERED));
1698 expectedBlockedStates.add(new Pair<>(true, RULE_REJECT_METERED));
1699 expectedBlockedStates.add(new Pair<>(true, RULE_ALLOW_ALL));
1700 expectedBlockedStates.add(new Pair<>(true, RULE_REJECT_ALL));
1701 verifyNetworkBlockedState(
1702 true /* metered */, true /* backgroundRestricted */, expectedBlockedStates);
1703 expectedBlockedStates.clear();
1704
1705 // Metered network. Data saver off.
1706 expectedBlockedStates.add(new Pair<>(false, RULE_NONE));
1707 expectedBlockedStates.add(new Pair<>(false, RULE_ALLOW_METERED));
1708 expectedBlockedStates.add(new Pair<>(false, RULE_TEMPORARY_ALLOW_METERED));
1709 expectedBlockedStates.add(new Pair<>(true, RULE_REJECT_METERED));
1710 expectedBlockedStates.add(new Pair<>(false, RULE_ALLOW_ALL));
1711 expectedBlockedStates.add(new Pair<>(true, RULE_REJECT_ALL));
1712 verifyNetworkBlockedState(
1713 true /* metered */, false /* backgroundRestricted */, expectedBlockedStates);
1714 expectedBlockedStates.clear();
1715
1716 // Non-metered network. Data saver on.
1717 expectedBlockedStates.add(new Pair<>(false, RULE_NONE));
1718 expectedBlockedStates.add(new Pair<>(false, RULE_ALLOW_METERED));
1719 expectedBlockedStates.add(new Pair<>(false, RULE_TEMPORARY_ALLOW_METERED));
1720 expectedBlockedStates.add(new Pair<>(false, RULE_REJECT_METERED));
1721 expectedBlockedStates.add(new Pair<>(false, RULE_ALLOW_ALL));
1722 expectedBlockedStates.add(new Pair<>(true, RULE_REJECT_ALL));
1723 verifyNetworkBlockedState(
1724 false /* metered */, true /* backgroundRestricted */, expectedBlockedStates);
1725
1726 // Non-metered network. Data saver off. The result is the same as previous case since
1727 // the network is blocked only for RULE_REJECT_ALL regardless of data saver.
1728 verifyNetworkBlockedState(
1729 false /* metered */, false /* backgroundRestricted */, expectedBlockedStates);
1730 expectedBlockedStates.clear();
1731 }
1732
1733 private void verifyNetworkBlockedState(boolean metered, boolean backgroundRestricted,
1734 ArrayList<Pair<Boolean, Integer>> expectedBlockedStateForRules) {
1735 final NetworkPolicyManagerInternal npmi = LocalServices
1736 .getService(NetworkPolicyManagerInternal.class);
1737
1738 for (Pair<Boolean, Integer> pair : expectedBlockedStateForRules) {
1739 final boolean expectedResult = pair.first;
1740 final int rule = pair.second;
1741 assertEquals(formatBlockedStateError(UID_A, rule, metered, backgroundRestricted),
1742 expectedResult,
1743 npmi.isUidNetworkingBlocked(UID_A, rule, metered, backgroundRestricted));
1744 assertFalse(formatBlockedStateError(SYSTEM_UID, rule, metered, backgroundRestricted),
1745 npmi.isUidNetworkingBlocked(SYSTEM_UID, rule, metered, backgroundRestricted));
1746 }
1747 }
1748
1749 private String formatBlockedStateError(int uid, int rule, boolean metered,
1750 boolean backgroundRestricted) {
1751 return String.format(
1752 "Unexpected BlockedState: (uid=%d, rule=%s, metered=%b, backgroundRestricted=%b)",
1753 uid, uidRulesToString(rule), metered, backgroundRestricted);
1754 }
1755
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001756 private SubscriptionPlan buildMonthlyDataPlan(ZonedDateTime start, long limitBytes) {
1757 return SubscriptionPlan.Builder
1758 .createRecurringMonthly(start)
1759 .setDataLimit(limitBytes, LIMIT_BEHAVIOR_DISABLED)
1760 .build();
1761 }
1762
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001763 private ApplicationInfo buildApplicationInfo(String label) {
1764 final ApplicationInfo ai = new ApplicationInfo();
1765 ai.nonLocalizedLabel = label;
1766 return ai;
1767 }
1768
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001769 private NetworkInfo buildNetworkInfo() {
1770 final NetworkInfo ni = new NetworkInfo(ConnectivityManager.TYPE_MOBILE,
1771 TelephonyManager.NETWORK_TYPE_LTE, null, null);
1772 ni.setDetailedState(NetworkInfo.DetailedState.CONNECTED, null, null);
1773 return ni;
1774 }
1775
1776 private LinkProperties buildLinkProperties(String iface) {
1777 final LinkProperties lp = new LinkProperties();
1778 lp.setInterfaceName(iface);
1779 return lp;
1780 }
1781
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001782 private NetworkCapabilities buildNetworkCapabilities(int subId, boolean roaming) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001783 final NetworkCapabilities nc = new NetworkCapabilities();
1784 nc.addTransportType(TRANSPORT_CELLULAR);
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001785 if (!roaming) {
1786 nc.addCapability(NET_CAPABILITY_NOT_ROAMING);
1787 }
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001788 nc.setNetworkSpecifier(new StringNetworkSpecifier(String.valueOf(subId)));
1789 return nc;
1790 }
1791
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001792 private NetworkPolicy buildDefaultFakeMobilePolicy() {
1793 NetworkPolicy p = mService.buildDefaultMobilePolicy(FAKE_SUB_ID, FAKE_SUBSCRIBER_ID);
1794 // set a deterministic cycle date
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001795 p.cycleRule = new RecurrenceRule(
1796 p.cycleRule.start.withDayOfMonth(DEFAULT_CYCLE_DAY),
1797 p.cycleRule.end, Period.ofMonths(1));
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001798 return p;
1799 }
1800
1801 private static NetworkPolicy buildFakeMobilePolicy(int cycleDay, long warningBytes,
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001802 long limitBytes, boolean inferred) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001803 final NetworkTemplate template = buildTemplateMobileAll(FAKE_SUBSCRIBER_ID);
Neil Fullerd5f0a392019-06-17 19:59:51 +01001804 return new NetworkPolicy(template, cycleDay, TimeZone.getDefault().getID(), warningBytes,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001805 limitBytes, SNOOZE_NEVER, SNOOZE_NEVER, true, inferred);
1806 }
1807
1808 private void assertNetworkPolicyEquals(int expectedCycleDay, long expectedWarningBytes,
1809 long expectedLimitBytes, boolean expectedInferred) {
1810 NetworkPolicy[] policies = mService.getNetworkPolicies(
1811 mServiceContext.getOpPackageName());
1812 assertEquals("Unexpected number of network policies", 1, policies.length);
1813 NetworkPolicy actualPolicy = policies[0];
1814 NetworkPolicy expectedPolicy = buildFakeMobilePolicy(expectedCycleDay, expectedWarningBytes,
1815 expectedLimitBytes, expectedInferred);
1816 assertEquals(expectedPolicy, actualPolicy);
1817 }
1818
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001819 private static long parseTime(String time) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06001820 return ZonedDateTime.parse(time).toInstant().toEpochMilli();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001821 }
1822
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07001823 private void setNetworkPolicies(NetworkPolicy... policies) {
1824 mService.setNetworkPolicies(policies);
1825 }
1826
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001827 private static NetworkState buildWifi() {
1828 final NetworkInfo info = new NetworkInfo(TYPE_WIFI, 0, null, null);
1829 info.setDetailedState(DetailedState.CONNECTED, null, null);
1830 final LinkProperties prop = new LinkProperties();
1831 prop.setInterfaceName(TEST_IFACE);
Stephen Chena1c92b72017-02-06 13:18:11 -08001832 final NetworkCapabilities networkCapabilities = new NetworkCapabilities();
1833 return new NetworkState(info, prop, networkCapabilities, null, null, TEST_SSID);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001834 }
1835
Felipe Leme3d3308d2016-08-23 17:41:47 -07001836 private void expectHasInternetPermission(int uid, boolean hasIt) throws Exception {
1837 when(mIpm.checkUidPermission(Manifest.permission.INTERNET, uid)).thenReturn(
1838 hasIt ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED);
1839 }
1840
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001841 private void expectNetworkState(boolean roaming) throws Exception {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001842 when(mCarrierConfigManager.getConfigForSubId(eq(TEST_SUB_ID)))
Ammar Aijazib0941aa2019-04-26 18:39:50 -07001843 .thenReturn(mCarrierConfig);
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001844 when(mConnManager.getAllNetworkState()).thenReturn(new NetworkState[] {
1845 new NetworkState(buildNetworkInfo(),
1846 buildLinkProperties(TEST_IFACE),
1847 buildNetworkCapabilities(TEST_SUB_ID, roaming),
1848 new Network(TEST_NET_ID), TEST_IMSI, null)
1849 });
1850 }
1851
Ammar Aijazib0941aa2019-04-26 18:39:50 -07001852 private void expectDefaultCarrierConfig() throws Exception {
1853 when(mCarrierConfigManager.getConfigForSubId(eq(TEST_SUB_ID)))
1854 .thenReturn(CarrierConfigManager.getDefaultConfig());
1855 }
1856
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001857 private void expectMobileDefaults() throws Exception {
1858 when(mSubscriptionManager.getActiveSubscriptionIdList()).thenReturn(
1859 new int[] { TEST_SUB_ID });
1860 when(mTelephonyManager.getSubscriberId(TEST_SUB_ID)).thenReturn(TEST_IMSI);
Sudheer Shanka2d1ab902019-10-12 15:01:44 -07001861 when(mTelephonyManager.createForSubscriptionId(TEST_SUB_ID))
1862 .thenReturn(mock(TelephonyManager.class));
Ammar Aijazib0941aa2019-04-26 18:39:50 -07001863 doNothing().when(mTelephonyManager).setPolicyDataEnabled(anyBoolean(), anyInt());
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001864 expectNetworkState(false /* roaming */);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001865 }
1866
Felipe Lemeef134662016-08-10 14:46:39 -07001867 private void verifyAdvisePersistThreshold() throws Exception {
1868 verify(mStatsService).advisePersistThreshold(anyLong());
Jeff Sharkey0cf6de02012-05-04 15:03:30 -07001869 }
1870
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001871 private static class TestAbstractFuture<T> extends AbstractFuture<T> {
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001872 @Override
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001873 public T get() throws InterruptedException, ExecutionException {
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001874 try {
1875 return get(5, TimeUnit.SECONDS);
1876 } catch (TimeoutException e) {
1877 throw new RuntimeException(e);
1878 }
1879 }
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001880 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001881
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -07001882 private static void assertTimeEquals(long expected, long actual) {
1883 if (expected != actual) {
1884 fail("expected " + formatTime(expected) + " but was actually " + formatTime(actual));
1885 }
1886 }
1887
1888 private static String formatTime(long millis) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06001889 return Instant.ofEpochMilli(millis) + " [" + millis + "]";
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -07001890 }
1891
1892 private static void assertEqualsFuzzy(long expected, long actual, long fuzzy) {
1893 final long low = expected - fuzzy;
1894 final long high = expected + fuzzy;
1895 if (actual < low || actual > high) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06001896 fail("value " + formatTime(actual) + " is outside [" + formatTime(low) + ","
1897 + formatTime(high) + "]");
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -07001898 }
1899 }
1900
1901 private static void assertUnique(LinkedHashSet<Long> seen, Long value) {
1902 if (!seen.add(value)) {
1903 fail("found duplicate time " + value + " in series " + seen.toString());
1904 }
1905 }
1906
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001907 private static void assertNotificationType(int expected, String actualTag) {
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001908 assertEquals("notification type mismatch for '" + actualTag + "'",
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001909 Integer.toString(expected), actualTag.substring(actualTag.lastIndexOf(':') + 1));
1910 }
1911
Felipe Lemee88729d2016-08-17 16:43:01 -07001912 private void assertUidPolicy(int uid, int expected) {
1913 final int actual = mService.getUidPolicy(uid);
1914 if (expected != actual) {
1915 fail("Wrong policy for UID " + uid + ": expected " + uidPoliciesToString(expected)
1916 + ", actual " + uidPoliciesToString(actual));
1917 }
1918 }
1919
Felipe Leme46b451f2016-08-19 08:46:17 -07001920 private void assertWhitelistUids(int... uids) {
Felipe Leme57e3d312016-08-23 14:42:52 -07001921 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_ALLOW_METERED_BACKGROUND), uids);
Felipe Leme46b451f2016-08-19 08:46:17 -07001922 }
1923
Felipe Leme3d3308d2016-08-23 17:41:47 -07001924 private void assertRestrictBackgroundOn() throws Exception {
1925 assertTrue("restrictBackground should be set", mService.getRestrictBackground());
1926 }
1927
1928 private void assertRestrictBackgroundOff() throws Exception {
1929 assertFalse("restrictBackground should not be set", mService.getRestrictBackground());
1930 }
1931
1932 private FutureIntent newRestrictBackgroundChangedFuture() {
1933 return mServiceContext
1934 .nextBroadcastIntent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
1935 }
1936
1937 private void assertRestrictBackgroundChangedReceived(Future<Intent> future,
1938 String expectedPackage) throws Exception {
1939 final String action = ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED;
1940 final Intent intent = future.get(5, TimeUnit.SECONDS);
1941 assertNotNull("Didn't get a " + action + "intent in 5 seconds");
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001942 assertEquals("Wrong package on " + action + " intent",
1943 expectedPackage, intent.getPackage());
Felipe Leme3d3308d2016-08-23 17:41:47 -07001944 }
1945
Felipe Lemee88729d2016-08-17 16:43:01 -07001946 // TODO: replace by Truth, Hamcrest, or a similar tool.
1947 private void assertContainsInAnyOrder(int[] actual, int...expected) {
1948 final StringBuilder errors = new StringBuilder();
1949 if (actual.length != expected.length) {
1950 errors.append("\tsize does not match\n");
1951 }
1952 final List<Integer> actualList =
1953 Arrays.stream(actual).boxed().collect(Collectors.<Integer>toList());
1954 final List<Integer> expectedList =
1955 Arrays.stream(expected).boxed().collect(Collectors.<Integer>toList());
1956 if (!actualList.containsAll(expectedList)) {
1957 errors.append("\tmissing elements on actual list\n");
1958 }
1959 if (!expectedList.containsAll(actualList)) {
1960 errors.append("\tmissing elements on expected list\n");
1961 }
1962 if (errors.length() > 0) {
1963 fail("assertContainsInAnyOrder(expected=" + Arrays.toString(expected)
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001964 + ", actual=" + Arrays.toString(actual) + ") failed: \n" + errors);
Felipe Lemee88729d2016-08-17 16:43:01 -07001965 }
1966 }
1967
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001968 private long getElapsedRealtime() {
1969 return mElapsedRealtime;
1970 }
1971
1972 private void setCurrentTimeMillis(long currentTimeMillis) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001973 RecurrenceRule.sClock = Clock.fixed(Instant.ofEpochMilli(currentTimeMillis),
1974 ZoneId.systemDefault());
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001975 mStartTime = currentTimeMillis;
1976 mElapsedRealtime = 0L;
1977 }
1978
1979 private long currentTimeMillis() {
1980 return mStartTime + mElapsedRealtime;
1981 }
1982
1983 private void incrementCurrentTime(long duration) {
1984 mElapsedRealtime += duration;
1985 }
1986
Felipe Leme3d3308d2016-08-23 17:41:47 -07001987 private FutureIntent mRestrictBackgroundChanged;
1988
Sudheer Shanka2d1ab902019-10-12 15:01:44 -07001989 private void postMsgAndWaitForCompletion() throws InterruptedException {
1990 final Handler handler = mService.getHandlerForTesting();
1991 final CountDownLatch latch = new CountDownLatch(1);
1992 mService.getHandlerForTesting().post(latch::countDown);
1993 if (!latch.await(5, TimeUnit.SECONDS)) {
1994 fail("Timed out waiting for the test msg to be handled");
1995 }
1996 }
1997
1998 private void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage)
1999 throws InterruptedException {
2000 mService.setSubscriptionPlans(subId, plans, callingPackage);
2001 // setSubscriptionPlans() triggers async events, wait for those to be completed before
2002 // moving forward as they could interfere with the tests later.
2003 postMsgAndWaitForCompletion();
2004 }
2005
Felipe Leme3d3308d2016-08-23 17:41:47 -07002006 private void setRestrictBackground(boolean flag) throws Exception {
Felipe Leme3d3308d2016-08-23 17:41:47 -07002007 mService.setRestrictBackground(flag);
2008 // Sanity check.
2009 assertEquals("restrictBackground not set", flag, mService.getRestrictBackground());
2010 }
2011
Felipe Lemeef134662016-08-10 14:46:39 -07002012 /**
2013 * Creates a mock and registers it to {@link LocalServices}.
2014 */
Felipe Leme9f27e7a2016-08-12 15:19:40 -07002015 private static <T> T addLocalServiceMock(Class<T> clazz) {
Felipe Lemeef134662016-08-10 14:46:39 -07002016 final T mock = mock(clazz);
Felipe Lemeef134662016-08-10 14:46:39 -07002017 LocalServices.addService(clazz, mock);
Felipe Lemeef134662016-08-10 14:46:39 -07002018 return mock;
2019 }
2020
2021 /**
Felipe Lemeef134662016-08-10 14:46:39 -07002022 * Custom Mockito answer used to verify async {@link INetworkPolicyListener} calls.
2023 *
2024 * <p>Typical usage:
2025 * <pre><code>
2026 * mPolicyListener.expect().someCallback(any());
2027 * // do something on objects under test
2028 * mPolicyListener.waitAndVerify().someCallback(eq(expectedValue));
2029 * </code></pre>
2030 */
2031 final class NetworkPolicyListenerAnswer implements Answer<Void> {
2032 private CountDownLatch latch;
2033 private final INetworkPolicyListener listener;
2034
2035 NetworkPolicyListenerAnswer(NetworkPolicyManagerService service) {
2036 this.listener = mock(INetworkPolicyListener.class);
2037 // RemoteCallbackList needs a binder to use as key
2038 when(listener.asBinder()).thenReturn(new Binder());
2039 service.registerListener(listener);
2040 }
2041
2042 @Override
2043 public Void answer(InvocationOnMock invocation) throws Throwable {
Sudheer Shanka8ab22992018-11-29 00:08:58 -08002044 Log.d(TAG, "counting down on answer: " + invocation);
Felipe Lemeef134662016-08-10 14:46:39 -07002045 latch.countDown();
2046 return null;
2047 }
2048
2049 INetworkPolicyListener expect() {
2050 assertNull("expect() called before waitAndVerify()", latch);
2051 latch = new CountDownLatch(1);
2052 return doAnswer(this).when(listener);
2053 }
2054
2055 INetworkPolicyListener waitAndVerify() {
2056 assertNotNull("waitAndVerify() called before expect()", latch);
2057 try {
2058 assertTrue("callback not called in 5 seconds", latch.await(5, TimeUnit.SECONDS));
2059 } catch (InterruptedException e) {
2060 fail("Thread interrupted before callback called");
2061 } finally {
2062 latch = null;
2063 }
2064 return verify(listener, atLeastOnce());
2065 }
Felipe Leme3d3308d2016-08-23 17:41:47 -07002066
2067 INetworkPolicyListener verifyNotCalled() {
2068 return verify(listener, never());
2069 }
2070
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002071 }
Felipe Lemee88729d2016-08-17 16:43:01 -07002072
2073 private void setNetpolicyXml(Context context) throws Exception {
2074 mPolicyDir = context.getFilesDir();
2075 if (mPolicyDir.exists()) {
2076 IoUtils.deleteContents(mPolicyDir);
2077 }
2078 if (!TextUtils.isEmpty(mNetpolicyXml)) {
2079 final String assetPath = NETPOLICY_DIR + "/" + mNetpolicyXml;
2080 final File netConfigFile = new File(mPolicyDir, "netpolicy.xml");
2081 Log.d(TAG, "Creating " + netConfigFile + " from asset " + assetPath);
Sudheer Shanka8ab22992018-11-29 00:08:58 -08002082 try (InputStream in = context.getResources().getAssets().open(assetPath);
2083 OutputStream out = new FileOutputStream(netConfigFile)) {
Felipe Lemee88729d2016-08-17 16:43:01 -07002084 Streams.copy(in, out);
2085 }
2086 }
2087 }
2088
2089 /**
2090 * Annotation used to define the relative path of the {@code netpolicy.xml} file.
2091 */
2092 @Retention(RetentionPolicy.RUNTIME)
2093 @Target(ElementType.METHOD)
2094 public @interface NetPolicyXml {
Sudheer Shanka8ab22992018-11-29 00:08:58 -08002095 String value() default "";
Felipe Lemee88729d2016-08-17 16:43:01 -07002096 }
2097
2098 /**
2099 * Rule used to set {@code mNetPolicyXml} according to the {@link NetPolicyXml} annotation.
2100 */
2101 public static class NetPolicyMethodRule implements MethodRule {
2102
2103 @Override
2104 public Statement apply(Statement base, FrameworkMethod method, Object target) {
2105 for (Annotation annotation : method.getAnnotations()) {
2106 if ((annotation instanceof NetPolicyXml)) {
2107 final String path = ((NetPolicyXml) annotation).value();
2108 if (!path.isEmpty()) {
2109 ((NetworkPolicyManagerServiceTest) target).mNetpolicyXml = path;
2110 break;
2111 }
2112 }
2113 }
2114 return base;
2115 }
2116 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002117}