blob: 8decb968c8fbe4421df2cde4117a68ba9fb59eb0 [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;
54import static org.mockito.ArgumentMatchers.anyInt;
55import static org.mockito.ArgumentMatchers.anyLong;
56import static org.mockito.ArgumentMatchers.anyString;
57import static org.mockito.ArgumentMatchers.eq;
58import static org.mockito.ArgumentMatchers.isA;
59import static org.mockito.ArgumentMatchers.isNull;
jackqdyulei29c82ab2017-03-10 14:09:16 -080060import static org.mockito.Mockito.atLeast;
Felipe Lemeef134662016-08-10 14:46:39 -070061import static org.mockito.Mockito.atLeastOnce;
62import static org.mockito.Mockito.doAnswer;
jackqdyulei29c82ab2017-03-10 14:09:16 -080063import static org.mockito.Mockito.doReturn;
Felipe Lemeef134662016-08-10 14:46:39 -070064import static org.mockito.Mockito.mock;
Felipe Leme3d3308d2016-08-23 17:41:47 -070065import static org.mockito.Mockito.never;
Felipe Lemeef134662016-08-10 14:46:39 -070066import static org.mockito.Mockito.verify;
67import static org.mockito.Mockito.when;
68
Felipe Leme3d3308d2016-08-23 17:41:47 -070069import android.Manifest;
Felipe Lemeef134662016-08-10 14:46:39 -070070import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -080071import android.app.ActivityManagerInternal;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070072import android.app.IActivityManager;
Jeff Sharkey2ef2aeb2011-06-15 11:01:31 -070073import android.app.INotificationManager;
Felipe Lemeef134662016-08-10 14:46:39 -070074import android.app.IUidObserver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070075import android.app.Notification;
Felipe Lemeef134662016-08-10 14:46:39 -070076import android.app.usage.UsageStatsManagerInternal;
77import android.content.Context;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070078import android.content.Intent;
Felipe Lemeef134662016-08-10 14:46:39 -070079import android.content.pm.ApplicationInfo;
Felipe Leme3d3308d2016-08-23 17:41:47 -070080import android.content.pm.IPackageManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070081import android.content.pm.PackageInfo;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070082import android.content.pm.PackageManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070083import android.content.pm.Signature;
Felipe Leme3d3308d2016-08-23 17:41:47 -070084import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070085import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070086import android.net.INetworkManagementEventObserver;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070087import android.net.INetworkPolicyListener;
Jeff Sharkey75279902011-05-24 18:39:45 -070088import android.net.INetworkStatsService;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070089import android.net.LinkProperties;
Stephen Chena1c92b72017-02-06 13:18:11 -080090import android.net.NetworkCapabilities;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070091import android.net.NetworkInfo;
92import android.net.NetworkInfo.DetailedState;
93import android.net.NetworkPolicy;
94import android.net.NetworkState;
95import android.net.NetworkStats;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070096import android.net.NetworkTemplate;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070097import android.os.Binder;
Ashish Sharma50fd36d2011-06-15 19:34:53 -070098import android.os.INetworkManagementService;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070099import android.os.PersistableBundle;
Felipe Lemeef134662016-08-10 14:46:39 -0700100import android.os.PowerManagerInternal;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800101import android.os.PowerSaveState;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700102import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700103import android.os.UserHandle;
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700104import android.support.test.InstrumentationRegistry;
Felipe Leme3d3308d2016-08-23 17:41:47 -0700105import android.support.test.filters.MediumTest;
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700106import android.support.test.runner.AndroidJUnit4;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700107import android.telephony.CarrierConfigManager;
108import android.telephony.SubscriptionManager;
109import android.telephony.TelephonyManager;
Felipe Lemee88729d2016-08-17 16:43:01 -0700110import android.text.TextUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700111import android.text.format.Time;
Felipe Lemeef134662016-08-10 14:46:39 -0700112import android.util.Log;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600113import android.util.Pair;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600114import android.util.RecurrenceRule;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700115import android.util.TrustedTime;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700116
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700117import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600118import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti281a17c2016-10-28 12:56:03 +0900119import com.android.internal.util.test.BroadcastInterceptingContext;
120import com.android.internal.util.test.BroadcastInterceptingContext.FutureIntent;
Felipe Lemeef134662016-08-10 14:46:39 -0700121import com.android.server.net.NetworkPolicyManagerInternal;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700122import com.android.server.net.NetworkPolicyManagerService;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600123import com.android.server.net.NetworkPolicyManagerService.ProcStateSeqHistory;
Felipe Lemeef134662016-08-10 14:46:39 -0700124
125import libcore.io.IoUtils;
Felipe Lemee88729d2016-08-17 16:43:01 -0700126import libcore.io.Streams;
Felipe Lemeef134662016-08-10 14:46:39 -0700127
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700128import com.google.common.util.concurrent.AbstractFuture;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700129
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700130import org.junit.After;
131import org.junit.Before;
Felipe Lemee88729d2016-08-17 16:43:01 -0700132import org.junit.Rule;
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700133import org.junit.Test;
Felipe Lemee88729d2016-08-17 16:43:01 -0700134import org.junit.rules.MethodRule;
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700135import org.junit.runner.RunWith;
Felipe Lemee88729d2016-08-17 16:43:01 -0700136import org.junit.runners.model.FrameworkMethod;
137import org.junit.runners.model.Statement;
Felipe Lemeef134662016-08-10 14:46:39 -0700138import org.mockito.ArgumentCaptor;
139import org.mockito.Mock;
140import org.mockito.MockitoAnnotations;
141import org.mockito.invocation.InvocationOnMock;
142import org.mockito.stubbing.Answer;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700143
Sudheer Shankae7361852017-03-07 11:51:46 -0800144import java.io.ByteArrayOutputStream;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700145import java.io.File;
Felipe Lemee88729d2016-08-17 16:43:01 -0700146import java.io.FileOutputStream;
147import java.io.InputStream;
148import java.io.OutputStream;
Sudheer Shankae7361852017-03-07 11:51:46 -0800149import java.io.PrintWriter;
Felipe Lemee88729d2016-08-17 16:43:01 -0700150import java.lang.annotation.Annotation;
151import java.lang.annotation.ElementType;
152import java.lang.annotation.Retention;
153import java.lang.annotation.RetentionPolicy;
154import java.lang.annotation.Target;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600155import java.time.Clock;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600156import java.time.Instant;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600157import java.time.Period;
158import java.time.ZoneId;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600159import java.time.ZonedDateTime;
Felipe Lemee88729d2016-08-17 16:43:01 -0700160import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700161import java.util.Calendar;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600162import java.util.Iterator;
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700163import java.util.LinkedHashSet;
Felipe Lemeef134662016-08-10 14:46:39 -0700164import java.util.List;
165import java.util.concurrent.CountDownLatch;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700166import java.util.concurrent.ExecutionException;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700167import java.util.concurrent.Future;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700168import java.util.concurrent.TimeUnit;
169import java.util.concurrent.TimeoutException;
Felipe Lemee88729d2016-08-17 16:43:01 -0700170import java.util.stream.Collectors;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700171
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700172/**
173 * Tests for {@link NetworkPolicyManagerService}.
Felipe Lemeb8d572e2016-12-05 13:41:43 -0800174 *
175 * <p>Typical usage:
176 *
177 * <pre><code>
178 m -j32 FrameworksServicesTests && adb install -r -g \
179 ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk && \
180 adb shell am instrument -e class "com.android.server.NetworkPolicyManagerServiceTest" -w \
181 "com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner"
182 * </code></pre>
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700183 */
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700184@RunWith(AndroidJUnit4.class)
Felipe Leme3d3308d2016-08-23 17:41:47 -0700185@MediumTest
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700186public class NetworkPolicyManagerServiceTest {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700187 private static final String TAG = "NetworkPolicyManagerServiceTest";
188
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700189 private static final long TEST_START = 1194220800000L;
190 private static final String TEST_IFACE = "test0";
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700191 private static final String TEST_SSID = "AndroidAP";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700192
Sudheer Shankae7361852017-03-07 11:51:46 -0800193 private static final String LINE_SEPARATOR = System.getProperty("line.separator");
194
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700195 private static NetworkTemplate sTemplateWifi = NetworkTemplate.buildTemplateWifi(TEST_SSID);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700196
Felipe Lemee88729d2016-08-17 16:43:01 -0700197 /**
198 * Path on assets where files used by {@link NetPolicyXml} are located.
199 */
200 private static final String NETPOLICY_DIR = "NetworkPolicyManagerServiceTest/netpolicy";
201
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700202 private BroadcastInterceptingContext mServiceContext;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700203 private File mPolicyDir;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700204
Felipe Lemee88729d2016-08-17 16:43:01 -0700205 /**
206 * Relative path of the XML file that will be used as {@code netpolicy.xml}.
207 *
208 * <p>Typically set through a {@link NetPolicyXml} annotation in the test method.
209 */
210 private String mNetpolicyXml;
211
Felipe Lemeef134662016-08-10 14:46:39 -0700212 private @Mock IActivityManager mActivityManager;
213 private @Mock INetworkStatsService mStatsService;
214 private @Mock INetworkManagementService mNetworkManager;
215 private @Mock TrustedTime mTime;
216 private @Mock IConnectivityManager mConnManager;
217 private @Mock INotificationManager mNotifManager;
Felipe Lemeef134662016-08-10 14:46:39 -0700218 private @Mock PackageManager mPackageManager;
Felipe Leme3d3308d2016-08-23 17:41:47 -0700219 private @Mock IPackageManager mIpm;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700220 private @Mock SubscriptionManager mSubscriptionManager;
221 private @Mock CarrierConfigManager mCarrierConfigManager;
222 private @Mock TelephonyManager mTelephonyManager;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700223
Sudheer Shankae7361852017-03-07 11:51:46 -0800224 private static ActivityManagerInternal mActivityManagerInternal;
225
Felipe Lemeef134662016-08-10 14:46:39 -0700226 private IUidObserver mUidObserver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700227 private INetworkManagementEventObserver mNetworkObserver;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700228
Felipe Lemeef134662016-08-10 14:46:39 -0700229 private NetworkPolicyListenerAnswer mPolicyListener;
230 private NetworkPolicyManagerService mService;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700231
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700232 /**
233 * In some of the tests while initializing NetworkPolicyManagerService,
234 * ACTION_RESTRICT_BACKGROUND_CHANGED is broadcasted. This is for capturing that broadcast.
235 */
236 private FutureIntent mFutureIntent;
237
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700238 private long mStartTime;
239 private long mElapsedRealtime;
240
Jeff Sharkeycae04a22012-03-22 15:18:52 -0700241 private static final int USER_ID = 0;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700242 private static final int FAKE_SUB_ID = 3737373;
243 private static final String FAKE_SUBSCRIBER_ID = "FAKE_SUB_ID";
244 private static final int DEFAULT_CYCLE_DAY = 1;
245 private static final int INVALID_CARRIER_CONFIG_VALUE = -9999;
246 private long mDefaultWarningBytes; // filled in with the actual default before tests are run
247 private long mDefaultLimitBytes; // filled in with the actual default before tests are run
Jeff Sharkeycae04a22012-03-22 15:18:52 -0700248
Felipe Lemee88729d2016-08-17 16:43:01 -0700249 private static final int APP_ID_A = android.os.Process.FIRST_APPLICATION_UID + 4;
250 private static final int APP_ID_B = android.os.Process.FIRST_APPLICATION_UID + 8;
251 private static final int APP_ID_C = android.os.Process.FIRST_APPLICATION_UID + 15;
252 private static final int APP_ID_D = android.os.Process.FIRST_APPLICATION_UID + 16;
253 private static final int APP_ID_E = android.os.Process.FIRST_APPLICATION_UID + 23;
254 private static final int APP_ID_F = android.os.Process.FIRST_APPLICATION_UID + 42;
Jeff Sharkeycae04a22012-03-22 15:18:52 -0700255
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700256 private static final int UID_A = UserHandle.getUid(USER_ID, APP_ID_A);
257 private static final int UID_B = UserHandle.getUid(USER_ID, APP_ID_B);
Felipe Lemee88729d2016-08-17 16:43:01 -0700258 private static final int UID_C = UserHandle.getUid(USER_ID, APP_ID_C);
259 private static final int UID_D = UserHandle.getUid(USER_ID, APP_ID_D);
260 private static final int UID_E = UserHandle.getUid(USER_ID, APP_ID_E);
261 private static final int UID_F = UserHandle.getUid(USER_ID, APP_ID_F);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700262
Felipe Lemeef134662016-08-10 14:46:39 -0700263 private static final String PKG_NAME_A = "name.is.A,pkg.A";
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700264
Felipe Lemee88729d2016-08-17 16:43:01 -0700265 public final @Rule NetPolicyMethodRule mNetPolicyXmlRule = new NetPolicyMethodRule();
266
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700267 private void registerLocalServices() {
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700268 addLocalServiceMock(DeviceIdleController.LocalService.class);
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700269
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700270 final UsageStatsManagerInternal usageStats =
271 addLocalServiceMock(UsageStatsManagerInternal.class);
272 when(usageStats.getIdleUidsForUser(anyInt())).thenReturn(new int[]{});
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700273
Sudheer Shankae7361852017-03-07 11:51:46 -0800274 mActivityManagerInternal = addLocalServiceMock(ActivityManagerInternal.class);
jackqdyulei29c82ab2017-03-10 14:09:16 -0800275
276 final PowerSaveState state = new PowerSaveState.Builder()
277 .setBatterySaverEnabled(false).build();
278 final PowerManagerInternal pmInternal = addLocalServiceMock(PowerManagerInternal.class);
279 when(pmInternal.getLowPowerState(anyInt())).thenReturn(state);
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700280 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700281
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700282 @Before
283 public void callSystemReady() throws Exception {
Felipe Lemeef134662016-08-10 14:46:39 -0700284 MockitoAnnotations.initMocks(this);
285
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700286 final Context context = InstrumentationRegistry.getContext();
Felipe Lemeef134662016-08-10 14:46:39 -0700287
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700288 setCurrentTimeMillis(TEST_START);
289
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700290 registerLocalServices();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700291 // Intercept various broadcasts, and pretend that uids have packages.
292 // Also return mock service instances for a few critical services.
Felipe Lemeef134662016-08-10 14:46:39 -0700293 mServiceContext = new BroadcastInterceptingContext(context) {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700294 @Override
295 public PackageManager getPackageManager() {
Felipe Lemeef134662016-08-10 14:46:39 -0700296 return mPackageManager;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700297 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700298
299 @Override
300 public void startActivity(Intent intent) {
301 // ignored
302 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700303
304 @Override
305 public Object getSystemService(String name) {
306 switch (name) {
307 case Context.TELEPHONY_SUBSCRIPTION_SERVICE:
308 return mSubscriptionManager;
309 case Context.CARRIER_CONFIG_SERVICE:
310 return mCarrierConfigManager;
311 case Context.TELEPHONY_SERVICE:
312 return mTelephonyManager;
313 default:
314 return super.getSystemService(name);
315 }
316 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700317 };
318
Felipe Lemee88729d2016-08-17 16:43:01 -0700319 setNetpolicyXml(context);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700320
Felipe Lemeef134662016-08-10 14:46:39 -0700321 doAnswer(new Answer<Void>() {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700322
Felipe Lemeef134662016-08-10 14:46:39 -0700323 @Override
324 public Void answer(InvocationOnMock invocation) throws Throwable {
325 mUidObserver = (IUidObserver) invocation.getArguments()[0];
326 Log.d(TAG, "set mUidObserver to " + mUidObserver);
327 return null;
328 }
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800329 }).when(mActivityManager).registerUidObserver(any(), anyInt(),
Felipe Lemeb8d572e2016-12-05 13:41:43 -0800330 eq(ActivityManager.PROCESS_STATE_UNKNOWN), isNull(String.class));
Felipe Lemeef134662016-08-10 14:46:39 -0700331
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700332 mFutureIntent = newRestrictBackgroundChangedFuture();
Felipe Lemeef134662016-08-10 14:46:39 -0700333 mService = new NetworkPolicyManagerService(mServiceContext, mActivityManager, mStatsService,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700334 mNetworkManager, mIpm, mTime, mPolicyDir, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700335 mService.bindConnectivityManager(mConnManager);
Jeff Sharkey2ef2aeb2011-06-15 11:01:31 -0700336 mService.bindNotificationManager(mNotifManager);
Felipe Lemeef134662016-08-10 14:46:39 -0700337 mPolicyListener = new NetworkPolicyListenerAnswer(mService);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700338
Felipe Lemeef134662016-08-10 14:46:39 -0700339 // Sets some common expectations.
340 when(mPackageManager.getPackageInfo(anyString(), anyInt())).thenAnswer(
341 new Answer<PackageInfo>() {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700342
Felipe Lemeef134662016-08-10 14:46:39 -0700343 @Override
344 public PackageInfo answer(InvocationOnMock invocation) throws Throwable {
345 final String packageName = (String) invocation.getArguments()[0];
346 final PackageInfo info = new PackageInfo();
347 final Signature signature;
348 if ("android".equals(packageName)) {
349 signature = new Signature("F00D");
350 } else {
351 signature = new Signature("DEAD");
352 }
353 info.signatures = new Signature[] {
354 signature
355 };
356 return info;
357 }
358 });
359 when(mPackageManager.getApplicationInfoAsUser(anyString(), anyInt(), anyInt()))
360 .thenReturn(new ApplicationInfo());
361 when(mPackageManager.getPackagesForUid(UID_A)).thenReturn(new String[] {PKG_NAME_A});
Felipe Lemeef134662016-08-10 14:46:39 -0700362 when(mNetworkManager.isBandwidthControlEnabled()).thenReturn(true);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700363 expectCurrentTime();
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700364
Felipe Lemeef134662016-08-10 14:46:39 -0700365 // Prepare NPMS.
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800366 mService.systemReady(mService.networkScoreAndNetworkManagementServiceReady());
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700367
Felipe Lemeef134662016-08-10 14:46:39 -0700368 // catch INetworkManagementEventObserver during systemReady()
Felipe Leme3d3308d2016-08-23 17:41:47 -0700369 final ArgumentCaptor<INetworkManagementEventObserver> networkObserver =
Felipe Lemeef134662016-08-10 14:46:39 -0700370 ArgumentCaptor.forClass(INetworkManagementEventObserver.class);
371 verify(mNetworkManager).registerObserver(networkObserver.capture());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700372 mNetworkObserver = networkObserver.getValue();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700373
374 NetworkPolicy defaultPolicy = mService.buildDefaultMobilePolicy(0, "");
375 mDefaultWarningBytes = defaultPolicy.warningBytes;
376 mDefaultLimitBytes = defaultPolicy.limitBytes;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700377 }
378
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700379 @After
380 public void removeFiles() throws Exception {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700381 for (File file : mPolicyDir.listFiles()) {
382 file.delete();
383 }
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700384 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700385
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700386 @After
387 public void unregisterLocalServices() throws Exception {
388 // Registered by NetworkPolicyManagerService's constructor.
Felipe Lemeef134662016-08-10 14:46:39 -0700389 LocalServices.removeServiceForTest(NetworkPolicyManagerInternal.class);
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700390
391 // Added in registerLocalServices()
392 LocalServices.removeServiceForTest(ActivityManagerInternal.class);
393 LocalServices.removeServiceForTest(PowerManagerInternal.class);
394 LocalServices.removeServiceForTest(DeviceIdleController.LocalService.class);
395 LocalServices.removeServiceForTest(UsageStatsManagerInternal.class);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700396 }
397
Jeff Sharkey53313d72017-07-13 16:47:32 -0600398 @After
399 public void resetClock() throws Exception {
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600400 RecurrenceRule.sClock = Clock.systemDefaultZone();
Jeff Sharkey53313d72017-07-13 16:47:32 -0600401 }
402
Felipe Lemee88729d2016-08-17 16:43:01 -0700403 @Test
Felipe Leme3d3308d2016-08-23 17:41:47 -0700404 public void testTurnRestrictBackgroundOn() throws Exception {
405 assertRestrictBackgroundOff(); // Sanity check.
406 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
407 setRestrictBackground(true);
408 assertRestrictBackgroundChangedReceived(futureIntent, null);
409 }
410
411 @Test
412 @NetPolicyXml("restrict-background-on.xml")
413 public void testTurnRestrictBackgroundOff() throws Exception {
414 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700415 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700416 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
417 setRestrictBackground(false);
418 assertRestrictBackgroundChangedReceived(futureIntent, null);
419 }
420
421 /**
422 * Adds whitelist when restrict background is on - app should receive an intent.
423 */
424 @Test
425 @NetPolicyXml("restrict-background-on.xml")
426 public void testAddRestrictBackgroundWhitelist_restrictBackgroundOn() throws Exception {
427 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700428 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700429 addRestrictBackgroundWhitelist(true);
430 }
431
432 /**
433 * Adds whitelist when restrict background is off - app should not receive an intent.
434 */
435 @Test
436 public void testAddRestrictBackgroundWhitelist_restrictBackgroundOff() throws Exception {
437 assertRestrictBackgroundOff(); // Sanity check.
438 addRestrictBackgroundWhitelist(false);
439 }
440
441 private void addRestrictBackgroundWhitelist(boolean expectIntent) throws Exception {
Felipe Leme57e3d312016-08-23 14:42:52 -0700442 // Sanity checks.
443 assertWhitelistUids();
444 assertUidPolicy(UID_A, POLICY_NONE);
445
Felipe Leme3d3308d2016-08-23 17:41:47 -0700446 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700447 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700448
Felipe Leme57e3d312016-08-23 14:42:52 -0700449 mService.setUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700450
451 assertWhitelistUids(UID_A);
Felipe Leme57e3d312016-08-23 14:42:52 -0700452 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700453 mPolicyListener.waitAndVerify()
454 .onUidPoliciesChanged(APP_ID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700455 if (expectIntent) {
456 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
457 } else {
458 futureIntent.assertNotReceived();
459 }
460 }
461
462 /**
463 * Removes whitelist when restrict background is on - app should receive an intent.
464 */
465 @Test
466 @NetPolicyXml("uidA-whitelisted-restrict-background-on.xml")
467 public void testRemoveRestrictBackgroundWhitelist_restrictBackgroundOn() throws Exception {
468 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700469 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700470 removeRestrictBackgroundWhitelist(true);
471 }
472
473 /**
474 * Removes whitelist when restrict background is off - app should not receive an intent.
475 */
476 @Test
477 @NetPolicyXml("uidA-whitelisted-restrict-background-off.xml")
478 public void testRemoveRestrictBackgroundWhitelist_restrictBackgroundOff() throws Exception {
479 assertRestrictBackgroundOff(); // Sanity check.
480 removeRestrictBackgroundWhitelist(false);
481 }
482
jackqdyulei29c82ab2017-03-10 14:09:16 -0800483 @Test
484 public void testLowPowerModeObserver_ListenersRegistered()
485 throws Exception {
486 PowerManagerInternal pmInternal = LocalServices.getService(PowerManagerInternal.class);
487
488 verify(pmInternal, atLeast(2)).registerLowPowerModeObserver(any());
489 }
490
491 @Test
492 public void updateRestrictBackgroundByLowPowerMode_RestrictOnBeforeBsm_RestrictOnAfterBsm()
493 throws Exception {
494 setRestrictBackground(true);
495 PowerSaveState stateOn = new PowerSaveState.Builder()
496 .setGlobalBatterySaverEnabled(true)
497 .setBatterySaverEnabled(false)
498 .build();
499 mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
500
501 // RestrictBackground should be on even though battery saver want to turn it off
502 assertThat(mService.getRestrictBackground()).isTrue();
503
504 PowerSaveState stateOff = new PowerSaveState.Builder()
505 .setGlobalBatterySaverEnabled(false)
506 .setBatterySaverEnabled(false)
507 .build();
508 mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
509
510 // RestrictBackground should be on, following its previous state
511 assertThat(mService.getRestrictBackground()).isTrue();
512 }
513
514 @Test
515 public void updateRestrictBackgroundByLowPowerMode_RestrictOffBeforeBsm_RestrictOffAfterBsm()
516 throws Exception {
517 setRestrictBackground(false);
518 PowerSaveState stateOn = new PowerSaveState.Builder()
519 .setGlobalBatterySaverEnabled(true)
520 .setBatterySaverEnabled(true)
521 .build();
522
523 doReturn(true).when(mNetworkManager).setDataSaverModeEnabled(true);
524 mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
525
526 // RestrictBackground should be turned on because of battery saver
527 assertThat(mService.getRestrictBackground()).isTrue();
528
529 PowerSaveState stateOff = new PowerSaveState.Builder()
530 .setGlobalBatterySaverEnabled(false)
531 .setBatterySaverEnabled(false)
532 .build();
533 mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
534
535 // RestrictBackground should be off, following its previous state
536 assertThat(mService.getRestrictBackground()).isFalse();
537 }
538
539 @Test
540 public void updateRestrictBackgroundByLowPowerMode_StatusChangedInBsm_DoNotRestore()
541 throws Exception {
542 setRestrictBackground(true);
543 PowerSaveState stateOn = new PowerSaveState.Builder()
544 .setGlobalBatterySaverEnabled(true)
545 .setBatterySaverEnabled(true)
546 .build();
547 mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
548
549 // RestrictBackground should still be on
550 assertThat(mService.getRestrictBackground()).isTrue();
551
552 // User turns off RestrictBackground manually
553 setRestrictBackground(false);
554 PowerSaveState stateOff = new PowerSaveState.Builder().setBatterySaverEnabled(
555 false).build();
556 mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
557
558 // RestrictBackground should be off because user changes it manually
559 assertThat(mService.getRestrictBackground()).isFalse();
560 }
561
Felipe Leme3d3308d2016-08-23 17:41:47 -0700562 private void removeRestrictBackgroundWhitelist(boolean expectIntent) throws Exception {
Felipe Leme57e3d312016-08-23 14:42:52 -0700563 // Sanity checks.
564 assertWhitelistUids(UID_A);
565 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
566
Felipe Leme3d3308d2016-08-23 17:41:47 -0700567 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700568 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700569
Felipe Leme57e3d312016-08-23 14:42:52 -0700570 mService.setUidPolicy(UID_A, POLICY_NONE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700571
572 assertWhitelistUids();
Felipe Leme57e3d312016-08-23 14:42:52 -0700573 assertUidPolicy(UID_A, POLICY_NONE);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700574 mPolicyListener.waitAndVerify().onUidPoliciesChanged(APP_ID_A, POLICY_NONE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700575 if (expectIntent) {
576 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
577 } else {
578 futureIntent.assertNotReceived();
579 }
580 }
581
582 /**
Felipe Leme57e3d312016-08-23 14:42:52 -0700583 * Adds blacklist when restrict background is on - app should not receive an intent.
Felipe Leme3d3308d2016-08-23 17:41:47 -0700584 */
585 @Test
586 @NetPolicyXml("restrict-background-on.xml")
587 public void testAddRestrictBackgroundBlacklist_restrictBackgroundOn() throws Exception {
588 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700589 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme57e3d312016-08-23 14:42:52 -0700590 addRestrictBackgroundBlacklist(false);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700591 }
592
593 /**
594 * Adds blacklist when restrict background is off - app should receive an intent.
595 */
596 @Test
597 public void testAddRestrictBackgroundBlacklist_restrictBackgroundOff() throws Exception {
598 assertRestrictBackgroundOff(); // Sanity check.
599 addRestrictBackgroundBlacklist(true);
600 }
601
602 private void addRestrictBackgroundBlacklist(boolean expectIntent) throws Exception {
603 assertUidPolicy(UID_A, POLICY_NONE); // Sanity check.
604 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700605 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700606
607 mService.setUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
608
609 assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700610 mPolicyListener.waitAndVerify()
611 .onUidPoliciesChanged(APP_ID_A, POLICY_REJECT_METERED_BACKGROUND);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700612 if (expectIntent) {
613 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
614 } else {
615 futureIntent.assertNotReceived();
616 }
617 }
618
619 /**
Felipe Leme57e3d312016-08-23 14:42:52 -0700620 * Removes blacklist when restrict background is on - app should not receive an intent.
Felipe Leme3d3308d2016-08-23 17:41:47 -0700621 */
622 @Test
623 @NetPolicyXml("uidA-blacklisted-restrict-background-on.xml")
624 public void testRemoveRestrictBackgroundBlacklist_restrictBackgroundOn() throws Exception {
625 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700626 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme57e3d312016-08-23 14:42:52 -0700627 removeRestrictBackgroundBlacklist(false);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700628 }
629
630 /**
631 * Removes blacklist when restrict background is off - app should receive an intent.
632 */
633 @Test
634 @NetPolicyXml("uidA-blacklisted-restrict-background-off.xml")
635 public void testRemoveRestrictBackgroundBlacklist_restrictBackgroundOff() throws Exception {
636 assertRestrictBackgroundOff(); // Sanity check.
637 removeRestrictBackgroundBlacklist(true);
638 }
639
640 private void removeRestrictBackgroundBlacklist(boolean expectIntent) throws Exception {
641 assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND); // Sanity check.
642 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700643 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700644
645 mService.setUidPolicy(UID_A, POLICY_NONE);
646
647 assertUidPolicy(UID_A, POLICY_NONE);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700648 mPolicyListener.waitAndVerify()
649 .onUidPoliciesChanged(APP_ID_A, POLICY_NONE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700650 if (expectIntent) {
651 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
652 } else {
653 futureIntent.assertNotReceived();
654 }
655 }
656
Felipe Leme51a63642016-08-30 12:15:09 -0700657 @Test
Felipe Lemec08ecdf2016-08-30 12:57:35 -0700658 @NetPolicyXml("uidA-blacklisted-restrict-background-on.xml")
Felipe Leme3d3308d2016-08-23 17:41:47 -0700659 public void testBlacklistedAppIsNotNotifiedWhenRestrictBackgroundIsOn() throws Exception {
660 // Sanity checks.
661 assertRestrictBackgroundOn();
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700662 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700663 assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
664
665 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
666 setRestrictBackground(true);
667 futureIntent.assertNotReceived();
668 }
669
Felipe Leme51a63642016-08-30 12:15:09 -0700670 @Test
Felipe Lemec08ecdf2016-08-30 12:57:35 -0700671 @NetPolicyXml("uidA-whitelisted-restrict-background-on.xml")
Felipe Leme3d3308d2016-08-23 17:41:47 -0700672 public void testWhitelistedAppIsNotNotifiedWhenRestrictBackgroundIsOn() throws Exception {
673 // Sanity checks.
Felipe Lemec08ecdf2016-08-30 12:57:35 -0700674 assertRestrictBackgroundOn();
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700675 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700676 assertWhitelistUids(UID_A);
677
678 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
679 setRestrictBackground(true);
680 futureIntent.assertNotReceived();
681 }
682
Andreas Gampe84d156b2016-09-03 10:50:38 -0700683 @Test
Felipe Leme57e3d312016-08-23 14:42:52 -0700684 @NetPolicyXml("uidA-whitelisted-restrict-background-on.xml")
685 public void testWhitelistedAppIsNotifiedWhenBlacklisted() throws Exception {
686 // Sanity checks.
687 assertRestrictBackgroundOn();
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700688 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme57e3d312016-08-23 14:42:52 -0700689 assertWhitelistUids(UID_A);
690
691 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
692 mService.setUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
693 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
694 }
695
Felipe Leme3d3308d2016-08-23 17:41:47 -0700696 @Test
Felipe Lemee88729d2016-08-17 16:43:01 -0700697 @NetPolicyXml("restrict-background-lists-whitelist-format.xml")
698 public void testRestrictBackgroundLists_whitelistFormat() throws Exception {
Felipe Leme46b451f2016-08-19 08:46:17 -0700699 restrictBackgroundListsTest();
700 }
701
702 @Test
703 @NetPolicyXml("restrict-background-lists-uid-policy-format.xml")
704 public void testRestrictBackgroundLists_uidPolicyFormat() throws Exception {
705 restrictBackgroundListsTest();
706 }
707
708 private void restrictBackgroundListsTest() throws Exception {
Felipe Leme8546a442016-08-23 09:38:20 -0700709 // UIds that are whitelisted.
Felipe Leme46b451f2016-08-19 08:46:17 -0700710 assertWhitelistUids(UID_A, UID_B, UID_C);
711 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
712 assertUidPolicy(UID_B, POLICY_ALLOW_METERED_BACKGROUND);
713 assertUidPolicy(UID_C, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Lemee88729d2016-08-17 16:43:01 -0700714
Felipe Leme8546a442016-08-23 09:38:20 -0700715 // UIDs that are blacklisted.
Felipe Lemee88729d2016-08-17 16:43:01 -0700716 assertUidPolicy(UID_D, POLICY_NONE);
717 assertUidPolicy(UID_E, POLICY_REJECT_METERED_BACKGROUND);
Felipe Leme8546a442016-08-23 09:38:20 -0700718
719 // UIDS that have legacy policies.
Felipe Leme46b451f2016-08-19 08:46:17 -0700720 assertUidPolicy(UID_F, 2); // POLICY_ALLOW_BACKGROUND_BATTERY_SAVE
721
722 // Remove whitelist.
Felipe Leme57e3d312016-08-23 14:42:52 -0700723 mService.setUidPolicy(UID_A, POLICY_NONE);
Felipe Leme46b451f2016-08-19 08:46:17 -0700724 assertUidPolicy(UID_A, POLICY_NONE);
725 assertWhitelistUids(UID_B, UID_C);
726
727 // Add whitelist when blacklisted.
Felipe Leme57e3d312016-08-23 14:42:52 -0700728 mService.setUidPolicy(UID_E, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme46b451f2016-08-19 08:46:17 -0700729 assertUidPolicy(UID_E, POLICY_ALLOW_METERED_BACKGROUND);
730 assertWhitelistUids(UID_B, UID_C, UID_E);
731
732 // Add blacklist when whitelisted.
733 mService.setUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND);
734 assertUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND);
735 assertWhitelistUids(UID_C, UID_E);
736 }
737
738 /**
739 * Tests scenario where an UID had {@code restrict-background} and {@code uid-policy} tags.
740 */
741 @Test
742 @NetPolicyXml("restrict-background-lists-mixed-format.xml")
743 public void testRestrictBackgroundLists_mixedFormat() throws Exception {
744 assertWhitelistUids(UID_A, UID_C, UID_D);
745 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme57e3d312016-08-23 14:42:52 -0700746 assertUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND); // Blacklist prevails.
Felipe Leme46b451f2016-08-19 08:46:17 -0700747 assertUidPolicy(UID_C, (POLICY_ALLOW_METERED_BACKGROUND | 2));
748 assertUidPolicy(UID_D, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Lemee88729d2016-08-17 16:43:01 -0700749 }
750
Felipe Leme6f51a0a2016-08-24 15:11:51 -0700751 @Test
752 @NetPolicyXml("uids-with-mixed-policies.xml")
753 public void testGetUidsWithPolicy() throws Exception {
Felipe Leme03f90292016-09-08 18:10:32 -0700754 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_NONE));
Felipe Leme6f51a0a2016-08-24 15:11:51 -0700755 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND),
756 UID_B, UID_D);
757 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_ALLOW_METERED_BACKGROUND),
758 UID_E, UID_F);
759 // Legacy (POLICY_ALLOW_BACKGROUND_BATTERY_SAVE)
760 assertContainsInAnyOrder(mService.getUidsWithPolicy(2),
761 UID_C, UID_D, UID_F);
762 }
763
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700764 // NOTE: testPolicyChangeTriggersListener() is too superficial, they
Felipe Lemeef134662016-08-10 14:46:39 -0700765 // don't check for side-effects (like calls to NetworkManagementService) neither cover all
766 // different modes (Data Saver, Battery Saver, Doze, App idle, etc...).
767 // These scenarios are extensively tested on CTS' HostsideRestrictBackgroundNetworkTests.
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700768 @Test
Felipe Lemeef134662016-08-10 14:46:39 -0700769 public void testUidForeground() throws Exception {
770 // push all uids into background
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700771 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE, 0);
772 callOnUidStateChanged(UID_B, ActivityManager.PROCESS_STATE_SERVICE, 0);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700773 assertFalse(mService.isUidForeground(UID_A));
774 assertFalse(mService.isUidForeground(UID_B));
775
Felipe Lemeef134662016-08-10 14:46:39 -0700776 // push one of the uids into foreground
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700777 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_TOP, 0);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700778 assertTrue(mService.isUidForeground(UID_A));
779 assertFalse(mService.isUidForeground(UID_B));
780
781 // and swap another uid into foreground
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700782 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE, 0);
783 callOnUidStateChanged(UID_B, ActivityManager.PROCESS_STATE_TOP, 0);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700784 assertFalse(mService.isUidForeground(UID_A));
785 assertTrue(mService.isUidForeground(UID_B));
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700786 }
787
Jeff Sharkey53313d72017-07-13 16:47:32 -0600788 private static long computeLastCycleBoundary(long currentTime, NetworkPolicy policy) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600789 RecurrenceRule.sClock = Clock.fixed(Instant.ofEpochMilli(currentTime),
790 ZoneId.systemDefault());
791 final Iterator<Pair<ZonedDateTime, ZonedDateTime>> it = policy.cycleIterator();
Jeff Sharkey53313d72017-07-13 16:47:32 -0600792 while (it.hasNext()) {
793 final Pair<ZonedDateTime, ZonedDateTime> cycle = it.next();
794 if (cycle.first.toInstant().toEpochMilli() < currentTime) {
795 return cycle.first.toInstant().toEpochMilli();
796 }
797 }
798 throw new IllegalStateException(
799 "Failed to find current cycle for " + policy + " at " + currentTime);
800 }
801
802 private static long computeNextCycleBoundary(long currentTime, NetworkPolicy policy) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600803 RecurrenceRule.sClock = Clock.fixed(Instant.ofEpochMilli(currentTime),
804 ZoneId.systemDefault());
805 return policy.cycleIterator().next().second.toInstant().toEpochMilli();
Jeff Sharkey53313d72017-07-13 16:47:32 -0600806 }
807
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700808 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700809 public void testLastCycleBoundaryThisMonth() throws Exception {
810 // assume cycle day of "5th", which should be in same month
811 final long currentTime = parseTime("2007-11-14T00:00:00.000Z");
812 final long expectedCycle = parseTime("2007-11-05T00:00:00.000Z");
813
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700814 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800815 sTemplateWifi, 5, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700816 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700817 assertTimeEquals(expectedCycle, actualCycle);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700818 }
819
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700820 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700821 public void testLastCycleBoundaryLastMonth() throws Exception {
822 // assume cycle day of "20th", which should be in last month
823 final long currentTime = parseTime("2007-11-14T00:00:00.000Z");
824 final long expectedCycle = parseTime("2007-10-20T00:00:00.000Z");
825
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700826 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800827 sTemplateWifi, 20, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700828 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700829 assertTimeEquals(expectedCycle, actualCycle);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700830 }
831
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700832 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700833 public void testLastCycleBoundaryThisMonthFebruary() throws Exception {
834 // assume cycle day of "30th" in february; should go to january
835 final long currentTime = parseTime("2007-02-14T00:00:00.000Z");
836 final long expectedCycle = parseTime("2007-01-30T00:00:00.000Z");
837
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700838 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800839 sTemplateWifi, 30, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700840 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700841 assertTimeEquals(expectedCycle, actualCycle);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700842 }
843
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700844 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700845 public void testLastCycleBoundaryLastMonthFebruary() throws Exception {
846 // assume cycle day of "30th" in february, which should clamp
847 final long currentTime = parseTime("2007-03-14T00:00:00.000Z");
Jeff Sharkey53313d72017-07-13 16:47:32 -0600848 final long expectedCycle = parseTime("2007-02-28T23:59:59.999Z");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700849
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700850 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800851 sTemplateWifi, 30, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700852 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700853 assertTimeEquals(expectedCycle, actualCycle);
854 }
855
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700856 @Test
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800857 public void testCycleBoundaryLeapYear() throws Exception {
858 final NetworkPolicy policy = new NetworkPolicy(
859 sTemplateWifi, 29, TIMEZONE_UTC, 1024L, 1024L, false);
860
861 assertTimeEquals(parseTime("2012-01-29T00:00:00.000Z"),
862 computeNextCycleBoundary(parseTime("2012-01-14T00:00:00.000Z"), policy));
863 assertTimeEquals(parseTime("2012-02-29T00:00:00.000Z"),
864 computeNextCycleBoundary(parseTime("2012-02-14T00:00:00.000Z"), policy));
865 assertTimeEquals(parseTime("2012-02-29T00:00:00.000Z"),
866 computeLastCycleBoundary(parseTime("2012-03-14T00:00:00.000Z"), policy));
867 assertTimeEquals(parseTime("2012-03-29T00:00:00.000Z"),
868 computeNextCycleBoundary(parseTime("2012-03-14T00:00:00.000Z"), policy));
869
870 assertTimeEquals(parseTime("2007-01-29T00:00:00.000Z"),
871 computeNextCycleBoundary(parseTime("2007-01-14T00:00:00.000Z"), policy));
Jeff Sharkey53313d72017-07-13 16:47:32 -0600872 assertTimeEquals(parseTime("2007-02-28T23:59:59.999Z"),
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800873 computeNextCycleBoundary(parseTime("2007-02-14T00:00:00.000Z"), policy));
Jeff Sharkey53313d72017-07-13 16:47:32 -0600874 assertTimeEquals(parseTime("2007-02-28T23:59:59.999Z"),
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800875 computeLastCycleBoundary(parseTime("2007-03-14T00:00:00.000Z"), policy));
876 assertTimeEquals(parseTime("2007-03-29T00:00:00.000Z"),
877 computeNextCycleBoundary(parseTime("2007-03-14T00:00:00.000Z"), policy));
878 }
879
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700880 @Test
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800881 public void testNextCycleTimezoneAfterUtc() throws Exception {
882 // US/Central is UTC-6
883 final NetworkPolicy policy = new NetworkPolicy(
884 sTemplateWifi, 10, "US/Central", 1024L, 1024L, false);
885 assertTimeEquals(parseTime("2012-01-10T06:00:00.000Z"),
886 computeNextCycleBoundary(parseTime("2012-01-05T00:00:00.000Z"), policy));
887 }
888
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700889 @Test
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800890 public void testNextCycleTimezoneBeforeUtc() throws Exception {
891 // Israel is UTC+2
892 final NetworkPolicy policy = new NetworkPolicy(
893 sTemplateWifi, 10, "Israel", 1024L, 1024L, false);
894 assertTimeEquals(parseTime("2012-01-09T22:00:00.000Z"),
895 computeNextCycleBoundary(parseTime("2012-01-05T00:00:00.000Z"), policy));
896 }
897
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700898 @Test
Jeff Sharkey15399052013-01-15 14:15:53 -0800899 public void testCycleTodayJanuary() throws Exception {
900 final NetworkPolicy policy = new NetworkPolicy(
901 sTemplateWifi, 14, "US/Pacific", 1024L, 1024L, false);
902
903 assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
904 computeNextCycleBoundary(parseTime("2013-01-13T23:59:59.000-08:00"), policy));
905 assertTimeEquals(parseTime("2013-02-14T00:00:00.000-08:00"),
906 computeNextCycleBoundary(parseTime("2013-01-14T00:00:01.000-08:00"), policy));
907 assertTimeEquals(parseTime("2013-02-14T00:00:00.000-08:00"),
908 computeNextCycleBoundary(parseTime("2013-01-14T15:11:00.000-08:00"), policy));
909
910 assertTimeEquals(parseTime("2012-12-14T00:00:00.000-08:00"),
911 computeLastCycleBoundary(parseTime("2013-01-13T23:59:59.000-08:00"), policy));
912 assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
913 computeLastCycleBoundary(parseTime("2013-01-14T00:00:01.000-08:00"), policy));
914 assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
915 computeLastCycleBoundary(parseTime("2013-01-14T15:11:00.000-08:00"), policy));
916 }
917
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700918 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700919 public void testNetworkPolicyAppliedCycleLastMonth() throws Exception {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700920 NetworkState[] state = null;
921 NetworkStats stats = null;
922
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700923 final int CYCLE_DAY = 15;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600924 final long NOW = parseTime("2007-03-10T00:00Z");
925 final long CYCLE_START = parseTime("2007-02-15T00:00Z");
926 final long CYCLE_END = parseTime("2007-03-15T00:00Z");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700927
Jeff Sharkey53313d72017-07-13 16:47:32 -0600928 setCurrentTimeMillis(NOW);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700929
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700930 // first, pretend that wifi network comes online. no policy active,
931 // which means we shouldn't push limit to interface.
932 state = new NetworkState[] { buildWifi() };
Felipe Lemeef134662016-08-10 14:46:39 -0700933 when(mConnManager.getAllNetworkState()).thenReturn(state);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700934 expectCurrentTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700935
Felipe Lemeef134662016-08-10 14:46:39 -0700936 mPolicyListener.expect().onMeteredIfacesChanged(any());
Erik Klinef851d6d2015-04-20 16:03:48 +0900937 mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION));
Felipe Lemeef134662016-08-10 14:46:39 -0700938 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(any());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700939
940 // now change cycle to be on 15th, and test in early march, to verify we
941 // pick cycle day in previous month.
Felipe Lemeef134662016-08-10 14:46:39 -0700942 when(mConnManager.getAllNetworkState()).thenReturn(state);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700943 expectCurrentTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700944
945 // pretend that 512 bytes total have happened
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700946 stats = new NetworkStats(getElapsedRealtime(), 1)
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700947 .addIfaceValues(TEST_IFACE, 256L, 2L, 256L, 2L);
Jeff Sharkey53313d72017-07-13 16:47:32 -0600948 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, CYCLE_START, CYCLE_END))
Felipe Lemeef134662016-08-10 14:46:39 -0700949 .thenReturn(stats.getTotalBytes());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700950
Felipe Lemeef134662016-08-10 14:46:39 -0700951 mPolicyListener.expect().onMeteredIfacesChanged(any());
Jeff Sharkey163e6442011-10-31 16:37:52 -0700952 setNetworkPolicies(new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800953 sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, 1 * MB_IN_BYTES, 2 * MB_IN_BYTES, false));
Felipe Lemeef134662016-08-10 14:46:39 -0700954 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
955
956 // TODO: consider making strongly ordered mock
957 verifyPolicyDataEnable(TYPE_WIFI, true);
958 verifyRemoveInterfaceQuota(TEST_IFACE);
959 verifySetInterfaceQuota(TEST_IFACE, (2 * MB_IN_BYTES) - 512);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700960 }
961
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700962 @Test
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700963 public void testOverWarningLimitNotification() throws Exception {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700964 NetworkState[] state = null;
965 NetworkStats stats = null;
Felipe Lemeef134662016-08-10 14:46:39 -0700966 Future<String> tagFuture = null;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700967
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700968 final int CYCLE_DAY = 15;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600969 final long NOW = parseTime("2007-03-10T00:00Z");
970 final long CYCLE_START = parseTime("2007-02-15T00:00Z");
971 final long CYCLE_END = parseTime("2007-03-15T00:00Z");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700972
Jeff Sharkey53313d72017-07-13 16:47:32 -0600973 setCurrentTimeMillis(NOW);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700974
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700975 // assign wifi policy
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700976 state = new NetworkState[] {};
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700977 stats = new NetworkStats(getElapsedRealtime(), 1)
978 .addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700979
980 {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700981 expectCurrentTime();
Felipe Lemeef134662016-08-10 14:46:39 -0700982 when(mConnManager.getAllNetworkState()).thenReturn(state);
Jeff Sharkey53313d72017-07-13 16:47:32 -0600983 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, CYCLE_START,
984 CYCLE_END)).thenReturn(stats.getTotalBytes());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700985
Felipe Lemeef134662016-08-10 14:46:39 -0700986 mPolicyListener.expect().onMeteredIfacesChanged(any());
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800987 setNetworkPolicies(new NetworkPolicy(sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, 1
988 * MB_IN_BYTES, 2 * MB_IN_BYTES, false));
Felipe Lemeef134662016-08-10 14:46:39 -0700989 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(any());
990 verifyPolicyDataEnable(TYPE_WIFI, true);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700991 }
992
993 // bring up wifi network
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700994 incrementCurrentTime(MINUTE_IN_MILLIS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700995 state = new NetworkState[] { buildWifi() };
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700996 stats = new NetworkStats(getElapsedRealtime(), 1)
997 .addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700998
999 {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001000 expectCurrentTime();
Felipe Lemeef134662016-08-10 14:46:39 -07001001 when(mConnManager.getAllNetworkState()).thenReturn(state);
Jeff Sharkey53313d72017-07-13 16:47:32 -06001002 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, CYCLE_START,
1003 CYCLE_END)).thenReturn(stats.getTotalBytes());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001004
Felipe Lemeef134662016-08-10 14:46:39 -07001005 mPolicyListener.expect().onMeteredIfacesChanged(any());
Erik Klinef851d6d2015-04-20 16:03:48 +09001006 mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION));
Felipe Lemeef134662016-08-10 14:46:39 -07001007 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
1008
1009 verifyPolicyDataEnable(TYPE_WIFI, true);
1010 verifyRemoveInterfaceQuota(TEST_IFACE);
1011 verifySetInterfaceQuota(TEST_IFACE, 2 * MB_IN_BYTES);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001012 }
1013
1014 // go over warning, which should kick notification
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001015 incrementCurrentTime(MINUTE_IN_MILLIS);
1016 stats = new NetworkStats(getElapsedRealtime(), 1)
Jeff Sharkey163e6442011-10-31 16:37:52 -07001017 .addIfaceValues(TEST_IFACE, 1536 * KB_IN_BYTES, 15L, 0L, 0L);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001018
1019 {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001020 expectCurrentTime();
Jeff Sharkey53313d72017-07-13 16:47:32 -06001021 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, CYCLE_START,
1022 CYCLE_END)).thenReturn(stats.getTotalBytes());
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001023 tagFuture = expectEnqueueNotification();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001024
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001025 mNetworkObserver.limitReached(null, TEST_IFACE);
Felipe Lemeef134662016-08-10 14:46:39 -07001026
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001027 assertNotificationType(TYPE_WARNING, tagFuture.get());
Felipe Lemeef134662016-08-10 14:46:39 -07001028 verifyPolicyDataEnable(TYPE_WIFI, true);
1029
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001030 }
1031
1032 // go over limit, which should kick notification and dialog
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001033 incrementCurrentTime(MINUTE_IN_MILLIS);
1034 stats = new NetworkStats(getElapsedRealtime(), 1)
Jeff Sharkey163e6442011-10-31 16:37:52 -07001035 .addIfaceValues(TEST_IFACE, 5 * MB_IN_BYTES, 512L, 0L, 0L);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001036
1037 {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001038 expectCurrentTime();
Jeff Sharkey53313d72017-07-13 16:47:32 -06001039 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, CYCLE_START,
1040 CYCLE_END)).thenReturn(stats.getTotalBytes());
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001041 tagFuture = expectEnqueueNotification();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001042
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001043 mNetworkObserver.limitReached(null, TEST_IFACE);
Felipe Lemeef134662016-08-10 14:46:39 -07001044
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001045 assertNotificationType(TYPE_LIMIT, tagFuture.get());
Felipe Lemeef134662016-08-10 14:46:39 -07001046 verifyPolicyDataEnable(TYPE_WIFI, false);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001047 }
1048
1049 // now snooze policy, which should remove quota
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001050 incrementCurrentTime(MINUTE_IN_MILLIS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001051
1052 {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001053 expectCurrentTime();
Felipe Lemeef134662016-08-10 14:46:39 -07001054 when(mConnManager.getAllNetworkState()).thenReturn(state);
Jeff Sharkey53313d72017-07-13 16:47:32 -06001055 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, CYCLE_START,
1056 CYCLE_END)).thenReturn(stats.getTotalBytes());
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001057 tagFuture = expectEnqueueNotification();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001058
Felipe Lemeef134662016-08-10 14:46:39 -07001059 mPolicyListener.expect().onMeteredIfacesChanged(any());
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001060 mService.snoozeLimit(sTemplateWifi);
Felipe Lemeef134662016-08-10 14:46:39 -07001061 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
1062
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001063 assertNotificationType(TYPE_LIMIT_SNOOZED, tagFuture.get());
Felipe Lemeef134662016-08-10 14:46:39 -07001064 // snoozed interface still has high quota so background data is
1065 // still restricted.
1066 verifyRemoveInterfaceQuota(TEST_IFACE);
1067 verifySetInterfaceQuota(TEST_IFACE, Long.MAX_VALUE);
1068 verifyPolicyDataEnable(TYPE_WIFI, true);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001069 }
1070 }
1071
Felipe Leme9f27e7a2016-08-12 15:19:40 -07001072 @Test
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001073 public void testMeteredNetworkWithoutLimit() throws Exception {
1074 NetworkState[] state = null;
1075 NetworkStats stats = null;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001076
1077 final long TIME_FEB_15 = 1171497600000L;
1078 final long TIME_MAR_10 = 1173484800000L;
1079 final int CYCLE_DAY = 15;
1080
1081 setCurrentTimeMillis(TIME_MAR_10);
1082
1083 // bring up wifi network with metered policy
1084 state = new NetworkState[] { buildWifi() };
1085 stats = new NetworkStats(getElapsedRealtime(), 1)
1086 .addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L);
1087
1088 {
1089 expectCurrentTime();
Felipe Lemeef134662016-08-10 14:46:39 -07001090 when(mConnManager.getAllNetworkState()).thenReturn(state);
1091 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15,
1092 currentTimeMillis())).thenReturn(stats.getTotalBytes());
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001093
Felipe Lemeef134662016-08-10 14:46:39 -07001094 mPolicyListener.expect().onMeteredIfacesChanged(any());
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001095 setNetworkPolicies(new NetworkPolicy(
1096 sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, WARNING_DISABLED, LIMIT_DISABLED,
1097 true));
Felipe Lemeef134662016-08-10 14:46:39 -07001098 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
1099
1100 verifyPolicyDataEnable(TYPE_WIFI, true);
1101 verifyRemoveInterfaceQuota(TEST_IFACE);
1102 verifySetInterfaceQuota(TEST_IFACE, Long.MAX_VALUE);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001103 }
1104 }
1105
Sudheer Shankae7361852017-03-07 11:51:46 -08001106 @Test
1107 public void testOnUidStateChanged_notifyAMS() throws Exception {
1108 final long procStateSeq = 222;
Sudheer Shankaed25ce62017-03-29 20:46:30 -07001109 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE, procStateSeq);
Sudheer Shankae7361852017-03-07 11:51:46 -08001110 verify(mActivityManagerInternal).notifyNetworkPolicyRulesUpdated(UID_A, procStateSeq);
1111
1112 final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
1113 final IndentingPrintWriter writer = new IndentingPrintWriter(
1114 new PrintWriter(outputStream), " ");
1115 mService.mObservedHistory.dumpUL(writer);
1116 writer.flush();
1117 assertEquals(ProcStateSeqHistory.getString(UID_A, procStateSeq),
1118 outputStream.toString().trim());
1119 }
1120
Sudheer Shankaed25ce62017-03-29 20:46:30 -07001121 private void callOnUidStateChanged(int uid, int procState, long procStateSeq)
1122 throws Exception {
1123 mUidObserver.onUidStateChanged(uid, procState, procStateSeq);
1124 final CountDownLatch latch = new CountDownLatch(1);
1125 mService.mUidEventHandler.post(() -> {
1126 latch.countDown();
1127 });
1128 latch.await(2, TimeUnit.SECONDS);
1129 }
1130
Sudheer Shankae7361852017-03-07 11:51:46 -08001131 @Test
1132 public void testProcStateHistory() {
1133 // Verify dump works correctly with no elements added.
1134 verifyProcStateHistoryDump(0);
1135
1136 // Add items upto half of the max capacity and verify that dump works correctly.
1137 verifyProcStateHistoryDump(MAX_PROC_STATE_SEQ_HISTORY / 2);
1138
1139 // Add items upto the max capacity and verify that dump works correctly.
1140 verifyProcStateHistoryDump(MAX_PROC_STATE_SEQ_HISTORY);
1141
1142 // Add more items than max capacity and verify that dump works correctly.
1143 verifyProcStateHistoryDump(MAX_PROC_STATE_SEQ_HISTORY + MAX_PROC_STATE_SEQ_HISTORY / 2);
1144
1145 }
1146
1147 private void verifyProcStateHistoryDump(int count) {
1148 final ProcStateSeqHistory history = new ProcStateSeqHistory(MAX_PROC_STATE_SEQ_HISTORY);
1149 final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
1150 final IndentingPrintWriter writer = new IndentingPrintWriter(
1151 new PrintWriter(outputStream), " ");
1152
1153 if (count == 0) {
1154 // Verify with no uid info written to history.
1155 history.dumpUL(writer);
1156 writer.flush();
1157 assertEquals("When no uid info is there, dump should contain NONE",
1158 "NONE", outputStream.toString().trim());
1159 return;
1160 }
1161
1162 int uid = 111;
1163 long procStateSeq = 222;
1164 // Add count items and verify dump works correctly.
1165 for (int i = 0; i < count; ++i) {
1166 uid++;
1167 procStateSeq++;
1168 history.addProcStateSeqUL(uid, procStateSeq);
1169 }
1170 history.dumpUL(writer);
1171 writer.flush();
1172 final String[] uidsDump = outputStream.toString().split(LINE_SEPARATOR);
1173 // Dump will have at most MAX_PROC_STATE_SEQ_HISTORY items.
1174 final int expectedCount = (count < MAX_PROC_STATE_SEQ_HISTORY)
1175 ? count : MAX_PROC_STATE_SEQ_HISTORY;
1176 assertEquals(expectedCount, uidsDump.length);
1177 for (int i = 0; i < expectedCount; ++i) {
1178 assertEquals(ProcStateSeqHistory.getString(uid, procStateSeq), uidsDump[i]);
1179 uid--;
1180 procStateSeq--;
1181 }
1182 }
1183
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001184 private void assertCycleDayAsExpected(PersistableBundle config, int carrierCycleDay,
1185 boolean expectValid) {
1186 config.putInt(KEY_MONTHLY_DATA_CYCLE_DAY_INT, carrierCycleDay);
1187 int actualCycleDay = mService.getCycleDayFromCarrierConfig(config,
1188 INVALID_CARRIER_CONFIG_VALUE);
1189 if (expectValid) {
1190 assertEquals(carrierCycleDay, actualCycleDay);
1191 } else {
1192 // INVALID_CARRIER_CONFIG_VALUE is returned for invalid values
1193 assertEquals(INVALID_CARRIER_CONFIG_VALUE, actualCycleDay);
1194 }
1195 }
1196
1197 @Test
1198 public void testGetCycleDayFromCarrierConfig() {
1199 PersistableBundle config = CarrierConfigManager.getDefaultConfig();
1200 final Calendar cal = Calendar.getInstance();
1201 int actualCycleDay;
1202
1203 config.putInt(KEY_MONTHLY_DATA_CYCLE_DAY_INT, DATA_CYCLE_USE_PLATFORM_DEFAULT);
1204 actualCycleDay = mService.getCycleDayFromCarrierConfig(config, DEFAULT_CYCLE_DAY);
1205 assertEquals(DEFAULT_CYCLE_DAY, actualCycleDay);
1206
1207 // null config returns a default value
1208 actualCycleDay = mService.getCycleDayFromCarrierConfig(null, DEFAULT_CYCLE_DAY);
1209 assertEquals(DEFAULT_CYCLE_DAY, actualCycleDay);
1210
1211 // Sane, non-default values
1212 assertCycleDayAsExpected(config, 1, true);
1213 assertCycleDayAsExpected(config, cal.getMaximum(Calendar.DAY_OF_MONTH), true);
1214 assertCycleDayAsExpected(config, cal.getMinimum(Calendar.DAY_OF_MONTH), true);
1215
1216 // Invalid values
1217 assertCycleDayAsExpected(config, 0, false);
1218 assertCycleDayAsExpected(config, DATA_CYCLE_THRESHOLD_DISABLED, false);
1219 assertCycleDayAsExpected(config, cal.getMaximum(Calendar.DAY_OF_MONTH) + 1, false);
1220 assertCycleDayAsExpected(config, cal.getMinimum(Calendar.DAY_OF_MONTH) - 5, false);
1221 }
1222
1223 private void assertWarningBytesAsExpected(PersistableBundle config, long carrierWarningBytes,
1224 long expected) {
1225 config.putLong(KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, carrierWarningBytes);
1226 long actualWarning = mService.getWarningBytesFromCarrierConfig(config,
1227 INVALID_CARRIER_CONFIG_VALUE);
1228 assertEquals(expected, actualWarning);
1229 }
1230
1231 @Test
1232 public void testGetWarningBytesFromCarrierConfig() {
1233 PersistableBundle config = CarrierConfigManager.getDefaultConfig();
1234 long actualWarningBytes;
1235
1236 assertWarningBytesAsExpected(config, DATA_CYCLE_USE_PLATFORM_DEFAULT,
1237 mDefaultWarningBytes);
1238 assertWarningBytesAsExpected(config, DATA_CYCLE_THRESHOLD_DISABLED, WARNING_DISABLED);
1239 assertWarningBytesAsExpected(config, 0, 0);
1240 // not a valid value
1241 assertWarningBytesAsExpected(config, -1000, INVALID_CARRIER_CONFIG_VALUE);
1242
1243 // null config returns a default value
1244 actualWarningBytes = mService.getWarningBytesFromCarrierConfig(null, mDefaultWarningBytes);
1245 assertEquals(mDefaultWarningBytes, actualWarningBytes);
1246 }
1247
1248 private void assertLimitBytesAsExpected(PersistableBundle config, long carrierWarningBytes,
1249 long expected) {
1250 config.putLong(KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG, carrierWarningBytes);
1251 long actualWarning = mService.getLimitBytesFromCarrierConfig(config,
1252 INVALID_CARRIER_CONFIG_VALUE);
1253 assertEquals(expected, actualWarning);
1254 }
1255
1256 @Test
1257 public void testGetLimitBytesFromCarrierConfig() {
1258 PersistableBundle config = CarrierConfigManager.getDefaultConfig();
1259 long actualLimitBytes;
1260
1261 assertLimitBytesAsExpected(config, DATA_CYCLE_USE_PLATFORM_DEFAULT,
1262 mDefaultLimitBytes);
1263 assertLimitBytesAsExpected(config, DATA_CYCLE_THRESHOLD_DISABLED, LIMIT_DISABLED);
1264 assertLimitBytesAsExpected(config, 0, 0);
1265 // not a valid value
1266 assertLimitBytesAsExpected(config, -1000, INVALID_CARRIER_CONFIG_VALUE);
1267
1268 // null config returns a default value
1269 actualLimitBytes = mService.getWarningBytesFromCarrierConfig(null, mDefaultLimitBytes);
1270 assertEquals(mDefaultLimitBytes, actualLimitBytes);
1271 }
1272
1273 private PersistableBundle setupUpdateMobilePolicyCycleTests() throws RemoteException {
1274 when(mConnManager.getAllNetworkState()).thenReturn(new NetworkState[0]);
1275 when(mSubscriptionManager.getActiveSubscriptionIdList()).thenReturn(new int[]{FAKE_SUB_ID});
1276 when(mTelephonyManager.getSubscriberId(FAKE_SUB_ID)).thenReturn(FAKE_SUBSCRIBER_ID);
1277 PersistableBundle bundle = CarrierConfigManager.getDefaultConfig();
1278 when(mCarrierConfigManager.getConfigForSubId(FAKE_SUB_ID)).thenReturn(bundle);
1279 setNetworkPolicies(buildDefaultFakeMobilePolicy());
1280 return bundle;
1281 }
1282
1283 @Test
1284 public void testUpdateMobilePolicyCycleWithNullConfig() throws RemoteException {
1285 when(mConnManager.getAllNetworkState()).thenReturn(new NetworkState[0]);
1286 when(mSubscriptionManager.getActiveSubscriptionIdList()).thenReturn(new int[]{FAKE_SUB_ID});
1287 when(mTelephonyManager.getSubscriberId(FAKE_SUB_ID)).thenReturn(FAKE_SUBSCRIBER_ID);
1288 when(mCarrierConfigManager.getConfigForSubId(FAKE_SUB_ID)).thenReturn(null);
1289 setNetworkPolicies(buildDefaultFakeMobilePolicy());
1290 // smoke test to make sure no errors are raised
1291 mServiceContext.sendBroadcast(
1292 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1293 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1294 );
1295 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1296 true);
1297 }
1298
1299 @Test
1300 public void testUpdateMobilePolicyCycleWithInvalidConfig() throws RemoteException {
1301 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1302 // Test with an invalid CarrierConfig, there should be no changes or crashes.
1303 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, -100);
1304 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, -100);
1305 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG, -100);
1306 mServiceContext.sendBroadcast(
1307 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1308 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1309 );
1310
1311 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1312 true);
1313 }
1314
1315 @Test
1316 public void testUpdateMobilePolicyCycleWithDefaultConfig() throws RemoteException {
1317 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1318 // Test that we respect the platform values when told to
1319 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT,
1320 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1321 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1322 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1323 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1324 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1325 mServiceContext.sendBroadcast(
1326 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1327 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1328 );
1329
1330 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1331 true);
1332 }
1333
1334 @Test
1335 public void testUpdateMobilePolicyCycleWithUserOverrides() throws RemoteException {
1336 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1337
1338 // inferred = false implies that a user manually modified this policy.
1339 NetworkPolicy policy = buildDefaultFakeMobilePolicy();
1340 policy.inferred = false;
1341 setNetworkPolicies(policy);
1342
1343 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1344 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, 9999);
1345 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1346 DATA_CYCLE_THRESHOLD_DISABLED);
1347 mServiceContext.sendBroadcast(
1348 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1349 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1350 );
1351
1352 // The policy still shouldn't change, because we don't want to overwrite user settings.
1353 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1354 false);
1355 }
1356
1357 @Test
1358 public void testUpdateMobilePolicyCycleUpdatesDataCycle() throws RemoteException {
1359 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1360
1361 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1362 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, 9999);
1363 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG, 9999);
1364 mServiceContext.sendBroadcast(
1365 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1366 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1367 );
1368
1369 assertNetworkPolicyEquals(31, 9999, 9999, true);
1370 }
1371
1372 @Test
1373 public void testUpdateMobilePolicyCycleDisableThresholds() throws RemoteException {
1374 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1375
1376 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1377 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1378 DATA_CYCLE_THRESHOLD_DISABLED);
1379 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1380 DATA_CYCLE_THRESHOLD_DISABLED);
1381 mServiceContext.sendBroadcast(
1382 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1383 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1384 );
1385
1386 assertNetworkPolicyEquals(31, WARNING_DISABLED, LIMIT_DISABLED, true);
1387 }
1388
1389 @Test
1390 public void testUpdateMobilePolicyCycleRevertsToDefault() throws RemoteException {
1391 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1392
1393 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1394 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1395 DATA_CYCLE_THRESHOLD_DISABLED);
1396 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1397 DATA_CYCLE_THRESHOLD_DISABLED);
1398 mServiceContext.sendBroadcast(
1399 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1400 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1401 );
1402 assertNetworkPolicyEquals(31, WARNING_DISABLED, LIMIT_DISABLED, true);
1403
1404 // If the user switches carriers to one that doesn't use a CarrierConfig, we should revert
1405 // to the default data limit and warning. The cycle date doesn't need to revert as it's
1406 // arbitrary anyways.
1407 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT,
1408 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1409 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1410 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1411 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1412 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1413 mServiceContext.sendBroadcast(
1414 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1415 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1416 );
1417
1418 assertNetworkPolicyEquals(31, mDefaultWarningBytes, mDefaultLimitBytes,
1419 true);
1420 }
1421
1422 private NetworkPolicy buildDefaultFakeMobilePolicy() {
1423 NetworkPolicy p = mService.buildDefaultMobilePolicy(FAKE_SUB_ID, FAKE_SUBSCRIBER_ID);
1424 // set a deterministic cycle date
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001425 p.cycleRule = new RecurrenceRule(
1426 p.cycleRule.start.withDayOfMonth(DEFAULT_CYCLE_DAY),
1427 p.cycleRule.end, Period.ofMonths(1));
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001428 return p;
1429 }
1430
1431 private static NetworkPolicy buildFakeMobilePolicy(int cycleDay, long warningBytes,
1432 long limitBytes, boolean inferred){
1433 final NetworkTemplate template = buildTemplateMobileAll(FAKE_SUBSCRIBER_ID);
Sudheer Shankaed25ce62017-03-29 20:46:30 -07001434 return new NetworkPolicy(template, cycleDay, new Time().timezone, warningBytes,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001435 limitBytes, SNOOZE_NEVER, SNOOZE_NEVER, true, inferred);
1436 }
1437
1438 private void assertNetworkPolicyEquals(int expectedCycleDay, long expectedWarningBytes,
1439 long expectedLimitBytes, boolean expectedInferred) {
1440 NetworkPolicy[] policies = mService.getNetworkPolicies(
1441 mServiceContext.getOpPackageName());
1442 assertEquals("Unexpected number of network policies", 1, policies.length);
1443 NetworkPolicy actualPolicy = policies[0];
1444 NetworkPolicy expectedPolicy = buildFakeMobilePolicy(expectedCycleDay, expectedWarningBytes,
1445 expectedLimitBytes, expectedInferred);
1446 assertEquals(expectedPolicy, actualPolicy);
1447 }
1448
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001449 private static long parseTime(String time) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06001450 return ZonedDateTime.parse(time).toInstant().toEpochMilli();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001451 }
1452
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07001453 private void setNetworkPolicies(NetworkPolicy... policies) {
1454 mService.setNetworkPolicies(policies);
1455 }
1456
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001457 private static NetworkState buildWifi() {
1458 final NetworkInfo info = new NetworkInfo(TYPE_WIFI, 0, null, null);
1459 info.setDetailedState(DetailedState.CONNECTED, null, null);
1460 final LinkProperties prop = new LinkProperties();
1461 prop.setInterfaceName(TEST_IFACE);
Stephen Chena1c92b72017-02-06 13:18:11 -08001462 final NetworkCapabilities networkCapabilities = new NetworkCapabilities();
1463 return new NetworkState(info, prop, networkCapabilities, null, null, TEST_SSID);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001464 }
1465
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001466 private void expectCurrentTime() throws Exception {
Felipe Lemeef134662016-08-10 14:46:39 -07001467 when(mTime.forceRefresh()).thenReturn(false);
1468 when(mTime.hasCache()).thenReturn(true);
1469 when(mTime.currentTimeMillis()).thenReturn(currentTimeMillis());
1470 when(mTime.getCacheAge()).thenReturn(0L);
1471 when(mTime.getCacheCertainty()).thenReturn(0L);
Jeff Sharkey2ef2aeb2011-06-15 11:01:31 -07001472 }
1473
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001474 private Future<String> expectEnqueueNotification() throws Exception {
Felipe Lemeef134662016-08-10 14:46:39 -07001475 final FutureAnswer<String> futureAnswer = new FutureAnswer<String>(2);
1476 doAnswer(futureAnswer).when(mNotifManager).enqueueNotificationWithTag(
1477 anyString(), anyString(), anyString() /* capture here (index 2)*/,
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001478 anyInt(), isA(Notification.class), anyInt());
Felipe Lemeef134662016-08-10 14:46:39 -07001479 return futureAnswer;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001480 }
1481
Felipe Leme3d3308d2016-08-23 17:41:47 -07001482 private void expectHasInternetPermission(int uid, boolean hasIt) throws Exception {
1483 when(mIpm.checkUidPermission(Manifest.permission.INTERNET, uid)).thenReturn(
1484 hasIt ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED);
1485 }
1486
Felipe Lemeef134662016-08-10 14:46:39 -07001487 private void verifySetInterfaceQuota(String iface, long quotaBytes) throws Exception {
1488 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001489 }
1490
Felipe Lemeef134662016-08-10 14:46:39 -07001491 private void verifyRemoveInterfaceQuota(String iface) throws Exception {
1492 verify(mNetworkManager, atLeastOnce()).removeInterfaceQuota(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001493 }
1494
Felipe Lemeef134662016-08-10 14:46:39 -07001495 private Future<Void> verifyPolicyDataEnable(int type, boolean enabled) throws Exception {
Jeff Sharkey32566012014-12-02 18:30:14 -08001496 // TODO: bring back this test
1497 return null;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001498 }
1499
Felipe Lemeef134662016-08-10 14:46:39 -07001500 private void verifyAdvisePersistThreshold() throws Exception {
1501 verify(mStatsService).advisePersistThreshold(anyLong());
Jeff Sharkey0cf6de02012-05-04 15:03:30 -07001502 }
1503
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001504 private static class TestAbstractFuture<T> extends AbstractFuture<T> {
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001505 @Override
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001506 public T get() throws InterruptedException, ExecutionException {
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001507 try {
1508 return get(5, TimeUnit.SECONDS);
1509 } catch (TimeoutException e) {
1510 throw new RuntimeException(e);
1511 }
1512 }
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001513 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001514
Felipe Lemeef134662016-08-10 14:46:39 -07001515 private static class FutureAnswer<T> extends TestAbstractFuture<T> implements Answer<Void> {
1516 private final int index;
1517
1518 FutureAnswer(int index) {
1519 this.index = index;
1520 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001521 @Override
Felipe Lemeef134662016-08-10 14:46:39 -07001522 public Void answer(InvocationOnMock invocation) throws Throwable {
1523 @SuppressWarnings("unchecked")
1524 T captured = (T) invocation.getArguments()[index];
1525 set(captured);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001526 return null;
1527 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001528 }
1529
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -07001530 private static void assertTimeEquals(long expected, long actual) {
1531 if (expected != actual) {
1532 fail("expected " + formatTime(expected) + " but was actually " + formatTime(actual));
1533 }
1534 }
1535
1536 private static String formatTime(long millis) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06001537 return Instant.ofEpochMilli(millis) + " [" + millis + "]";
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -07001538 }
1539
1540 private static void assertEqualsFuzzy(long expected, long actual, long fuzzy) {
1541 final long low = expected - fuzzy;
1542 final long high = expected + fuzzy;
1543 if (actual < low || actual > high) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06001544 fail("value " + formatTime(actual) + " is outside [" + formatTime(low) + ","
1545 + formatTime(high) + "]");
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -07001546 }
1547 }
1548
1549 private static void assertUnique(LinkedHashSet<Long> seen, Long value) {
1550 if (!seen.add(value)) {
1551 fail("found duplicate time " + value + " in series " + seen.toString());
1552 }
1553 }
1554
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001555 private static void assertNotificationType(int expected, String actualTag) {
Felipe Lemeef134662016-08-10 14:46:39 -07001556 assertEquals("notification type mismatch for '" + actualTag +"'",
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001557 Integer.toString(expected), actualTag.substring(actualTag.lastIndexOf(':') + 1));
1558 }
1559
Felipe Lemee88729d2016-08-17 16:43:01 -07001560 private void assertUidPolicy(int uid, int expected) {
1561 final int actual = mService.getUidPolicy(uid);
1562 if (expected != actual) {
1563 fail("Wrong policy for UID " + uid + ": expected " + uidPoliciesToString(expected)
1564 + ", actual " + uidPoliciesToString(actual));
1565 }
1566 }
1567
Felipe Leme46b451f2016-08-19 08:46:17 -07001568 private void assertWhitelistUids(int... uids) {
Felipe Leme57e3d312016-08-23 14:42:52 -07001569 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_ALLOW_METERED_BACKGROUND), uids);
Felipe Leme46b451f2016-08-19 08:46:17 -07001570 }
1571
Felipe Leme3d3308d2016-08-23 17:41:47 -07001572 private void assertRestrictBackgroundOn() throws Exception {
1573 assertTrue("restrictBackground should be set", mService.getRestrictBackground());
1574 }
1575
1576 private void assertRestrictBackgroundOff() throws Exception {
1577 assertFalse("restrictBackground should not be set", mService.getRestrictBackground());
1578 }
1579
1580 private FutureIntent newRestrictBackgroundChangedFuture() {
1581 return mServiceContext
1582 .nextBroadcastIntent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
1583 }
1584
1585 private void assertRestrictBackgroundChangedReceived(Future<Intent> future,
1586 String expectedPackage) throws Exception {
1587 final String action = ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED;
1588 final Intent intent = future.get(5, TimeUnit.SECONDS);
1589 assertNotNull("Didn't get a " + action + "intent in 5 seconds");
1590 assertEquals("Wrong package on " + action + " intent", expectedPackage, intent.getPackage());
1591 }
1592
Felipe Lemee88729d2016-08-17 16:43:01 -07001593 // TODO: replace by Truth, Hamcrest, or a similar tool.
1594 private void assertContainsInAnyOrder(int[] actual, int...expected) {
1595 final StringBuilder errors = new StringBuilder();
1596 if (actual.length != expected.length) {
1597 errors.append("\tsize does not match\n");
1598 }
1599 final List<Integer> actualList =
1600 Arrays.stream(actual).boxed().collect(Collectors.<Integer>toList());
1601 final List<Integer> expectedList =
1602 Arrays.stream(expected).boxed().collect(Collectors.<Integer>toList());
1603 if (!actualList.containsAll(expectedList)) {
1604 errors.append("\tmissing elements on actual list\n");
1605 }
1606 if (!expectedList.containsAll(actualList)) {
1607 errors.append("\tmissing elements on expected list\n");
1608 }
1609 if (errors.length() > 0) {
1610 fail("assertContainsInAnyOrder(expected=" + Arrays.toString(expected)
1611 + ", actual=" + Arrays.toString(actual) +") failed: \n" + errors);
1612 }
1613 }
1614
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001615 private long getElapsedRealtime() {
1616 return mElapsedRealtime;
1617 }
1618
1619 private void setCurrentTimeMillis(long currentTimeMillis) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001620 RecurrenceRule.sClock = Clock.fixed(Instant.ofEpochMilli(currentTimeMillis),
1621 ZoneId.systemDefault());
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001622 mStartTime = currentTimeMillis;
1623 mElapsedRealtime = 0L;
1624 }
1625
1626 private long currentTimeMillis() {
1627 return mStartTime + mElapsedRealtime;
1628 }
1629
1630 private void incrementCurrentTime(long duration) {
1631 mElapsedRealtime += duration;
1632 }
1633
Felipe Leme3d3308d2016-08-23 17:41:47 -07001634 private FutureIntent mRestrictBackgroundChanged;
1635
1636 private void setRestrictBackground(boolean flag) throws Exception {
1637 // Must set expectation, otherwise NMPS will reset value to previous one.
jackqdyulei29c82ab2017-03-10 14:09:16 -08001638 doReturn(true).when(mNetworkManager).setDataSaverModeEnabled(flag);
Felipe Leme3d3308d2016-08-23 17:41:47 -07001639 mService.setRestrictBackground(flag);
1640 // Sanity check.
1641 assertEquals("restrictBackground not set", flag, mService.getRestrictBackground());
1642 }
1643
Felipe Lemeef134662016-08-10 14:46:39 -07001644 /**
1645 * Creates a mock and registers it to {@link LocalServices}.
1646 */
Felipe Leme9f27e7a2016-08-12 15:19:40 -07001647 private static <T> T addLocalServiceMock(Class<T> clazz) {
Felipe Lemeef134662016-08-10 14:46:39 -07001648 final T mock = mock(clazz);
Felipe Lemeef134662016-08-10 14:46:39 -07001649 LocalServices.addService(clazz, mock);
Felipe Lemeef134662016-08-10 14:46:39 -07001650 return mock;
1651 }
1652
1653 /**
Felipe Lemeef134662016-08-10 14:46:39 -07001654 * Custom Mockito answer used to verify async {@link INetworkPolicyListener} calls.
1655 *
1656 * <p>Typical usage:
1657 * <pre><code>
1658 * mPolicyListener.expect().someCallback(any());
1659 * // do something on objects under test
1660 * mPolicyListener.waitAndVerify().someCallback(eq(expectedValue));
1661 * </code></pre>
1662 */
1663 final class NetworkPolicyListenerAnswer implements Answer<Void> {
1664 private CountDownLatch latch;
1665 private final INetworkPolicyListener listener;
1666
1667 NetworkPolicyListenerAnswer(NetworkPolicyManagerService service) {
1668 this.listener = mock(INetworkPolicyListener.class);
1669 // RemoteCallbackList needs a binder to use as key
1670 when(listener.asBinder()).thenReturn(new Binder());
1671 service.registerListener(listener);
1672 }
1673
1674 @Override
1675 public Void answer(InvocationOnMock invocation) throws Throwable {
1676 Log.d(TAG,"counting down on answer: " + invocation);
1677 latch.countDown();
1678 return null;
1679 }
1680
1681 INetworkPolicyListener expect() {
1682 assertNull("expect() called before waitAndVerify()", latch);
1683 latch = new CountDownLatch(1);
1684 return doAnswer(this).when(listener);
1685 }
1686
1687 INetworkPolicyListener waitAndVerify() {
1688 assertNotNull("waitAndVerify() called before expect()", latch);
1689 try {
1690 assertTrue("callback not called in 5 seconds", latch.await(5, TimeUnit.SECONDS));
1691 } catch (InterruptedException e) {
1692 fail("Thread interrupted before callback called");
1693 } finally {
1694 latch = null;
1695 }
1696 return verify(listener, atLeastOnce());
1697 }
Felipe Leme3d3308d2016-08-23 17:41:47 -07001698
1699 INetworkPolicyListener verifyNotCalled() {
1700 return verify(listener, never());
1701 }
1702
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001703 }
Felipe Lemee88729d2016-08-17 16:43:01 -07001704
1705 private void setNetpolicyXml(Context context) throws Exception {
1706 mPolicyDir = context.getFilesDir();
1707 if (mPolicyDir.exists()) {
1708 IoUtils.deleteContents(mPolicyDir);
1709 }
1710 if (!TextUtils.isEmpty(mNetpolicyXml)) {
1711 final String assetPath = NETPOLICY_DIR + "/" + mNetpolicyXml;
1712 final File netConfigFile = new File(mPolicyDir, "netpolicy.xml");
1713 Log.d(TAG, "Creating " + netConfigFile + " from asset " + assetPath);
1714 try (final InputStream in = context.getResources().getAssets().open(assetPath);
1715 final OutputStream out = new FileOutputStream(netConfigFile)) {
1716 Streams.copy(in, out);
1717 }
1718 }
1719 }
1720
1721 /**
1722 * Annotation used to define the relative path of the {@code netpolicy.xml} file.
1723 */
1724 @Retention(RetentionPolicy.RUNTIME)
1725 @Target(ElementType.METHOD)
1726 public @interface NetPolicyXml {
1727
1728 public String value() default "";
1729
1730 }
1731
1732 /**
1733 * Rule used to set {@code mNetPolicyXml} according to the {@link NetPolicyXml} annotation.
1734 */
1735 public static class NetPolicyMethodRule implements MethodRule {
1736
1737 @Override
1738 public Statement apply(Statement base, FrameworkMethod method, Object target) {
1739 for (Annotation annotation : method.getAnnotations()) {
1740 if ((annotation instanceof NetPolicyXml)) {
1741 final String path = ((NetPolicyXml) annotation).value();
1742 if (!path.isEmpty()) {
1743 ((NetworkPolicyManagerServiceTest) target).mNetpolicyXml = path;
1744 break;
1745 }
1746 }
1747 }
1748 return base;
1749 }
1750 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001751}