blob: 40788299a6c62389dc79562a4b326ebc96674cdf [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
17package com.android.server;
18
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;
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -070021import static android.net.NetworkPolicy.LIMIT_DISABLED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070022import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -070023import static android.net.NetworkPolicy.WARNING_DISABLED;
Felipe Leme46b451f2016-08-19 08:46:17 -070024import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070025import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070026import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemee88729d2016-08-17 16:43:01 -070027import static android.net.NetworkPolicyManager.uidPoliciesToString;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070028import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080029import static android.net.TrafficStats.KB_IN_BYTES;
30import static android.net.TrafficStats.MB_IN_BYTES;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070031import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070032import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
Jeff Sharkey53313d72017-07-13 16:47:32 -060033import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070034import static android.telephony.CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG;
35import static android.telephony.CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG;
36import static android.telephony.CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070037import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Jeff Sharkey9bf31502012-03-09 17:07:21 -080038import static android.text.format.Time.TIMEZONE_UTC;
Felipe Lemeef134662016-08-10 14:46:39 -070039
Sudheer Shankae7361852017-03-07 11:51:46 -080040import static com.android.server.net.NetworkPolicyManagerService.MAX_PROC_STATE_SEQ_HISTORY;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070041import static com.android.server.net.NetworkPolicyManagerService.TYPE_LIMIT;
42import static com.android.server.net.NetworkPolicyManagerService.TYPE_LIMIT_SNOOZED;
43import static com.android.server.net.NetworkPolicyManagerService.TYPE_WARNING;
Jeff Sharkey53313d72017-07-13 16:47:32 -060044
jackqdyulei29c82ab2017-03-10 14:09:16 -080045import static com.google.common.truth.Truth.assertThat;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070046
Felipe Leme9f27e7a2016-08-12 15:19:40 -070047import static org.junit.Assert.assertEquals;
48import static org.junit.Assert.assertFalse;
49import static org.junit.Assert.assertNotNull;
50import static org.junit.Assert.assertNull;
51import static org.junit.Assert.assertTrue;
52import static org.junit.Assert.fail;
Jeff Sharkey53313d72017-07-13 16:47:32 -060053import static org.mockito.ArgumentMatchers.any;
Sudheer Shanka543339f2017-07-28 15:18:07 -070054import static org.mockito.ArgumentMatchers.anyBoolean;
Jeff Sharkey53313d72017-07-13 16:47:32 -060055import static org.mockito.ArgumentMatchers.anyInt;
56import static org.mockito.ArgumentMatchers.anyLong;
57import static org.mockito.ArgumentMatchers.anyString;
58import static org.mockito.ArgumentMatchers.eq;
59import static org.mockito.ArgumentMatchers.isA;
60import static org.mockito.ArgumentMatchers.isNull;
jackqdyulei29c82ab2017-03-10 14:09:16 -080061import static org.mockito.Mockito.atLeast;
Felipe Lemeef134662016-08-10 14:46:39 -070062import static org.mockito.Mockito.atLeastOnce;
63import static org.mockito.Mockito.doAnswer;
jackqdyulei29c82ab2017-03-10 14:09:16 -080064import static org.mockito.Mockito.doReturn;
Felipe Lemeef134662016-08-10 14:46:39 -070065import static org.mockito.Mockito.mock;
Felipe Leme3d3308d2016-08-23 17:41:47 -070066import static org.mockito.Mockito.never;
Felipe Lemeef134662016-08-10 14:46:39 -070067import static org.mockito.Mockito.verify;
68import static org.mockito.Mockito.when;
69
Felipe Leme3d3308d2016-08-23 17:41:47 -070070import android.Manifest;
Felipe Lemeef134662016-08-10 14:46:39 -070071import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -080072import android.app.ActivityManagerInternal;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070073import android.app.IActivityManager;
Jeff Sharkey2ef2aeb2011-06-15 11:01:31 -070074import android.app.INotificationManager;
Felipe Lemeef134662016-08-10 14:46:39 -070075import android.app.IUidObserver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070076import android.app.Notification;
Felipe Lemeef134662016-08-10 14:46:39 -070077import android.app.usage.UsageStatsManagerInternal;
78import android.content.Context;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070079import android.content.Intent;
Felipe Lemeef134662016-08-10 14:46:39 -070080import android.content.pm.ApplicationInfo;
Felipe Leme3d3308d2016-08-23 17:41:47 -070081import android.content.pm.IPackageManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070082import android.content.pm.PackageInfo;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070083import android.content.pm.PackageManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070084import android.content.pm.Signature;
Felipe Leme3d3308d2016-08-23 17:41:47 -070085import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070086import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070087import android.net.INetworkManagementEventObserver;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070088import android.net.INetworkPolicyListener;
Jeff Sharkey75279902011-05-24 18:39:45 -070089import android.net.INetworkStatsService;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070090import android.net.LinkProperties;
Stephen Chena1c92b72017-02-06 13:18:11 -080091import android.net.NetworkCapabilities;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070092import android.net.NetworkInfo;
93import android.net.NetworkInfo.DetailedState;
94import android.net.NetworkPolicy;
95import android.net.NetworkState;
96import android.net.NetworkStats;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070097import android.net.NetworkTemplate;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070098import android.os.Binder;
Ashish Sharma50fd36d2011-06-15 19:34:53 -070099import android.os.INetworkManagementService;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700100import android.os.PersistableBundle;
Felipe Lemeef134662016-08-10 14:46:39 -0700101import android.os.PowerManagerInternal;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800102import android.os.PowerSaveState;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700103import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700104import android.os.UserHandle;
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700105import android.support.test.InstrumentationRegistry;
Felipe Leme3d3308d2016-08-23 17:41:47 -0700106import android.support.test.filters.MediumTest;
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700107import android.support.test.runner.AndroidJUnit4;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700108import android.telephony.CarrierConfigManager;
109import android.telephony.SubscriptionManager;
110import android.telephony.TelephonyManager;
Felipe Lemee88729d2016-08-17 16:43:01 -0700111import android.text.TextUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700112import android.text.format.Time;
Felipe Lemeef134662016-08-10 14:46:39 -0700113import android.util.Log;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600114import android.util.Pair;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600115import android.util.RecurrenceRule;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700116import android.util.TrustedTime;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700117
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700118import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600119import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti281a17c2016-10-28 12:56:03 +0900120import com.android.internal.util.test.BroadcastInterceptingContext;
121import com.android.internal.util.test.BroadcastInterceptingContext.FutureIntent;
Felipe Lemeef134662016-08-10 14:46:39 -0700122import com.android.server.net.NetworkPolicyManagerInternal;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700123import com.android.server.net.NetworkPolicyManagerService;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600124import com.android.server.net.NetworkPolicyManagerService.ProcStateSeqHistory;
Felipe Lemeef134662016-08-10 14:46:39 -0700125
126import libcore.io.IoUtils;
Felipe Lemee88729d2016-08-17 16:43:01 -0700127import libcore.io.Streams;
Felipe Lemeef134662016-08-10 14:46:39 -0700128
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700129import com.google.common.util.concurrent.AbstractFuture;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700130
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700131import org.junit.After;
132import org.junit.Before;
Felipe Lemee88729d2016-08-17 16:43:01 -0700133import org.junit.Rule;
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700134import org.junit.Test;
Felipe Lemee88729d2016-08-17 16:43:01 -0700135import org.junit.rules.MethodRule;
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700136import org.junit.runner.RunWith;
Felipe Lemee88729d2016-08-17 16:43:01 -0700137import org.junit.runners.model.FrameworkMethod;
138import org.junit.runners.model.Statement;
Felipe Lemeef134662016-08-10 14:46:39 -0700139import org.mockito.ArgumentCaptor;
140import org.mockito.Mock;
141import org.mockito.MockitoAnnotations;
142import org.mockito.invocation.InvocationOnMock;
143import org.mockito.stubbing.Answer;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700144
Sudheer Shankae7361852017-03-07 11:51:46 -0800145import java.io.ByteArrayOutputStream;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700146import java.io.File;
Felipe Lemee88729d2016-08-17 16:43:01 -0700147import java.io.FileOutputStream;
148import java.io.InputStream;
149import java.io.OutputStream;
Sudheer Shankae7361852017-03-07 11:51:46 -0800150import java.io.PrintWriter;
Felipe Lemee88729d2016-08-17 16:43:01 -0700151import java.lang.annotation.Annotation;
152import java.lang.annotation.ElementType;
153import java.lang.annotation.Retention;
154import java.lang.annotation.RetentionPolicy;
155import java.lang.annotation.Target;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600156import java.time.Clock;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600157import java.time.Instant;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600158import java.time.Period;
159import java.time.ZoneId;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600160import java.time.ZonedDateTime;
Felipe Lemee88729d2016-08-17 16:43:01 -0700161import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700162import java.util.Calendar;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600163import java.util.Iterator;
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700164import java.util.LinkedHashSet;
Felipe Lemeef134662016-08-10 14:46:39 -0700165import java.util.List;
166import java.util.concurrent.CountDownLatch;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700167import java.util.concurrent.ExecutionException;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700168import java.util.concurrent.Future;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700169import java.util.concurrent.TimeUnit;
170import java.util.concurrent.TimeoutException;
Felipe Lemee88729d2016-08-17 16:43:01 -0700171import java.util.stream.Collectors;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700172
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700173/**
174 * Tests for {@link NetworkPolicyManagerService}.
Felipe Lemeb8d572e2016-12-05 13:41:43 -0800175 *
176 * <p>Typical usage:
177 *
178 * <pre><code>
179 m -j32 FrameworksServicesTests && adb install -r -g \
180 ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk && \
181 adb shell am instrument -e class "com.android.server.NetworkPolicyManagerServiceTest" -w \
182 "com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner"
183 * </code></pre>
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700184 */
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700185@RunWith(AndroidJUnit4.class)
Felipe Leme3d3308d2016-08-23 17:41:47 -0700186@MediumTest
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700187public class NetworkPolicyManagerServiceTest {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700188 private static final String TAG = "NetworkPolicyManagerServiceTest";
189
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700190 private static final long TEST_START = 1194220800000L;
191 private static final String TEST_IFACE = "test0";
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700192 private static final String TEST_SSID = "AndroidAP";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700193
Sudheer Shankae7361852017-03-07 11:51:46 -0800194 private static final String LINE_SEPARATOR = System.getProperty("line.separator");
195
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700196 private static NetworkTemplate sTemplateWifi = NetworkTemplate.buildTemplateWifi(TEST_SSID);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700197
Felipe Lemee88729d2016-08-17 16:43:01 -0700198 /**
199 * Path on assets where files used by {@link NetPolicyXml} are located.
200 */
201 private static final String NETPOLICY_DIR = "NetworkPolicyManagerServiceTest/netpolicy";
202
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700203 private BroadcastInterceptingContext mServiceContext;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700204 private File mPolicyDir;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700205
Felipe Lemee88729d2016-08-17 16:43:01 -0700206 /**
207 * Relative path of the XML file that will be used as {@code netpolicy.xml}.
208 *
209 * <p>Typically set through a {@link NetPolicyXml} annotation in the test method.
210 */
211 private String mNetpolicyXml;
212
Felipe Lemeef134662016-08-10 14:46:39 -0700213 private @Mock IActivityManager mActivityManager;
214 private @Mock INetworkStatsService mStatsService;
215 private @Mock INetworkManagementService mNetworkManager;
216 private @Mock TrustedTime mTime;
217 private @Mock IConnectivityManager mConnManager;
218 private @Mock INotificationManager mNotifManager;
Felipe Lemeef134662016-08-10 14:46:39 -0700219 private @Mock PackageManager mPackageManager;
Felipe Leme3d3308d2016-08-23 17:41:47 -0700220 private @Mock IPackageManager mIpm;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700221 private @Mock SubscriptionManager mSubscriptionManager;
222 private @Mock CarrierConfigManager mCarrierConfigManager;
223 private @Mock TelephonyManager mTelephonyManager;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700224
Sudheer Shankae7361852017-03-07 11:51:46 -0800225 private static ActivityManagerInternal mActivityManagerInternal;
226
Felipe Lemeef134662016-08-10 14:46:39 -0700227 private IUidObserver mUidObserver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700228 private INetworkManagementEventObserver mNetworkObserver;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700229
Felipe Lemeef134662016-08-10 14:46:39 -0700230 private NetworkPolicyListenerAnswer mPolicyListener;
231 private NetworkPolicyManagerService mService;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700232
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700233 /**
234 * In some of the tests while initializing NetworkPolicyManagerService,
235 * ACTION_RESTRICT_BACKGROUND_CHANGED is broadcasted. This is for capturing that broadcast.
236 */
237 private FutureIntent mFutureIntent;
238
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700239 private long mStartTime;
240 private long mElapsedRealtime;
241
Jeff Sharkeycae04a22012-03-22 15:18:52 -0700242 private static final int USER_ID = 0;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700243 private static final int FAKE_SUB_ID = 3737373;
244 private static final String FAKE_SUBSCRIBER_ID = "FAKE_SUB_ID";
245 private static final int DEFAULT_CYCLE_DAY = 1;
246 private static final int INVALID_CARRIER_CONFIG_VALUE = -9999;
247 private long mDefaultWarningBytes; // filled in with the actual default before tests are run
248 private long mDefaultLimitBytes; // filled in with the actual default before tests are run
Jeff Sharkeycae04a22012-03-22 15:18:52 -0700249
Felipe Lemee88729d2016-08-17 16:43:01 -0700250 private static final int APP_ID_A = android.os.Process.FIRST_APPLICATION_UID + 4;
251 private static final int APP_ID_B = android.os.Process.FIRST_APPLICATION_UID + 8;
252 private static final int APP_ID_C = android.os.Process.FIRST_APPLICATION_UID + 15;
253 private static final int APP_ID_D = android.os.Process.FIRST_APPLICATION_UID + 16;
254 private static final int APP_ID_E = android.os.Process.FIRST_APPLICATION_UID + 23;
255 private static final int APP_ID_F = android.os.Process.FIRST_APPLICATION_UID + 42;
Jeff Sharkeycae04a22012-03-22 15:18:52 -0700256
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700257 private static final int UID_A = UserHandle.getUid(USER_ID, APP_ID_A);
258 private static final int UID_B = UserHandle.getUid(USER_ID, APP_ID_B);
Felipe Lemee88729d2016-08-17 16:43:01 -0700259 private static final int UID_C = UserHandle.getUid(USER_ID, APP_ID_C);
260 private static final int UID_D = UserHandle.getUid(USER_ID, APP_ID_D);
261 private static final int UID_E = UserHandle.getUid(USER_ID, APP_ID_E);
262 private static final int UID_F = UserHandle.getUid(USER_ID, APP_ID_F);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700263
Felipe Lemeef134662016-08-10 14:46:39 -0700264 private static final String PKG_NAME_A = "name.is.A,pkg.A";
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700265
Felipe Lemee88729d2016-08-17 16:43:01 -0700266 public final @Rule NetPolicyMethodRule mNetPolicyXmlRule = new NetPolicyMethodRule();
267
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700268 private void registerLocalServices() {
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700269 addLocalServiceMock(DeviceIdleController.LocalService.class);
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700270
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700271 final UsageStatsManagerInternal usageStats =
272 addLocalServiceMock(UsageStatsManagerInternal.class);
273 when(usageStats.getIdleUidsForUser(anyInt())).thenReturn(new int[]{});
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700274
Sudheer Shankae7361852017-03-07 11:51:46 -0800275 mActivityManagerInternal = addLocalServiceMock(ActivityManagerInternal.class);
jackqdyulei29c82ab2017-03-10 14:09:16 -0800276
277 final PowerSaveState state = new PowerSaveState.Builder()
278 .setBatterySaverEnabled(false).build();
279 final PowerManagerInternal pmInternal = addLocalServiceMock(PowerManagerInternal.class);
280 when(pmInternal.getLowPowerState(anyInt())).thenReturn(state);
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700281 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700282
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700283 @Before
284 public void callSystemReady() throws Exception {
Felipe Lemeef134662016-08-10 14:46:39 -0700285 MockitoAnnotations.initMocks(this);
286
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700287 final Context context = InstrumentationRegistry.getContext();
Felipe Lemeef134662016-08-10 14:46:39 -0700288
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700289 setCurrentTimeMillis(TEST_START);
290
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700291 registerLocalServices();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700292 // Intercept various broadcasts, and pretend that uids have packages.
293 // Also return mock service instances for a few critical services.
Felipe Lemeef134662016-08-10 14:46:39 -0700294 mServiceContext = new BroadcastInterceptingContext(context) {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700295 @Override
296 public PackageManager getPackageManager() {
Felipe Lemeef134662016-08-10 14:46:39 -0700297 return mPackageManager;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700298 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700299
300 @Override
301 public void startActivity(Intent intent) {
302 // ignored
303 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700304
305 @Override
306 public Object getSystemService(String name) {
307 switch (name) {
308 case Context.TELEPHONY_SUBSCRIPTION_SERVICE:
309 return mSubscriptionManager;
310 case Context.CARRIER_CONFIG_SERVICE:
311 return mCarrierConfigManager;
312 case Context.TELEPHONY_SERVICE:
313 return mTelephonyManager;
314 default:
315 return super.getSystemService(name);
316 }
317 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700318 };
319
Felipe Lemee88729d2016-08-17 16:43:01 -0700320 setNetpolicyXml(context);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700321
Felipe Lemeef134662016-08-10 14:46:39 -0700322 doAnswer(new Answer<Void>() {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700323
Felipe Lemeef134662016-08-10 14:46:39 -0700324 @Override
325 public Void answer(InvocationOnMock invocation) throws Throwable {
326 mUidObserver = (IUidObserver) invocation.getArguments()[0];
327 Log.d(TAG, "set mUidObserver to " + mUidObserver);
328 return null;
329 }
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800330 }).when(mActivityManager).registerUidObserver(any(), anyInt(),
Felipe Lemeb8d572e2016-12-05 13:41:43 -0800331 eq(ActivityManager.PROCESS_STATE_UNKNOWN), isNull(String.class));
Felipe Lemeef134662016-08-10 14:46:39 -0700332
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700333 mFutureIntent = newRestrictBackgroundChangedFuture();
Felipe Lemeef134662016-08-10 14:46:39 -0700334 mService = new NetworkPolicyManagerService(mServiceContext, mActivityManager, mStatsService,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700335 mNetworkManager, mIpm, mTime, mPolicyDir, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700336 mService.bindConnectivityManager(mConnManager);
Jeff Sharkey2ef2aeb2011-06-15 11:01:31 -0700337 mService.bindNotificationManager(mNotifManager);
Felipe Lemeef134662016-08-10 14:46:39 -0700338 mPolicyListener = new NetworkPolicyListenerAnswer(mService);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700339
Felipe Lemeef134662016-08-10 14:46:39 -0700340 // Sets some common expectations.
341 when(mPackageManager.getPackageInfo(anyString(), anyInt())).thenAnswer(
342 new Answer<PackageInfo>() {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700343
Felipe Lemeef134662016-08-10 14:46:39 -0700344 @Override
345 public PackageInfo answer(InvocationOnMock invocation) throws Throwable {
346 final String packageName = (String) invocation.getArguments()[0];
347 final PackageInfo info = new PackageInfo();
348 final Signature signature;
349 if ("android".equals(packageName)) {
350 signature = new Signature("F00D");
351 } else {
352 signature = new Signature("DEAD");
353 }
354 info.signatures = new Signature[] {
355 signature
356 };
357 return info;
358 }
359 });
360 when(mPackageManager.getApplicationInfoAsUser(anyString(), anyInt(), anyInt()))
361 .thenReturn(new ApplicationInfo());
362 when(mPackageManager.getPackagesForUid(UID_A)).thenReturn(new String[] {PKG_NAME_A});
Felipe Lemeef134662016-08-10 14:46:39 -0700363 when(mNetworkManager.isBandwidthControlEnabled()).thenReturn(true);
Sudheer Shanka543339f2017-07-28 15:18:07 -0700364 when(mNetworkManager.setDataSaverModeEnabled(anyBoolean())).thenReturn(true);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700365 expectCurrentTime();
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700366
Felipe Lemeef134662016-08-10 14:46:39 -0700367 // Prepare NPMS.
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800368 mService.systemReady(mService.networkScoreAndNetworkManagementServiceReady());
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700369
Felipe Lemeef134662016-08-10 14:46:39 -0700370 // catch INetworkManagementEventObserver during systemReady()
Felipe Leme3d3308d2016-08-23 17:41:47 -0700371 final ArgumentCaptor<INetworkManagementEventObserver> networkObserver =
Felipe Lemeef134662016-08-10 14:46:39 -0700372 ArgumentCaptor.forClass(INetworkManagementEventObserver.class);
373 verify(mNetworkManager).registerObserver(networkObserver.capture());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700374 mNetworkObserver = networkObserver.getValue();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700375
376 NetworkPolicy defaultPolicy = mService.buildDefaultMobilePolicy(0, "");
377 mDefaultWarningBytes = defaultPolicy.warningBytes;
378 mDefaultLimitBytes = defaultPolicy.limitBytes;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700379 }
380
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700381 @After
382 public void removeFiles() throws Exception {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700383 for (File file : mPolicyDir.listFiles()) {
384 file.delete();
385 }
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700386 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700387
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700388 @After
389 public void unregisterLocalServices() throws Exception {
390 // Registered by NetworkPolicyManagerService's constructor.
Felipe Lemeef134662016-08-10 14:46:39 -0700391 LocalServices.removeServiceForTest(NetworkPolicyManagerInternal.class);
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700392
393 // Added in registerLocalServices()
394 LocalServices.removeServiceForTest(ActivityManagerInternal.class);
395 LocalServices.removeServiceForTest(PowerManagerInternal.class);
396 LocalServices.removeServiceForTest(DeviceIdleController.LocalService.class);
397 LocalServices.removeServiceForTest(UsageStatsManagerInternal.class);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700398 }
399
Jeff Sharkey53313d72017-07-13 16:47:32 -0600400 @After
401 public void resetClock() throws Exception {
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600402 RecurrenceRule.sClock = Clock.systemDefaultZone();
Jeff Sharkey53313d72017-07-13 16:47:32 -0600403 }
404
Felipe Lemee88729d2016-08-17 16:43:01 -0700405 @Test
Felipe Leme3d3308d2016-08-23 17:41:47 -0700406 public void testTurnRestrictBackgroundOn() throws Exception {
407 assertRestrictBackgroundOff(); // Sanity check.
408 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
409 setRestrictBackground(true);
410 assertRestrictBackgroundChangedReceived(futureIntent, null);
411 }
412
413 @Test
414 @NetPolicyXml("restrict-background-on.xml")
415 public void testTurnRestrictBackgroundOff() throws Exception {
416 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700417 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700418 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
419 setRestrictBackground(false);
420 assertRestrictBackgroundChangedReceived(futureIntent, null);
421 }
422
423 /**
424 * Adds whitelist when restrict background is on - app should receive an intent.
425 */
426 @Test
427 @NetPolicyXml("restrict-background-on.xml")
428 public void testAddRestrictBackgroundWhitelist_restrictBackgroundOn() throws Exception {
429 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700430 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700431 addRestrictBackgroundWhitelist(true);
432 }
433
434 /**
435 * Adds whitelist when restrict background is off - app should not receive an intent.
436 */
437 @Test
438 public void testAddRestrictBackgroundWhitelist_restrictBackgroundOff() throws Exception {
439 assertRestrictBackgroundOff(); // Sanity check.
440 addRestrictBackgroundWhitelist(false);
441 }
442
443 private void addRestrictBackgroundWhitelist(boolean expectIntent) throws Exception {
Felipe Leme57e3d312016-08-23 14:42:52 -0700444 // Sanity checks.
445 assertWhitelistUids();
446 assertUidPolicy(UID_A, POLICY_NONE);
447
Felipe Leme3d3308d2016-08-23 17:41:47 -0700448 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700449 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700450
Felipe Leme57e3d312016-08-23 14:42:52 -0700451 mService.setUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700452
453 assertWhitelistUids(UID_A);
Felipe Leme57e3d312016-08-23 14:42:52 -0700454 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700455 mPolicyListener.waitAndVerify()
456 .onUidPoliciesChanged(APP_ID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700457 if (expectIntent) {
458 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
459 } else {
460 futureIntent.assertNotReceived();
461 }
462 }
463
464 /**
465 * Removes whitelist when restrict background is on - app should receive an intent.
466 */
467 @Test
468 @NetPolicyXml("uidA-whitelisted-restrict-background-on.xml")
469 public void testRemoveRestrictBackgroundWhitelist_restrictBackgroundOn() throws Exception {
470 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700471 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700472 removeRestrictBackgroundWhitelist(true);
473 }
474
475 /**
476 * Removes whitelist when restrict background is off - app should not receive an intent.
477 */
478 @Test
479 @NetPolicyXml("uidA-whitelisted-restrict-background-off.xml")
480 public void testRemoveRestrictBackgroundWhitelist_restrictBackgroundOff() throws Exception {
481 assertRestrictBackgroundOff(); // Sanity check.
482 removeRestrictBackgroundWhitelist(false);
483 }
484
jackqdyulei29c82ab2017-03-10 14:09:16 -0800485 @Test
486 public void testLowPowerModeObserver_ListenersRegistered()
487 throws Exception {
488 PowerManagerInternal pmInternal = LocalServices.getService(PowerManagerInternal.class);
489
490 verify(pmInternal, atLeast(2)).registerLowPowerModeObserver(any());
491 }
492
493 @Test
494 public void updateRestrictBackgroundByLowPowerMode_RestrictOnBeforeBsm_RestrictOnAfterBsm()
495 throws Exception {
496 setRestrictBackground(true);
497 PowerSaveState stateOn = new PowerSaveState.Builder()
498 .setGlobalBatterySaverEnabled(true)
499 .setBatterySaverEnabled(false)
500 .build();
501 mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
502
503 // RestrictBackground should be on even though battery saver want to turn it off
504 assertThat(mService.getRestrictBackground()).isTrue();
505
506 PowerSaveState stateOff = new PowerSaveState.Builder()
507 .setGlobalBatterySaverEnabled(false)
508 .setBatterySaverEnabled(false)
509 .build();
510 mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
511
512 // RestrictBackground should be on, following its previous state
513 assertThat(mService.getRestrictBackground()).isTrue();
514 }
515
516 @Test
517 public void updateRestrictBackgroundByLowPowerMode_RestrictOffBeforeBsm_RestrictOffAfterBsm()
518 throws Exception {
519 setRestrictBackground(false);
520 PowerSaveState stateOn = new PowerSaveState.Builder()
521 .setGlobalBatterySaverEnabled(true)
522 .setBatterySaverEnabled(true)
523 .build();
524
jackqdyulei29c82ab2017-03-10 14:09:16 -0800525 mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
526
527 // RestrictBackground should be turned on because of battery saver
528 assertThat(mService.getRestrictBackground()).isTrue();
529
530 PowerSaveState stateOff = new PowerSaveState.Builder()
531 .setGlobalBatterySaverEnabled(false)
532 .setBatterySaverEnabled(false)
533 .build();
534 mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
535
536 // RestrictBackground should be off, following its previous state
537 assertThat(mService.getRestrictBackground()).isFalse();
538 }
539
540 @Test
541 public void updateRestrictBackgroundByLowPowerMode_StatusChangedInBsm_DoNotRestore()
542 throws Exception {
543 setRestrictBackground(true);
544 PowerSaveState stateOn = new PowerSaveState.Builder()
545 .setGlobalBatterySaverEnabled(true)
546 .setBatterySaverEnabled(true)
547 .build();
548 mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
549
550 // RestrictBackground should still be on
551 assertThat(mService.getRestrictBackground()).isTrue();
552
553 // User turns off RestrictBackground manually
554 setRestrictBackground(false);
555 PowerSaveState stateOff = new PowerSaveState.Builder().setBatterySaverEnabled(
556 false).build();
557 mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
558
559 // RestrictBackground should be off because user changes it manually
560 assertThat(mService.getRestrictBackground()).isFalse();
561 }
562
Felipe Leme3d3308d2016-08-23 17:41:47 -0700563 private void removeRestrictBackgroundWhitelist(boolean expectIntent) throws Exception {
Felipe Leme57e3d312016-08-23 14:42:52 -0700564 // Sanity checks.
565 assertWhitelistUids(UID_A);
566 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
567
Felipe Leme3d3308d2016-08-23 17:41:47 -0700568 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700569 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700570
Felipe Leme57e3d312016-08-23 14:42:52 -0700571 mService.setUidPolicy(UID_A, POLICY_NONE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700572
573 assertWhitelistUids();
Felipe Leme57e3d312016-08-23 14:42:52 -0700574 assertUidPolicy(UID_A, POLICY_NONE);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700575 mPolicyListener.waitAndVerify().onUidPoliciesChanged(APP_ID_A, POLICY_NONE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700576 if (expectIntent) {
577 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
578 } else {
579 futureIntent.assertNotReceived();
580 }
581 }
582
583 /**
Felipe Leme57e3d312016-08-23 14:42:52 -0700584 * Adds blacklist when restrict background is on - app should not receive an intent.
Felipe Leme3d3308d2016-08-23 17:41:47 -0700585 */
586 @Test
587 @NetPolicyXml("restrict-background-on.xml")
588 public void testAddRestrictBackgroundBlacklist_restrictBackgroundOn() throws Exception {
589 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700590 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme57e3d312016-08-23 14:42:52 -0700591 addRestrictBackgroundBlacklist(false);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700592 }
593
594 /**
595 * Adds blacklist when restrict background is off - app should receive an intent.
596 */
597 @Test
598 public void testAddRestrictBackgroundBlacklist_restrictBackgroundOff() throws Exception {
599 assertRestrictBackgroundOff(); // Sanity check.
600 addRestrictBackgroundBlacklist(true);
601 }
602
603 private void addRestrictBackgroundBlacklist(boolean expectIntent) throws Exception {
604 assertUidPolicy(UID_A, POLICY_NONE); // Sanity check.
605 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700606 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700607
608 mService.setUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
609
610 assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700611 mPolicyListener.waitAndVerify()
612 .onUidPoliciesChanged(APP_ID_A, POLICY_REJECT_METERED_BACKGROUND);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700613 if (expectIntent) {
614 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
615 } else {
616 futureIntent.assertNotReceived();
617 }
618 }
619
620 /**
Felipe Leme57e3d312016-08-23 14:42:52 -0700621 * Removes blacklist when restrict background is on - app should not receive an intent.
Felipe Leme3d3308d2016-08-23 17:41:47 -0700622 */
623 @Test
624 @NetPolicyXml("uidA-blacklisted-restrict-background-on.xml")
625 public void testRemoveRestrictBackgroundBlacklist_restrictBackgroundOn() throws Exception {
626 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700627 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme57e3d312016-08-23 14:42:52 -0700628 removeRestrictBackgroundBlacklist(false);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700629 }
630
631 /**
632 * Removes blacklist when restrict background is off - app should receive an intent.
633 */
634 @Test
635 @NetPolicyXml("uidA-blacklisted-restrict-background-off.xml")
636 public void testRemoveRestrictBackgroundBlacklist_restrictBackgroundOff() throws Exception {
637 assertRestrictBackgroundOff(); // Sanity check.
638 removeRestrictBackgroundBlacklist(true);
639 }
640
641 private void removeRestrictBackgroundBlacklist(boolean expectIntent) throws Exception {
642 assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND); // Sanity check.
643 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700644 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700645
646 mService.setUidPolicy(UID_A, POLICY_NONE);
647
648 assertUidPolicy(UID_A, POLICY_NONE);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700649 mPolicyListener.waitAndVerify()
650 .onUidPoliciesChanged(APP_ID_A, POLICY_NONE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700651 if (expectIntent) {
652 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
653 } else {
654 futureIntent.assertNotReceived();
655 }
656 }
657
Felipe Leme51a63642016-08-30 12:15:09 -0700658 @Test
Felipe Lemec08ecdf2016-08-30 12:57:35 -0700659 @NetPolicyXml("uidA-blacklisted-restrict-background-on.xml")
Felipe Leme3d3308d2016-08-23 17:41:47 -0700660 public void testBlacklistedAppIsNotNotifiedWhenRestrictBackgroundIsOn() throws Exception {
661 // Sanity checks.
662 assertRestrictBackgroundOn();
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700663 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700664 assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
665
666 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
667 setRestrictBackground(true);
668 futureIntent.assertNotReceived();
669 }
670
Felipe Leme51a63642016-08-30 12:15:09 -0700671 @Test
Felipe Lemec08ecdf2016-08-30 12:57:35 -0700672 @NetPolicyXml("uidA-whitelisted-restrict-background-on.xml")
Felipe Leme3d3308d2016-08-23 17:41:47 -0700673 public void testWhitelistedAppIsNotNotifiedWhenRestrictBackgroundIsOn() throws Exception {
674 // Sanity checks.
Felipe Lemec08ecdf2016-08-30 12:57:35 -0700675 assertRestrictBackgroundOn();
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700676 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700677 assertWhitelistUids(UID_A);
678
679 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
680 setRestrictBackground(true);
681 futureIntent.assertNotReceived();
682 }
683
Andreas Gampe84d156b2016-09-03 10:50:38 -0700684 @Test
Felipe Leme57e3d312016-08-23 14:42:52 -0700685 @NetPolicyXml("uidA-whitelisted-restrict-background-on.xml")
686 public void testWhitelistedAppIsNotifiedWhenBlacklisted() throws Exception {
687 // Sanity checks.
688 assertRestrictBackgroundOn();
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700689 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme57e3d312016-08-23 14:42:52 -0700690 assertWhitelistUids(UID_A);
691
692 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
693 mService.setUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
694 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
695 }
696
Felipe Leme3d3308d2016-08-23 17:41:47 -0700697 @Test
Felipe Lemee88729d2016-08-17 16:43:01 -0700698 @NetPolicyXml("restrict-background-lists-whitelist-format.xml")
699 public void testRestrictBackgroundLists_whitelistFormat() throws Exception {
Felipe Leme46b451f2016-08-19 08:46:17 -0700700 restrictBackgroundListsTest();
701 }
702
703 @Test
704 @NetPolicyXml("restrict-background-lists-uid-policy-format.xml")
705 public void testRestrictBackgroundLists_uidPolicyFormat() throws Exception {
706 restrictBackgroundListsTest();
707 }
708
709 private void restrictBackgroundListsTest() throws Exception {
Felipe Leme8546a442016-08-23 09:38:20 -0700710 // UIds that are whitelisted.
Felipe Leme46b451f2016-08-19 08:46:17 -0700711 assertWhitelistUids(UID_A, UID_B, UID_C);
712 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
713 assertUidPolicy(UID_B, POLICY_ALLOW_METERED_BACKGROUND);
714 assertUidPolicy(UID_C, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Lemee88729d2016-08-17 16:43:01 -0700715
Felipe Leme8546a442016-08-23 09:38:20 -0700716 // UIDs that are blacklisted.
Felipe Lemee88729d2016-08-17 16:43:01 -0700717 assertUidPolicy(UID_D, POLICY_NONE);
718 assertUidPolicy(UID_E, POLICY_REJECT_METERED_BACKGROUND);
Felipe Leme8546a442016-08-23 09:38:20 -0700719
720 // UIDS that have legacy policies.
Felipe Leme46b451f2016-08-19 08:46:17 -0700721 assertUidPolicy(UID_F, 2); // POLICY_ALLOW_BACKGROUND_BATTERY_SAVE
722
723 // Remove whitelist.
Felipe Leme57e3d312016-08-23 14:42:52 -0700724 mService.setUidPolicy(UID_A, POLICY_NONE);
Felipe Leme46b451f2016-08-19 08:46:17 -0700725 assertUidPolicy(UID_A, POLICY_NONE);
726 assertWhitelistUids(UID_B, UID_C);
727
728 // Add whitelist when blacklisted.
Felipe Leme57e3d312016-08-23 14:42:52 -0700729 mService.setUidPolicy(UID_E, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme46b451f2016-08-19 08:46:17 -0700730 assertUidPolicy(UID_E, POLICY_ALLOW_METERED_BACKGROUND);
731 assertWhitelistUids(UID_B, UID_C, UID_E);
732
733 // Add blacklist when whitelisted.
734 mService.setUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND);
735 assertUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND);
736 assertWhitelistUids(UID_C, UID_E);
737 }
738
739 /**
740 * Tests scenario where an UID had {@code restrict-background} and {@code uid-policy} tags.
741 */
742 @Test
743 @NetPolicyXml("restrict-background-lists-mixed-format.xml")
744 public void testRestrictBackgroundLists_mixedFormat() throws Exception {
745 assertWhitelistUids(UID_A, UID_C, UID_D);
746 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme57e3d312016-08-23 14:42:52 -0700747 assertUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND); // Blacklist prevails.
Felipe Leme46b451f2016-08-19 08:46:17 -0700748 assertUidPolicy(UID_C, (POLICY_ALLOW_METERED_BACKGROUND | 2));
749 assertUidPolicy(UID_D, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Lemee88729d2016-08-17 16:43:01 -0700750 }
751
Felipe Leme6f51a0a2016-08-24 15:11:51 -0700752 @Test
753 @NetPolicyXml("uids-with-mixed-policies.xml")
754 public void testGetUidsWithPolicy() throws Exception {
Felipe Leme03f90292016-09-08 18:10:32 -0700755 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_NONE));
Felipe Leme6f51a0a2016-08-24 15:11:51 -0700756 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND),
757 UID_B, UID_D);
758 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_ALLOW_METERED_BACKGROUND),
759 UID_E, UID_F);
760 // Legacy (POLICY_ALLOW_BACKGROUND_BATTERY_SAVE)
761 assertContainsInAnyOrder(mService.getUidsWithPolicy(2),
762 UID_C, UID_D, UID_F);
763 }
764
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700765 // NOTE: testPolicyChangeTriggersListener() is too superficial, they
Felipe Lemeef134662016-08-10 14:46:39 -0700766 // don't check for side-effects (like calls to NetworkManagementService) neither cover all
767 // different modes (Data Saver, Battery Saver, Doze, App idle, etc...).
768 // These scenarios are extensively tested on CTS' HostsideRestrictBackgroundNetworkTests.
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700769 @Test
Felipe Lemeef134662016-08-10 14:46:39 -0700770 public void testUidForeground() throws Exception {
771 // push all uids into background
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700772 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE, 0);
773 callOnUidStateChanged(UID_B, ActivityManager.PROCESS_STATE_SERVICE, 0);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700774 assertFalse(mService.isUidForeground(UID_A));
775 assertFalse(mService.isUidForeground(UID_B));
776
Felipe Lemeef134662016-08-10 14:46:39 -0700777 // push one of the uids into foreground
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700778 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_TOP, 0);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700779 assertTrue(mService.isUidForeground(UID_A));
780 assertFalse(mService.isUidForeground(UID_B));
781
782 // and swap another uid into foreground
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700783 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE, 0);
784 callOnUidStateChanged(UID_B, ActivityManager.PROCESS_STATE_TOP, 0);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700785 assertFalse(mService.isUidForeground(UID_A));
786 assertTrue(mService.isUidForeground(UID_B));
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700787 }
788
Jeff Sharkey53313d72017-07-13 16:47:32 -0600789 private static long computeLastCycleBoundary(long currentTime, NetworkPolicy policy) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600790 RecurrenceRule.sClock = Clock.fixed(Instant.ofEpochMilli(currentTime),
791 ZoneId.systemDefault());
792 final Iterator<Pair<ZonedDateTime, ZonedDateTime>> it = policy.cycleIterator();
Jeff Sharkey53313d72017-07-13 16:47:32 -0600793 while (it.hasNext()) {
794 final Pair<ZonedDateTime, ZonedDateTime> cycle = it.next();
795 if (cycle.first.toInstant().toEpochMilli() < currentTime) {
796 return cycle.first.toInstant().toEpochMilli();
797 }
798 }
799 throw new IllegalStateException(
800 "Failed to find current cycle for " + policy + " at " + currentTime);
801 }
802
803 private static long computeNextCycleBoundary(long currentTime, NetworkPolicy policy) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600804 RecurrenceRule.sClock = Clock.fixed(Instant.ofEpochMilli(currentTime),
805 ZoneId.systemDefault());
806 return policy.cycleIterator().next().second.toInstant().toEpochMilli();
Jeff Sharkey53313d72017-07-13 16:47:32 -0600807 }
808
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700809 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700810 public void testLastCycleBoundaryThisMonth() throws Exception {
811 // assume cycle day of "5th", which should be in same month
812 final long currentTime = parseTime("2007-11-14T00:00:00.000Z");
813 final long expectedCycle = parseTime("2007-11-05T00:00:00.000Z");
814
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700815 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800816 sTemplateWifi, 5, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700817 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700818 assertTimeEquals(expectedCycle, actualCycle);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700819 }
820
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700821 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700822 public void testLastCycleBoundaryLastMonth() throws Exception {
823 // assume cycle day of "20th", which should be in last month
824 final long currentTime = parseTime("2007-11-14T00:00:00.000Z");
825 final long expectedCycle = parseTime("2007-10-20T00:00:00.000Z");
826
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700827 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800828 sTemplateWifi, 20, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700829 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700830 assertTimeEquals(expectedCycle, actualCycle);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700831 }
832
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700833 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700834 public void testLastCycleBoundaryThisMonthFebruary() throws Exception {
835 // assume cycle day of "30th" in february; should go to january
836 final long currentTime = parseTime("2007-02-14T00:00:00.000Z");
837 final long expectedCycle = parseTime("2007-01-30T00:00:00.000Z");
838
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700839 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800840 sTemplateWifi, 30, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700841 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700842 assertTimeEquals(expectedCycle, actualCycle);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700843 }
844
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700845 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700846 public void testLastCycleBoundaryLastMonthFebruary() throws Exception {
847 // assume cycle day of "30th" in february, which should clamp
848 final long currentTime = parseTime("2007-03-14T00:00:00.000Z");
Jeff Sharkey53313d72017-07-13 16:47:32 -0600849 final long expectedCycle = parseTime("2007-02-28T23:59:59.999Z");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700850
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700851 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800852 sTemplateWifi, 30, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700853 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700854 assertTimeEquals(expectedCycle, actualCycle);
855 }
856
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700857 @Test
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800858 public void testCycleBoundaryLeapYear() throws Exception {
859 final NetworkPolicy policy = new NetworkPolicy(
860 sTemplateWifi, 29, TIMEZONE_UTC, 1024L, 1024L, false);
861
862 assertTimeEquals(parseTime("2012-01-29T00:00:00.000Z"),
863 computeNextCycleBoundary(parseTime("2012-01-14T00:00:00.000Z"), policy));
864 assertTimeEquals(parseTime("2012-02-29T00:00:00.000Z"),
865 computeNextCycleBoundary(parseTime("2012-02-14T00:00:00.000Z"), policy));
866 assertTimeEquals(parseTime("2012-02-29T00:00:00.000Z"),
867 computeLastCycleBoundary(parseTime("2012-03-14T00:00:00.000Z"), policy));
868 assertTimeEquals(parseTime("2012-03-29T00:00:00.000Z"),
869 computeNextCycleBoundary(parseTime("2012-03-14T00:00:00.000Z"), policy));
870
871 assertTimeEquals(parseTime("2007-01-29T00:00:00.000Z"),
872 computeNextCycleBoundary(parseTime("2007-01-14T00:00:00.000Z"), policy));
Jeff Sharkey53313d72017-07-13 16:47:32 -0600873 assertTimeEquals(parseTime("2007-02-28T23:59:59.999Z"),
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800874 computeNextCycleBoundary(parseTime("2007-02-14T00:00:00.000Z"), policy));
Jeff Sharkey53313d72017-07-13 16:47:32 -0600875 assertTimeEquals(parseTime("2007-02-28T23:59:59.999Z"),
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800876 computeLastCycleBoundary(parseTime("2007-03-14T00:00:00.000Z"), policy));
877 assertTimeEquals(parseTime("2007-03-29T00:00:00.000Z"),
878 computeNextCycleBoundary(parseTime("2007-03-14T00:00:00.000Z"), policy));
879 }
880
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700881 @Test
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800882 public void testNextCycleTimezoneAfterUtc() throws Exception {
883 // US/Central is UTC-6
884 final NetworkPolicy policy = new NetworkPolicy(
885 sTemplateWifi, 10, "US/Central", 1024L, 1024L, false);
886 assertTimeEquals(parseTime("2012-01-10T06:00:00.000Z"),
887 computeNextCycleBoundary(parseTime("2012-01-05T00:00:00.000Z"), policy));
888 }
889
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700890 @Test
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800891 public void testNextCycleTimezoneBeforeUtc() throws Exception {
892 // Israel is UTC+2
893 final NetworkPolicy policy = new NetworkPolicy(
894 sTemplateWifi, 10, "Israel", 1024L, 1024L, false);
895 assertTimeEquals(parseTime("2012-01-09T22:00:00.000Z"),
896 computeNextCycleBoundary(parseTime("2012-01-05T00:00:00.000Z"), policy));
897 }
898
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700899 @Test
Jeff Sharkey15399052013-01-15 14:15:53 -0800900 public void testCycleTodayJanuary() throws Exception {
901 final NetworkPolicy policy = new NetworkPolicy(
902 sTemplateWifi, 14, "US/Pacific", 1024L, 1024L, false);
903
904 assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
905 computeNextCycleBoundary(parseTime("2013-01-13T23:59:59.000-08:00"), policy));
906 assertTimeEquals(parseTime("2013-02-14T00:00:00.000-08:00"),
907 computeNextCycleBoundary(parseTime("2013-01-14T00:00:01.000-08:00"), policy));
908 assertTimeEquals(parseTime("2013-02-14T00:00:00.000-08:00"),
909 computeNextCycleBoundary(parseTime("2013-01-14T15:11:00.000-08:00"), policy));
910
911 assertTimeEquals(parseTime("2012-12-14T00:00:00.000-08:00"),
912 computeLastCycleBoundary(parseTime("2013-01-13T23:59:59.000-08:00"), policy));
913 assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
914 computeLastCycleBoundary(parseTime("2013-01-14T00:00:01.000-08:00"), policy));
915 assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
916 computeLastCycleBoundary(parseTime("2013-01-14T15:11:00.000-08:00"), policy));
917 }
918
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700919 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700920 public void testNetworkPolicyAppliedCycleLastMonth() throws Exception {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700921 NetworkState[] state = null;
922 NetworkStats stats = null;
923
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700924 final int CYCLE_DAY = 15;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600925 final long NOW = parseTime("2007-03-10T00:00Z");
926 final long CYCLE_START = parseTime("2007-02-15T00:00Z");
927 final long CYCLE_END = parseTime("2007-03-15T00:00Z");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700928
Jeff Sharkey53313d72017-07-13 16:47:32 -0600929 setCurrentTimeMillis(NOW);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700930
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700931 // first, pretend that wifi network comes online. no policy active,
932 // which means we shouldn't push limit to interface.
933 state = new NetworkState[] { buildWifi() };
Felipe Lemeef134662016-08-10 14:46:39 -0700934 when(mConnManager.getAllNetworkState()).thenReturn(state);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700935 expectCurrentTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700936
Felipe Lemeef134662016-08-10 14:46:39 -0700937 mPolicyListener.expect().onMeteredIfacesChanged(any());
Erik Klinef851d6d2015-04-20 16:03:48 +0900938 mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION));
Felipe Lemeef134662016-08-10 14:46:39 -0700939 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(any());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700940
941 // now change cycle to be on 15th, and test in early march, to verify we
942 // pick cycle day in previous month.
Felipe Lemeef134662016-08-10 14:46:39 -0700943 when(mConnManager.getAllNetworkState()).thenReturn(state);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700944 expectCurrentTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700945
946 // pretend that 512 bytes total have happened
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700947 stats = new NetworkStats(getElapsedRealtime(), 1)
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700948 .addIfaceValues(TEST_IFACE, 256L, 2L, 256L, 2L);
Jeff Sharkey53313d72017-07-13 16:47:32 -0600949 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, CYCLE_START, CYCLE_END))
Felipe Lemeef134662016-08-10 14:46:39 -0700950 .thenReturn(stats.getTotalBytes());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700951
Felipe Lemeef134662016-08-10 14:46:39 -0700952 mPolicyListener.expect().onMeteredIfacesChanged(any());
Jeff Sharkey163e6442011-10-31 16:37:52 -0700953 setNetworkPolicies(new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800954 sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, 1 * MB_IN_BYTES, 2 * MB_IN_BYTES, false));
Felipe Lemeef134662016-08-10 14:46:39 -0700955 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
956
957 // TODO: consider making strongly ordered mock
958 verifyPolicyDataEnable(TYPE_WIFI, true);
959 verifyRemoveInterfaceQuota(TEST_IFACE);
960 verifySetInterfaceQuota(TEST_IFACE, (2 * MB_IN_BYTES) - 512);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700961 }
962
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700963 @Test
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700964 public void testOverWarningLimitNotification() throws Exception {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700965 NetworkState[] state = null;
966 NetworkStats stats = null;
Felipe Lemeef134662016-08-10 14:46:39 -0700967 Future<String> tagFuture = null;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700968
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700969 final int CYCLE_DAY = 15;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600970 final long NOW = parseTime("2007-03-10T00:00Z");
971 final long CYCLE_START = parseTime("2007-02-15T00:00Z");
972 final long CYCLE_END = parseTime("2007-03-15T00:00Z");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700973
Jeff Sharkey53313d72017-07-13 16:47:32 -0600974 setCurrentTimeMillis(NOW);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700975
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700976 // assign wifi policy
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700977 state = new NetworkState[] {};
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700978 stats = new NetworkStats(getElapsedRealtime(), 1)
979 .addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700980
981 {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700982 expectCurrentTime();
Felipe Lemeef134662016-08-10 14:46:39 -0700983 when(mConnManager.getAllNetworkState()).thenReturn(state);
Jeff Sharkey53313d72017-07-13 16:47:32 -0600984 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, CYCLE_START,
985 CYCLE_END)).thenReturn(stats.getTotalBytes());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700986
Felipe Lemeef134662016-08-10 14:46:39 -0700987 mPolicyListener.expect().onMeteredIfacesChanged(any());
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800988 setNetworkPolicies(new NetworkPolicy(sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, 1
989 * MB_IN_BYTES, 2 * MB_IN_BYTES, false));
Felipe Lemeef134662016-08-10 14:46:39 -0700990 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(any());
991 verifyPolicyDataEnable(TYPE_WIFI, true);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700992 }
993
994 // bring up wifi network
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700995 incrementCurrentTime(MINUTE_IN_MILLIS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700996 state = new NetworkState[] { buildWifi() };
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700997 stats = new NetworkStats(getElapsedRealtime(), 1)
998 .addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700999
1000 {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001001 expectCurrentTime();
Felipe Lemeef134662016-08-10 14:46:39 -07001002 when(mConnManager.getAllNetworkState()).thenReturn(state);
Jeff Sharkey53313d72017-07-13 16:47:32 -06001003 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, CYCLE_START,
1004 CYCLE_END)).thenReturn(stats.getTotalBytes());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001005
Felipe Lemeef134662016-08-10 14:46:39 -07001006 mPolicyListener.expect().onMeteredIfacesChanged(any());
Erik Klinef851d6d2015-04-20 16:03:48 +09001007 mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION));
Felipe Lemeef134662016-08-10 14:46:39 -07001008 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
1009
1010 verifyPolicyDataEnable(TYPE_WIFI, true);
1011 verifyRemoveInterfaceQuota(TEST_IFACE);
1012 verifySetInterfaceQuota(TEST_IFACE, 2 * MB_IN_BYTES);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001013 }
1014
1015 // go over warning, which should kick notification
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001016 incrementCurrentTime(MINUTE_IN_MILLIS);
1017 stats = new NetworkStats(getElapsedRealtime(), 1)
Jeff Sharkey163e6442011-10-31 16:37:52 -07001018 .addIfaceValues(TEST_IFACE, 1536 * KB_IN_BYTES, 15L, 0L, 0L);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001019
1020 {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001021 expectCurrentTime();
Jeff Sharkey53313d72017-07-13 16:47:32 -06001022 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, CYCLE_START,
1023 CYCLE_END)).thenReturn(stats.getTotalBytes());
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001024 tagFuture = expectEnqueueNotification();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001025
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001026 mNetworkObserver.limitReached(null, TEST_IFACE);
Felipe Lemeef134662016-08-10 14:46:39 -07001027
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001028 assertNotificationType(TYPE_WARNING, tagFuture.get());
Felipe Lemeef134662016-08-10 14:46:39 -07001029 verifyPolicyDataEnable(TYPE_WIFI, true);
1030
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001031 }
1032
1033 // go over limit, which should kick notification and dialog
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001034 incrementCurrentTime(MINUTE_IN_MILLIS);
1035 stats = new NetworkStats(getElapsedRealtime(), 1)
Jeff Sharkey163e6442011-10-31 16:37:52 -07001036 .addIfaceValues(TEST_IFACE, 5 * MB_IN_BYTES, 512L, 0L, 0L);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001037
1038 {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001039 expectCurrentTime();
Jeff Sharkey53313d72017-07-13 16:47:32 -06001040 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, CYCLE_START,
1041 CYCLE_END)).thenReturn(stats.getTotalBytes());
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001042 tagFuture = expectEnqueueNotification();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001043
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001044 mNetworkObserver.limitReached(null, TEST_IFACE);
Felipe Lemeef134662016-08-10 14:46:39 -07001045
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001046 assertNotificationType(TYPE_LIMIT, tagFuture.get());
Felipe Lemeef134662016-08-10 14:46:39 -07001047 verifyPolicyDataEnable(TYPE_WIFI, false);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001048 }
1049
1050 // now snooze policy, which should remove quota
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001051 incrementCurrentTime(MINUTE_IN_MILLIS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001052
1053 {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001054 expectCurrentTime();
Felipe Lemeef134662016-08-10 14:46:39 -07001055 when(mConnManager.getAllNetworkState()).thenReturn(state);
Jeff Sharkey53313d72017-07-13 16:47:32 -06001056 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, CYCLE_START,
1057 CYCLE_END)).thenReturn(stats.getTotalBytes());
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001058 tagFuture = expectEnqueueNotification();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001059
Felipe Lemeef134662016-08-10 14:46:39 -07001060 mPolicyListener.expect().onMeteredIfacesChanged(any());
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001061 mService.snoozeLimit(sTemplateWifi);
Felipe Lemeef134662016-08-10 14:46:39 -07001062 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
1063
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001064 assertNotificationType(TYPE_LIMIT_SNOOZED, tagFuture.get());
Felipe Lemeef134662016-08-10 14:46:39 -07001065 // snoozed interface still has high quota so background data is
1066 // still restricted.
1067 verifyRemoveInterfaceQuota(TEST_IFACE);
1068 verifySetInterfaceQuota(TEST_IFACE, Long.MAX_VALUE);
1069 verifyPolicyDataEnable(TYPE_WIFI, true);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001070 }
1071 }
1072
Felipe Leme9f27e7a2016-08-12 15:19:40 -07001073 @Test
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001074 public void testMeteredNetworkWithoutLimit() throws Exception {
1075 NetworkState[] state = null;
1076 NetworkStats stats = null;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001077
1078 final long TIME_FEB_15 = 1171497600000L;
1079 final long TIME_MAR_10 = 1173484800000L;
1080 final int CYCLE_DAY = 15;
1081
1082 setCurrentTimeMillis(TIME_MAR_10);
1083
1084 // bring up wifi network with metered policy
1085 state = new NetworkState[] { buildWifi() };
1086 stats = new NetworkStats(getElapsedRealtime(), 1)
1087 .addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L);
1088
1089 {
1090 expectCurrentTime();
Felipe Lemeef134662016-08-10 14:46:39 -07001091 when(mConnManager.getAllNetworkState()).thenReturn(state);
1092 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15,
1093 currentTimeMillis())).thenReturn(stats.getTotalBytes());
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001094
Felipe Lemeef134662016-08-10 14:46:39 -07001095 mPolicyListener.expect().onMeteredIfacesChanged(any());
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001096 setNetworkPolicies(new NetworkPolicy(
1097 sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, WARNING_DISABLED, LIMIT_DISABLED,
1098 true));
Felipe Lemeef134662016-08-10 14:46:39 -07001099 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
1100
1101 verifyPolicyDataEnable(TYPE_WIFI, true);
1102 verifyRemoveInterfaceQuota(TEST_IFACE);
1103 verifySetInterfaceQuota(TEST_IFACE, Long.MAX_VALUE);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001104 }
1105 }
1106
Sudheer Shankae7361852017-03-07 11:51:46 -08001107 @Test
1108 public void testOnUidStateChanged_notifyAMS() throws Exception {
1109 final long procStateSeq = 222;
Sudheer Shankaed25ce62017-03-29 20:46:30 -07001110 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE, procStateSeq);
Sudheer Shankae7361852017-03-07 11:51:46 -08001111 verify(mActivityManagerInternal).notifyNetworkPolicyRulesUpdated(UID_A, procStateSeq);
1112
1113 final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
1114 final IndentingPrintWriter writer = new IndentingPrintWriter(
1115 new PrintWriter(outputStream), " ");
1116 mService.mObservedHistory.dumpUL(writer);
1117 writer.flush();
1118 assertEquals(ProcStateSeqHistory.getString(UID_A, procStateSeq),
1119 outputStream.toString().trim());
1120 }
1121
Sudheer Shankaed25ce62017-03-29 20:46:30 -07001122 private void callOnUidStateChanged(int uid, int procState, long procStateSeq)
1123 throws Exception {
1124 mUidObserver.onUidStateChanged(uid, procState, procStateSeq);
1125 final CountDownLatch latch = new CountDownLatch(1);
1126 mService.mUidEventHandler.post(() -> {
1127 latch.countDown();
1128 });
1129 latch.await(2, TimeUnit.SECONDS);
1130 }
1131
Sudheer Shankae7361852017-03-07 11:51:46 -08001132 @Test
1133 public void testProcStateHistory() {
1134 // Verify dump works correctly with no elements added.
1135 verifyProcStateHistoryDump(0);
1136
1137 // Add items upto half of the max capacity and verify that dump works correctly.
1138 verifyProcStateHistoryDump(MAX_PROC_STATE_SEQ_HISTORY / 2);
1139
1140 // Add items upto the max capacity and verify that dump works correctly.
1141 verifyProcStateHistoryDump(MAX_PROC_STATE_SEQ_HISTORY);
1142
1143 // Add more items than max capacity and verify that dump works correctly.
1144 verifyProcStateHistoryDump(MAX_PROC_STATE_SEQ_HISTORY + MAX_PROC_STATE_SEQ_HISTORY / 2);
1145
1146 }
1147
1148 private void verifyProcStateHistoryDump(int count) {
1149 final ProcStateSeqHistory history = new ProcStateSeqHistory(MAX_PROC_STATE_SEQ_HISTORY);
1150 final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
1151 final IndentingPrintWriter writer = new IndentingPrintWriter(
1152 new PrintWriter(outputStream), " ");
1153
1154 if (count == 0) {
1155 // Verify with no uid info written to history.
1156 history.dumpUL(writer);
1157 writer.flush();
1158 assertEquals("When no uid info is there, dump should contain NONE",
1159 "NONE", outputStream.toString().trim());
1160 return;
1161 }
1162
1163 int uid = 111;
1164 long procStateSeq = 222;
1165 // Add count items and verify dump works correctly.
1166 for (int i = 0; i < count; ++i) {
1167 uid++;
1168 procStateSeq++;
1169 history.addProcStateSeqUL(uid, procStateSeq);
1170 }
1171 history.dumpUL(writer);
1172 writer.flush();
1173 final String[] uidsDump = outputStream.toString().split(LINE_SEPARATOR);
1174 // Dump will have at most MAX_PROC_STATE_SEQ_HISTORY items.
1175 final int expectedCount = (count < MAX_PROC_STATE_SEQ_HISTORY)
1176 ? count : MAX_PROC_STATE_SEQ_HISTORY;
1177 assertEquals(expectedCount, uidsDump.length);
1178 for (int i = 0; i < expectedCount; ++i) {
1179 assertEquals(ProcStateSeqHistory.getString(uid, procStateSeq), uidsDump[i]);
1180 uid--;
1181 procStateSeq--;
1182 }
1183 }
1184
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001185 private void assertCycleDayAsExpected(PersistableBundle config, int carrierCycleDay,
1186 boolean expectValid) {
1187 config.putInt(KEY_MONTHLY_DATA_CYCLE_DAY_INT, carrierCycleDay);
1188 int actualCycleDay = mService.getCycleDayFromCarrierConfig(config,
1189 INVALID_CARRIER_CONFIG_VALUE);
1190 if (expectValid) {
1191 assertEquals(carrierCycleDay, actualCycleDay);
1192 } else {
1193 // INVALID_CARRIER_CONFIG_VALUE is returned for invalid values
1194 assertEquals(INVALID_CARRIER_CONFIG_VALUE, actualCycleDay);
1195 }
1196 }
1197
1198 @Test
1199 public void testGetCycleDayFromCarrierConfig() {
1200 PersistableBundle config = CarrierConfigManager.getDefaultConfig();
1201 final Calendar cal = Calendar.getInstance();
1202 int actualCycleDay;
1203
1204 config.putInt(KEY_MONTHLY_DATA_CYCLE_DAY_INT, DATA_CYCLE_USE_PLATFORM_DEFAULT);
1205 actualCycleDay = mService.getCycleDayFromCarrierConfig(config, DEFAULT_CYCLE_DAY);
1206 assertEquals(DEFAULT_CYCLE_DAY, actualCycleDay);
1207
1208 // null config returns a default value
1209 actualCycleDay = mService.getCycleDayFromCarrierConfig(null, DEFAULT_CYCLE_DAY);
1210 assertEquals(DEFAULT_CYCLE_DAY, actualCycleDay);
1211
1212 // Sane, non-default values
1213 assertCycleDayAsExpected(config, 1, true);
1214 assertCycleDayAsExpected(config, cal.getMaximum(Calendar.DAY_OF_MONTH), true);
1215 assertCycleDayAsExpected(config, cal.getMinimum(Calendar.DAY_OF_MONTH), true);
1216
1217 // Invalid values
1218 assertCycleDayAsExpected(config, 0, false);
1219 assertCycleDayAsExpected(config, DATA_CYCLE_THRESHOLD_DISABLED, false);
1220 assertCycleDayAsExpected(config, cal.getMaximum(Calendar.DAY_OF_MONTH) + 1, false);
1221 assertCycleDayAsExpected(config, cal.getMinimum(Calendar.DAY_OF_MONTH) - 5, false);
1222 }
1223
1224 private void assertWarningBytesAsExpected(PersistableBundle config, long carrierWarningBytes,
1225 long expected) {
1226 config.putLong(KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, carrierWarningBytes);
1227 long actualWarning = mService.getWarningBytesFromCarrierConfig(config,
1228 INVALID_CARRIER_CONFIG_VALUE);
1229 assertEquals(expected, actualWarning);
1230 }
1231
1232 @Test
1233 public void testGetWarningBytesFromCarrierConfig() {
1234 PersistableBundle config = CarrierConfigManager.getDefaultConfig();
1235 long actualWarningBytes;
1236
1237 assertWarningBytesAsExpected(config, DATA_CYCLE_USE_PLATFORM_DEFAULT,
1238 mDefaultWarningBytes);
1239 assertWarningBytesAsExpected(config, DATA_CYCLE_THRESHOLD_DISABLED, WARNING_DISABLED);
1240 assertWarningBytesAsExpected(config, 0, 0);
1241 // not a valid value
1242 assertWarningBytesAsExpected(config, -1000, INVALID_CARRIER_CONFIG_VALUE);
1243
1244 // null config returns a default value
1245 actualWarningBytes = mService.getWarningBytesFromCarrierConfig(null, mDefaultWarningBytes);
1246 assertEquals(mDefaultWarningBytes, actualWarningBytes);
1247 }
1248
1249 private void assertLimitBytesAsExpected(PersistableBundle config, long carrierWarningBytes,
1250 long expected) {
1251 config.putLong(KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG, carrierWarningBytes);
1252 long actualWarning = mService.getLimitBytesFromCarrierConfig(config,
1253 INVALID_CARRIER_CONFIG_VALUE);
1254 assertEquals(expected, actualWarning);
1255 }
1256
1257 @Test
1258 public void testGetLimitBytesFromCarrierConfig() {
1259 PersistableBundle config = CarrierConfigManager.getDefaultConfig();
1260 long actualLimitBytes;
1261
1262 assertLimitBytesAsExpected(config, DATA_CYCLE_USE_PLATFORM_DEFAULT,
1263 mDefaultLimitBytes);
1264 assertLimitBytesAsExpected(config, DATA_CYCLE_THRESHOLD_DISABLED, LIMIT_DISABLED);
1265 assertLimitBytesAsExpected(config, 0, 0);
1266 // not a valid value
1267 assertLimitBytesAsExpected(config, -1000, INVALID_CARRIER_CONFIG_VALUE);
1268
1269 // null config returns a default value
1270 actualLimitBytes = mService.getWarningBytesFromCarrierConfig(null, mDefaultLimitBytes);
1271 assertEquals(mDefaultLimitBytes, actualLimitBytes);
1272 }
1273
1274 private PersistableBundle setupUpdateMobilePolicyCycleTests() throws RemoteException {
1275 when(mConnManager.getAllNetworkState()).thenReturn(new NetworkState[0]);
1276 when(mSubscriptionManager.getActiveSubscriptionIdList()).thenReturn(new int[]{FAKE_SUB_ID});
1277 when(mTelephonyManager.getSubscriberId(FAKE_SUB_ID)).thenReturn(FAKE_SUBSCRIBER_ID);
1278 PersistableBundle bundle = CarrierConfigManager.getDefaultConfig();
1279 when(mCarrierConfigManager.getConfigForSubId(FAKE_SUB_ID)).thenReturn(bundle);
1280 setNetworkPolicies(buildDefaultFakeMobilePolicy());
1281 return bundle;
1282 }
1283
1284 @Test
1285 public void testUpdateMobilePolicyCycleWithNullConfig() throws RemoteException {
1286 when(mConnManager.getAllNetworkState()).thenReturn(new NetworkState[0]);
1287 when(mSubscriptionManager.getActiveSubscriptionIdList()).thenReturn(new int[]{FAKE_SUB_ID});
1288 when(mTelephonyManager.getSubscriberId(FAKE_SUB_ID)).thenReturn(FAKE_SUBSCRIBER_ID);
1289 when(mCarrierConfigManager.getConfigForSubId(FAKE_SUB_ID)).thenReturn(null);
1290 setNetworkPolicies(buildDefaultFakeMobilePolicy());
1291 // smoke test to make sure no errors are raised
1292 mServiceContext.sendBroadcast(
1293 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1294 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1295 );
1296 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1297 true);
1298 }
1299
1300 @Test
1301 public void testUpdateMobilePolicyCycleWithInvalidConfig() throws RemoteException {
1302 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1303 // Test with an invalid CarrierConfig, there should be no changes or crashes.
1304 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, -100);
1305 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, -100);
1306 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG, -100);
1307 mServiceContext.sendBroadcast(
1308 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1309 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1310 );
1311
1312 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1313 true);
1314 }
1315
1316 @Test
1317 public void testUpdateMobilePolicyCycleWithDefaultConfig() throws RemoteException {
1318 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1319 // Test that we respect the platform values when told to
1320 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT,
1321 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1322 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1323 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1324 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1325 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1326 mServiceContext.sendBroadcast(
1327 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1328 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1329 );
1330
1331 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1332 true);
1333 }
1334
1335 @Test
1336 public void testUpdateMobilePolicyCycleWithUserOverrides() throws RemoteException {
1337 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1338
1339 // inferred = false implies that a user manually modified this policy.
1340 NetworkPolicy policy = buildDefaultFakeMobilePolicy();
1341 policy.inferred = false;
1342 setNetworkPolicies(policy);
1343
1344 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1345 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, 9999);
1346 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1347 DATA_CYCLE_THRESHOLD_DISABLED);
1348 mServiceContext.sendBroadcast(
1349 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1350 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1351 );
1352
1353 // The policy still shouldn't change, because we don't want to overwrite user settings.
1354 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1355 false);
1356 }
1357
1358 @Test
1359 public void testUpdateMobilePolicyCycleUpdatesDataCycle() throws RemoteException {
1360 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1361
1362 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1363 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, 9999);
1364 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG, 9999);
1365 mServiceContext.sendBroadcast(
1366 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1367 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1368 );
1369
1370 assertNetworkPolicyEquals(31, 9999, 9999, true);
1371 }
1372
1373 @Test
1374 public void testUpdateMobilePolicyCycleDisableThresholds() throws RemoteException {
1375 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1376
1377 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1378 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1379 DATA_CYCLE_THRESHOLD_DISABLED);
1380 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1381 DATA_CYCLE_THRESHOLD_DISABLED);
1382 mServiceContext.sendBroadcast(
1383 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1384 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1385 );
1386
1387 assertNetworkPolicyEquals(31, WARNING_DISABLED, LIMIT_DISABLED, true);
1388 }
1389
1390 @Test
1391 public void testUpdateMobilePolicyCycleRevertsToDefault() throws RemoteException {
1392 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1393
1394 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1395 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1396 DATA_CYCLE_THRESHOLD_DISABLED);
1397 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1398 DATA_CYCLE_THRESHOLD_DISABLED);
1399 mServiceContext.sendBroadcast(
1400 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1401 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1402 );
1403 assertNetworkPolicyEquals(31, WARNING_DISABLED, LIMIT_DISABLED, true);
1404
1405 // If the user switches carriers to one that doesn't use a CarrierConfig, we should revert
1406 // to the default data limit and warning. The cycle date doesn't need to revert as it's
1407 // arbitrary anyways.
1408 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT,
1409 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1410 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1411 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1412 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1413 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1414 mServiceContext.sendBroadcast(
1415 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1416 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1417 );
1418
1419 assertNetworkPolicyEquals(31, mDefaultWarningBytes, mDefaultLimitBytes,
1420 true);
1421 }
1422
1423 private NetworkPolicy buildDefaultFakeMobilePolicy() {
1424 NetworkPolicy p = mService.buildDefaultMobilePolicy(FAKE_SUB_ID, FAKE_SUBSCRIBER_ID);
1425 // set a deterministic cycle date
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001426 p.cycleRule = new RecurrenceRule(
1427 p.cycleRule.start.withDayOfMonth(DEFAULT_CYCLE_DAY),
1428 p.cycleRule.end, Period.ofMonths(1));
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001429 return p;
1430 }
1431
1432 private static NetworkPolicy buildFakeMobilePolicy(int cycleDay, long warningBytes,
1433 long limitBytes, boolean inferred){
1434 final NetworkTemplate template = buildTemplateMobileAll(FAKE_SUBSCRIBER_ID);
Sudheer Shankaed25ce62017-03-29 20:46:30 -07001435 return new NetworkPolicy(template, cycleDay, new Time().timezone, warningBytes,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001436 limitBytes, SNOOZE_NEVER, SNOOZE_NEVER, true, inferred);
1437 }
1438
1439 private void assertNetworkPolicyEquals(int expectedCycleDay, long expectedWarningBytes,
1440 long expectedLimitBytes, boolean expectedInferred) {
1441 NetworkPolicy[] policies = mService.getNetworkPolicies(
1442 mServiceContext.getOpPackageName());
1443 assertEquals("Unexpected number of network policies", 1, policies.length);
1444 NetworkPolicy actualPolicy = policies[0];
1445 NetworkPolicy expectedPolicy = buildFakeMobilePolicy(expectedCycleDay, expectedWarningBytes,
1446 expectedLimitBytes, expectedInferred);
1447 assertEquals(expectedPolicy, actualPolicy);
1448 }
1449
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001450 private static long parseTime(String time) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06001451 return ZonedDateTime.parse(time).toInstant().toEpochMilli();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001452 }
1453
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07001454 private void setNetworkPolicies(NetworkPolicy... policies) {
1455 mService.setNetworkPolicies(policies);
1456 }
1457
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001458 private static NetworkState buildWifi() {
1459 final NetworkInfo info = new NetworkInfo(TYPE_WIFI, 0, null, null);
1460 info.setDetailedState(DetailedState.CONNECTED, null, null);
1461 final LinkProperties prop = new LinkProperties();
1462 prop.setInterfaceName(TEST_IFACE);
Stephen Chena1c92b72017-02-06 13:18:11 -08001463 final NetworkCapabilities networkCapabilities = new NetworkCapabilities();
1464 return new NetworkState(info, prop, networkCapabilities, null, null, TEST_SSID);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001465 }
1466
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001467 private void expectCurrentTime() throws Exception {
Felipe Lemeef134662016-08-10 14:46:39 -07001468 when(mTime.forceRefresh()).thenReturn(false);
1469 when(mTime.hasCache()).thenReturn(true);
1470 when(mTime.currentTimeMillis()).thenReturn(currentTimeMillis());
1471 when(mTime.getCacheAge()).thenReturn(0L);
1472 when(mTime.getCacheCertainty()).thenReturn(0L);
Jeff Sharkey2ef2aeb2011-06-15 11:01:31 -07001473 }
1474
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001475 private Future<String> expectEnqueueNotification() throws Exception {
Felipe Lemeef134662016-08-10 14:46:39 -07001476 final FutureAnswer<String> futureAnswer = new FutureAnswer<String>(2);
1477 doAnswer(futureAnswer).when(mNotifManager).enqueueNotificationWithTag(
1478 anyString(), anyString(), anyString() /* capture here (index 2)*/,
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001479 anyInt(), isA(Notification.class), anyInt());
Felipe Lemeef134662016-08-10 14:46:39 -07001480 return futureAnswer;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001481 }
1482
Felipe Leme3d3308d2016-08-23 17:41:47 -07001483 private void expectHasInternetPermission(int uid, boolean hasIt) throws Exception {
1484 when(mIpm.checkUidPermission(Manifest.permission.INTERNET, uid)).thenReturn(
1485 hasIt ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED);
1486 }
1487
Felipe Lemeef134662016-08-10 14:46:39 -07001488 private void verifySetInterfaceQuota(String iface, long quotaBytes) throws Exception {
1489 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001490 }
1491
Felipe Lemeef134662016-08-10 14:46:39 -07001492 private void verifyRemoveInterfaceQuota(String iface) throws Exception {
1493 verify(mNetworkManager, atLeastOnce()).removeInterfaceQuota(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001494 }
1495
Felipe Lemeef134662016-08-10 14:46:39 -07001496 private Future<Void> verifyPolicyDataEnable(int type, boolean enabled) throws Exception {
Jeff Sharkey32566012014-12-02 18:30:14 -08001497 // TODO: bring back this test
1498 return null;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001499 }
1500
Felipe Lemeef134662016-08-10 14:46:39 -07001501 private void verifyAdvisePersistThreshold() throws Exception {
1502 verify(mStatsService).advisePersistThreshold(anyLong());
Jeff Sharkey0cf6de02012-05-04 15:03:30 -07001503 }
1504
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001505 private static class TestAbstractFuture<T> extends AbstractFuture<T> {
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001506 @Override
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001507 public T get() throws InterruptedException, ExecutionException {
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001508 try {
1509 return get(5, TimeUnit.SECONDS);
1510 } catch (TimeoutException e) {
1511 throw new RuntimeException(e);
1512 }
1513 }
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001514 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001515
Felipe Lemeef134662016-08-10 14:46:39 -07001516 private static class FutureAnswer<T> extends TestAbstractFuture<T> implements Answer<Void> {
1517 private final int index;
1518
1519 FutureAnswer(int index) {
1520 this.index = index;
1521 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001522 @Override
Felipe Lemeef134662016-08-10 14:46:39 -07001523 public Void answer(InvocationOnMock invocation) throws Throwable {
1524 @SuppressWarnings("unchecked")
1525 T captured = (T) invocation.getArguments()[index];
1526 set(captured);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001527 return null;
1528 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001529 }
1530
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -07001531 private static void assertTimeEquals(long expected, long actual) {
1532 if (expected != actual) {
1533 fail("expected " + formatTime(expected) + " but was actually " + formatTime(actual));
1534 }
1535 }
1536
1537 private static String formatTime(long millis) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06001538 return Instant.ofEpochMilli(millis) + " [" + millis + "]";
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -07001539 }
1540
1541 private static void assertEqualsFuzzy(long expected, long actual, long fuzzy) {
1542 final long low = expected - fuzzy;
1543 final long high = expected + fuzzy;
1544 if (actual < low || actual > high) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06001545 fail("value " + formatTime(actual) + " is outside [" + formatTime(low) + ","
1546 + formatTime(high) + "]");
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -07001547 }
1548 }
1549
1550 private static void assertUnique(LinkedHashSet<Long> seen, Long value) {
1551 if (!seen.add(value)) {
1552 fail("found duplicate time " + value + " in series " + seen.toString());
1553 }
1554 }
1555
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001556 private static void assertNotificationType(int expected, String actualTag) {
Felipe Lemeef134662016-08-10 14:46:39 -07001557 assertEquals("notification type mismatch for '" + actualTag +"'",
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001558 Integer.toString(expected), actualTag.substring(actualTag.lastIndexOf(':') + 1));
1559 }
1560
Felipe Lemee88729d2016-08-17 16:43:01 -07001561 private void assertUidPolicy(int uid, int expected) {
1562 final int actual = mService.getUidPolicy(uid);
1563 if (expected != actual) {
1564 fail("Wrong policy for UID " + uid + ": expected " + uidPoliciesToString(expected)
1565 + ", actual " + uidPoliciesToString(actual));
1566 }
1567 }
1568
Felipe Leme46b451f2016-08-19 08:46:17 -07001569 private void assertWhitelistUids(int... uids) {
Felipe Leme57e3d312016-08-23 14:42:52 -07001570 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_ALLOW_METERED_BACKGROUND), uids);
Felipe Leme46b451f2016-08-19 08:46:17 -07001571 }
1572
Felipe Leme3d3308d2016-08-23 17:41:47 -07001573 private void assertRestrictBackgroundOn() throws Exception {
1574 assertTrue("restrictBackground should be set", mService.getRestrictBackground());
1575 }
1576
1577 private void assertRestrictBackgroundOff() throws Exception {
1578 assertFalse("restrictBackground should not be set", mService.getRestrictBackground());
1579 }
1580
1581 private FutureIntent newRestrictBackgroundChangedFuture() {
1582 return mServiceContext
1583 .nextBroadcastIntent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
1584 }
1585
1586 private void assertRestrictBackgroundChangedReceived(Future<Intent> future,
1587 String expectedPackage) throws Exception {
1588 final String action = ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED;
1589 final Intent intent = future.get(5, TimeUnit.SECONDS);
1590 assertNotNull("Didn't get a " + action + "intent in 5 seconds");
1591 assertEquals("Wrong package on " + action + " intent", expectedPackage, intent.getPackage());
1592 }
1593
Felipe Lemee88729d2016-08-17 16:43:01 -07001594 // TODO: replace by Truth, Hamcrest, or a similar tool.
1595 private void assertContainsInAnyOrder(int[] actual, int...expected) {
1596 final StringBuilder errors = new StringBuilder();
1597 if (actual.length != expected.length) {
1598 errors.append("\tsize does not match\n");
1599 }
1600 final List<Integer> actualList =
1601 Arrays.stream(actual).boxed().collect(Collectors.<Integer>toList());
1602 final List<Integer> expectedList =
1603 Arrays.stream(expected).boxed().collect(Collectors.<Integer>toList());
1604 if (!actualList.containsAll(expectedList)) {
1605 errors.append("\tmissing elements on actual list\n");
1606 }
1607 if (!expectedList.containsAll(actualList)) {
1608 errors.append("\tmissing elements on expected list\n");
1609 }
1610 if (errors.length() > 0) {
1611 fail("assertContainsInAnyOrder(expected=" + Arrays.toString(expected)
1612 + ", actual=" + Arrays.toString(actual) +") failed: \n" + errors);
1613 }
1614 }
1615
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001616 private long getElapsedRealtime() {
1617 return mElapsedRealtime;
1618 }
1619
1620 private void setCurrentTimeMillis(long currentTimeMillis) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001621 RecurrenceRule.sClock = Clock.fixed(Instant.ofEpochMilli(currentTimeMillis),
1622 ZoneId.systemDefault());
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001623 mStartTime = currentTimeMillis;
1624 mElapsedRealtime = 0L;
1625 }
1626
1627 private long currentTimeMillis() {
1628 return mStartTime + mElapsedRealtime;
1629 }
1630
1631 private void incrementCurrentTime(long duration) {
1632 mElapsedRealtime += duration;
1633 }
1634
Felipe Leme3d3308d2016-08-23 17:41:47 -07001635 private FutureIntent mRestrictBackgroundChanged;
1636
1637 private void setRestrictBackground(boolean flag) throws Exception {
Felipe Leme3d3308d2016-08-23 17:41:47 -07001638 mService.setRestrictBackground(flag);
1639 // Sanity check.
1640 assertEquals("restrictBackground not set", flag, mService.getRestrictBackground());
1641 }
1642
Felipe Lemeef134662016-08-10 14:46:39 -07001643 /**
1644 * Creates a mock and registers it to {@link LocalServices}.
1645 */
Felipe Leme9f27e7a2016-08-12 15:19:40 -07001646 private static <T> T addLocalServiceMock(Class<T> clazz) {
Felipe Lemeef134662016-08-10 14:46:39 -07001647 final T mock = mock(clazz);
Felipe Lemeef134662016-08-10 14:46:39 -07001648 LocalServices.addService(clazz, mock);
Felipe Lemeef134662016-08-10 14:46:39 -07001649 return mock;
1650 }
1651
1652 /**
Felipe Lemeef134662016-08-10 14:46:39 -07001653 * Custom Mockito answer used to verify async {@link INetworkPolicyListener} calls.
1654 *
1655 * <p>Typical usage:
1656 * <pre><code>
1657 * mPolicyListener.expect().someCallback(any());
1658 * // do something on objects under test
1659 * mPolicyListener.waitAndVerify().someCallback(eq(expectedValue));
1660 * </code></pre>
1661 */
1662 final class NetworkPolicyListenerAnswer implements Answer<Void> {
1663 private CountDownLatch latch;
1664 private final INetworkPolicyListener listener;
1665
1666 NetworkPolicyListenerAnswer(NetworkPolicyManagerService service) {
1667 this.listener = mock(INetworkPolicyListener.class);
1668 // RemoteCallbackList needs a binder to use as key
1669 when(listener.asBinder()).thenReturn(new Binder());
1670 service.registerListener(listener);
1671 }
1672
1673 @Override
1674 public Void answer(InvocationOnMock invocation) throws Throwable {
1675 Log.d(TAG,"counting down on answer: " + invocation);
1676 latch.countDown();
1677 return null;
1678 }
1679
1680 INetworkPolicyListener expect() {
1681 assertNull("expect() called before waitAndVerify()", latch);
1682 latch = new CountDownLatch(1);
1683 return doAnswer(this).when(listener);
1684 }
1685
1686 INetworkPolicyListener waitAndVerify() {
1687 assertNotNull("waitAndVerify() called before expect()", latch);
1688 try {
1689 assertTrue("callback not called in 5 seconds", latch.await(5, TimeUnit.SECONDS));
1690 } catch (InterruptedException e) {
1691 fail("Thread interrupted before callback called");
1692 } finally {
1693 latch = null;
1694 }
1695 return verify(listener, atLeastOnce());
1696 }
Felipe Leme3d3308d2016-08-23 17:41:47 -07001697
1698 INetworkPolicyListener verifyNotCalled() {
1699 return verify(listener, never());
1700 }
1701
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001702 }
Felipe Lemee88729d2016-08-17 16:43:01 -07001703
1704 private void setNetpolicyXml(Context context) throws Exception {
1705 mPolicyDir = context.getFilesDir();
1706 if (mPolicyDir.exists()) {
1707 IoUtils.deleteContents(mPolicyDir);
1708 }
1709 if (!TextUtils.isEmpty(mNetpolicyXml)) {
1710 final String assetPath = NETPOLICY_DIR + "/" + mNetpolicyXml;
1711 final File netConfigFile = new File(mPolicyDir, "netpolicy.xml");
1712 Log.d(TAG, "Creating " + netConfigFile + " from asset " + assetPath);
1713 try (final InputStream in = context.getResources().getAssets().open(assetPath);
1714 final OutputStream out = new FileOutputStream(netConfigFile)) {
1715 Streams.copy(in, out);
1716 }
1717 }
1718 }
1719
1720 /**
1721 * Annotation used to define the relative path of the {@code netpolicy.xml} file.
1722 */
1723 @Retention(RetentionPolicy.RUNTIME)
1724 @Target(ElementType.METHOD)
1725 public @interface NetPolicyXml {
1726
1727 public String value() default "";
1728
1729 }
1730
1731 /**
1732 * Rule used to set {@code mNetPolicyXml} according to the {@link NetPolicyXml} annotation.
1733 */
1734 public static class NetPolicyMethodRule implements MethodRule {
1735
1736 @Override
1737 public Statement apply(Statement base, FrameworkMethod method, Object target) {
1738 for (Annotation annotation : method.getAnnotations()) {
1739 if ((annotation instanceof NetPolicyXml)) {
1740 final String path = ((NetPolicyXml) annotation).value();
1741 if (!path.isEmpty()) {
1742 ((NetworkPolicyManagerServiceTest) target).mNetpolicyXml = path;
1743 break;
1744 }
1745 }
1746 }
1747 return base;
1748 }
1749 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001750}