blob: fbcccf0fec2a3ac72624ccf8afb90f5f12aa6939 [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
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070040import static com.android.server.net.NetworkPolicyManagerService.TYPE_LIMIT;
41import static com.android.server.net.NetworkPolicyManagerService.TYPE_LIMIT_SNOOZED;
42import static com.android.server.net.NetworkPolicyManagerService.TYPE_WARNING;
Jeff Sharkey53313d72017-07-13 16:47:32 -060043
jackqdyulei29c82ab2017-03-10 14:09:16 -080044import static com.google.common.truth.Truth.assertThat;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070045
Felipe Leme9f27e7a2016-08-12 15:19:40 -070046import static org.junit.Assert.assertEquals;
47import static org.junit.Assert.assertFalse;
48import static org.junit.Assert.assertNotNull;
49import static org.junit.Assert.assertNull;
50import static org.junit.Assert.assertTrue;
51import static org.junit.Assert.fail;
Jeff Sharkey53313d72017-07-13 16:47:32 -060052import static org.mockito.ArgumentMatchers.any;
Sudheer Shanka543339f2017-07-28 15:18:07 -070053import static org.mockito.ArgumentMatchers.anyBoolean;
Jeff Sharkey53313d72017-07-13 16:47:32 -060054import 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;
63import static org.mockito.Mockito.mock;
Felipe Leme3d3308d2016-08-23 17:41:47 -070064import static org.mockito.Mockito.never;
Felipe Lemeef134662016-08-10 14:46:39 -070065import static org.mockito.Mockito.verify;
66import static org.mockito.Mockito.when;
67
Felipe Leme3d3308d2016-08-23 17:41:47 -070068import android.Manifest;
Felipe Lemeef134662016-08-10 14:46:39 -070069import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -080070import android.app.ActivityManagerInternal;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070071import android.app.IActivityManager;
Jeff Sharkey2ef2aeb2011-06-15 11:01:31 -070072import android.app.INotificationManager;
Felipe Lemeef134662016-08-10 14:46:39 -070073import android.app.IUidObserver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070074import android.app.Notification;
Felipe Lemeef134662016-08-10 14:46:39 -070075import android.app.usage.UsageStatsManagerInternal;
76import android.content.Context;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070077import android.content.Intent;
Felipe Lemeef134662016-08-10 14:46:39 -070078import android.content.pm.ApplicationInfo;
Felipe Leme3d3308d2016-08-23 17:41:47 -070079import android.content.pm.IPackageManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070080import android.content.pm.PackageInfo;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070081import android.content.pm.PackageManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070082import android.content.pm.Signature;
Felipe Leme3d3308d2016-08-23 17:41:47 -070083import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070084import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070085import android.net.INetworkManagementEventObserver;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070086import android.net.INetworkPolicyListener;
Jeff Sharkey75279902011-05-24 18:39:45 -070087import android.net.INetworkStatsService;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070088import android.net.LinkProperties;
Stephen Chena1c92b72017-02-06 13:18:11 -080089import android.net.NetworkCapabilities;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070090import android.net.NetworkInfo;
91import android.net.NetworkInfo.DetailedState;
92import android.net.NetworkPolicy;
93import android.net.NetworkState;
94import android.net.NetworkStats;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070095import android.net.NetworkTemplate;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070096import android.os.Binder;
Ashish Sharma50fd36d2011-06-15 19:34:53 -070097import android.os.INetworkManagementService;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070098import android.os.PersistableBundle;
Felipe Lemeef134662016-08-10 14:46:39 -070099import android.os.PowerManagerInternal;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800100import android.os.PowerSaveState;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700101import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700102import android.os.UserHandle;
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700103import android.support.test.InstrumentationRegistry;
Felipe Leme3d3308d2016-08-23 17:41:47 -0700104import android.support.test.filters.MediumTest;
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700105import android.support.test.runner.AndroidJUnit4;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700106import android.telephony.CarrierConfigManager;
107import android.telephony.SubscriptionManager;
108import android.telephony.TelephonyManager;
Felipe Lemee88729d2016-08-17 16:43:01 -0700109import android.text.TextUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700110import android.text.format.Time;
Felipe Lemeef134662016-08-10 14:46:39 -0700111import android.util.Log;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600112import android.util.Pair;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600113import android.util.RecurrenceRule;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700114import android.util.TrustedTime;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700115
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700116import com.android.internal.telephony.PhoneConstants;
Lorenzo Colitti281a17c2016-10-28 12:56:03 +0900117import com.android.internal.util.test.BroadcastInterceptingContext;
118import com.android.internal.util.test.BroadcastInterceptingContext.FutureIntent;
Felipe Lemeef134662016-08-10 14:46:39 -0700119import com.android.server.net.NetworkPolicyManagerInternal;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700120import com.android.server.net.NetworkPolicyManagerService;
Felipe Lemeef134662016-08-10 14:46:39 -0700121
122import libcore.io.IoUtils;
Felipe Lemee88729d2016-08-17 16:43:01 -0700123import libcore.io.Streams;
Felipe Lemeef134662016-08-10 14:46:39 -0700124
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700125import com.google.common.util.concurrent.AbstractFuture;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700126
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700127import org.junit.After;
128import org.junit.Before;
Sudheer Shankac1adfd82017-11-29 10:53:12 -0800129import org.junit.Ignore;
Felipe Lemee88729d2016-08-17 16:43:01 -0700130import org.junit.Rule;
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700131import org.junit.Test;
Felipe Lemee88729d2016-08-17 16:43:01 -0700132import org.junit.rules.MethodRule;
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700133import org.junit.runner.RunWith;
Felipe Lemee88729d2016-08-17 16:43:01 -0700134import org.junit.runners.model.FrameworkMethod;
135import org.junit.runners.model.Statement;
Felipe Lemeef134662016-08-10 14:46:39 -0700136import org.mockito.ArgumentCaptor;
137import org.mockito.Mock;
138import org.mockito.MockitoAnnotations;
139import org.mockito.invocation.InvocationOnMock;
140import org.mockito.stubbing.Answer;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700141
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700142import java.io.File;
Felipe Lemee88729d2016-08-17 16:43:01 -0700143import java.io.FileOutputStream;
144import java.io.InputStream;
145import java.io.OutputStream;
146import java.lang.annotation.Annotation;
147import java.lang.annotation.ElementType;
148import java.lang.annotation.Retention;
149import java.lang.annotation.RetentionPolicy;
150import java.lang.annotation.Target;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600151import java.time.Clock;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600152import java.time.Instant;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600153import java.time.Period;
154import java.time.ZoneId;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600155import java.time.ZonedDateTime;
Felipe Lemee88729d2016-08-17 16:43:01 -0700156import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700157import java.util.Calendar;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600158import java.util.Iterator;
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700159import java.util.LinkedHashSet;
Felipe Lemeef134662016-08-10 14:46:39 -0700160import java.util.List;
161import java.util.concurrent.CountDownLatch;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700162import java.util.concurrent.ExecutionException;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700163import java.util.concurrent.Future;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700164import java.util.concurrent.TimeUnit;
165import java.util.concurrent.TimeoutException;
Felipe Lemee88729d2016-08-17 16:43:01 -0700166import java.util.stream.Collectors;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700167
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700168/**
169 * Tests for {@link NetworkPolicyManagerService}.
Felipe Lemeb8d572e2016-12-05 13:41:43 -0800170 *
171 * <p>Typical usage:
172 *
173 * <pre><code>
174 m -j32 FrameworksServicesTests && adb install -r -g \
175 ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk && \
176 adb shell am instrument -e class "com.android.server.NetworkPolicyManagerServiceTest" -w \
177 "com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner"
178 * </code></pre>
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700179 */
Sudheer Shankac1adfd82017-11-29 10:53:12 -0800180@Ignore
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700181@RunWith(AndroidJUnit4.class)
Felipe Leme3d3308d2016-08-23 17:41:47 -0700182@MediumTest
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700183public class NetworkPolicyManagerServiceTest {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700184 private static final String TAG = "NetworkPolicyManagerServiceTest";
185
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700186 private static final long TEST_START = 1194220800000L;
187 private static final String TEST_IFACE = "test0";
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700188 private static final String TEST_SSID = "AndroidAP";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700189
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700190 private static NetworkTemplate sTemplateWifi = NetworkTemplate.buildTemplateWifi(TEST_SSID);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700191
Felipe Lemee88729d2016-08-17 16:43:01 -0700192 /**
193 * Path on assets where files used by {@link NetPolicyXml} are located.
194 */
195 private static final String NETPOLICY_DIR = "NetworkPolicyManagerServiceTest/netpolicy";
196
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700197 private BroadcastInterceptingContext mServiceContext;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700198 private File mPolicyDir;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700199
Felipe Lemee88729d2016-08-17 16:43:01 -0700200 /**
201 * Relative path of the XML file that will be used as {@code netpolicy.xml}.
202 *
203 * <p>Typically set through a {@link NetPolicyXml} annotation in the test method.
204 */
205 private String mNetpolicyXml;
206
Felipe Lemeef134662016-08-10 14:46:39 -0700207 private @Mock IActivityManager mActivityManager;
208 private @Mock INetworkStatsService mStatsService;
209 private @Mock INetworkManagementService mNetworkManager;
210 private @Mock TrustedTime mTime;
211 private @Mock IConnectivityManager mConnManager;
212 private @Mock INotificationManager mNotifManager;
Felipe Lemeef134662016-08-10 14:46:39 -0700213 private @Mock PackageManager mPackageManager;
Felipe Leme3d3308d2016-08-23 17:41:47 -0700214 private @Mock IPackageManager mIpm;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700215 private @Mock SubscriptionManager mSubscriptionManager;
216 private @Mock CarrierConfigManager mCarrierConfigManager;
217 private @Mock TelephonyManager mTelephonyManager;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700218
Sudheer Shankae7361852017-03-07 11:51:46 -0800219 private static ActivityManagerInternal mActivityManagerInternal;
220
Felipe Lemeef134662016-08-10 14:46:39 -0700221 private IUidObserver mUidObserver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700222 private INetworkManagementEventObserver mNetworkObserver;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700223
Felipe Lemeef134662016-08-10 14:46:39 -0700224 private NetworkPolicyListenerAnswer mPolicyListener;
225 private NetworkPolicyManagerService mService;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700226
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700227 /**
228 * In some of the tests while initializing NetworkPolicyManagerService,
229 * ACTION_RESTRICT_BACKGROUND_CHANGED is broadcasted. This is for capturing that broadcast.
230 */
231 private FutureIntent mFutureIntent;
232
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700233 private long mStartTime;
234 private long mElapsedRealtime;
235
Jeff Sharkeycae04a22012-03-22 15:18:52 -0700236 private static final int USER_ID = 0;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700237 private static final int FAKE_SUB_ID = 3737373;
238 private static final String FAKE_SUBSCRIBER_ID = "FAKE_SUB_ID";
239 private static final int DEFAULT_CYCLE_DAY = 1;
240 private static final int INVALID_CARRIER_CONFIG_VALUE = -9999;
241 private long mDefaultWarningBytes; // filled in with the actual default before tests are run
242 private long mDefaultLimitBytes; // filled in with the actual default before tests are run
Jeff Sharkeycae04a22012-03-22 15:18:52 -0700243
Felipe Lemee88729d2016-08-17 16:43:01 -0700244 private static final int APP_ID_A = android.os.Process.FIRST_APPLICATION_UID + 4;
245 private static final int APP_ID_B = android.os.Process.FIRST_APPLICATION_UID + 8;
246 private static final int APP_ID_C = android.os.Process.FIRST_APPLICATION_UID + 15;
247 private static final int APP_ID_D = android.os.Process.FIRST_APPLICATION_UID + 16;
248 private static final int APP_ID_E = android.os.Process.FIRST_APPLICATION_UID + 23;
249 private static final int APP_ID_F = android.os.Process.FIRST_APPLICATION_UID + 42;
Jeff Sharkeycae04a22012-03-22 15:18:52 -0700250
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700251 private static final int UID_A = UserHandle.getUid(USER_ID, APP_ID_A);
252 private static final int UID_B = UserHandle.getUid(USER_ID, APP_ID_B);
Felipe Lemee88729d2016-08-17 16:43:01 -0700253 private static final int UID_C = UserHandle.getUid(USER_ID, APP_ID_C);
254 private static final int UID_D = UserHandle.getUid(USER_ID, APP_ID_D);
255 private static final int UID_E = UserHandle.getUid(USER_ID, APP_ID_E);
256 private static final int UID_F = UserHandle.getUid(USER_ID, APP_ID_F);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700257
Felipe Lemeef134662016-08-10 14:46:39 -0700258 private static final String PKG_NAME_A = "name.is.A,pkg.A";
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700259
Felipe Lemee88729d2016-08-17 16:43:01 -0700260 public final @Rule NetPolicyMethodRule mNetPolicyXmlRule = new NetPolicyMethodRule();
261
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700262 private void registerLocalServices() {
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700263 addLocalServiceMock(DeviceIdleController.LocalService.class);
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700264
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700265 final UsageStatsManagerInternal usageStats =
266 addLocalServiceMock(UsageStatsManagerInternal.class);
267 when(usageStats.getIdleUidsForUser(anyInt())).thenReturn(new int[]{});
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700268
Sudheer Shankae7361852017-03-07 11:51:46 -0800269 mActivityManagerInternal = addLocalServiceMock(ActivityManagerInternal.class);
jackqdyulei29c82ab2017-03-10 14:09:16 -0800270
271 final PowerSaveState state = new PowerSaveState.Builder()
272 .setBatterySaverEnabled(false).build();
273 final PowerManagerInternal pmInternal = addLocalServiceMock(PowerManagerInternal.class);
274 when(pmInternal.getLowPowerState(anyInt())).thenReturn(state);
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700275 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700276
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700277 @Before
278 public void callSystemReady() throws Exception {
Felipe Lemeef134662016-08-10 14:46:39 -0700279 MockitoAnnotations.initMocks(this);
280
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700281 final Context context = InstrumentationRegistry.getContext();
Felipe Lemeef134662016-08-10 14:46:39 -0700282
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700283 setCurrentTimeMillis(TEST_START);
284
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700285 registerLocalServices();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700286 // Intercept various broadcasts, and pretend that uids have packages.
287 // Also return mock service instances for a few critical services.
Felipe Lemeef134662016-08-10 14:46:39 -0700288 mServiceContext = new BroadcastInterceptingContext(context) {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700289 @Override
290 public PackageManager getPackageManager() {
Felipe Lemeef134662016-08-10 14:46:39 -0700291 return mPackageManager;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700292 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700293
294 @Override
295 public void startActivity(Intent intent) {
296 // ignored
297 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700298
299 @Override
300 public Object getSystemService(String name) {
301 switch (name) {
302 case Context.TELEPHONY_SUBSCRIPTION_SERVICE:
303 return mSubscriptionManager;
304 case Context.CARRIER_CONFIG_SERVICE:
305 return mCarrierConfigManager;
306 case Context.TELEPHONY_SERVICE:
307 return mTelephonyManager;
308 default:
309 return super.getSystemService(name);
310 }
311 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700312 };
313
Felipe Lemee88729d2016-08-17 16:43:01 -0700314 setNetpolicyXml(context);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700315
Felipe Lemeef134662016-08-10 14:46:39 -0700316 doAnswer(new Answer<Void>() {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700317
Felipe Lemeef134662016-08-10 14:46:39 -0700318 @Override
319 public Void answer(InvocationOnMock invocation) throws Throwable {
320 mUidObserver = (IUidObserver) invocation.getArguments()[0];
321 Log.d(TAG, "set mUidObserver to " + mUidObserver);
322 return null;
323 }
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800324 }).when(mActivityManager).registerUidObserver(any(), anyInt(),
Felipe Lemeb8d572e2016-12-05 13:41:43 -0800325 eq(ActivityManager.PROCESS_STATE_UNKNOWN), isNull(String.class));
Felipe Lemeef134662016-08-10 14:46:39 -0700326
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700327 mFutureIntent = newRestrictBackgroundChangedFuture();
Felipe Lemeef134662016-08-10 14:46:39 -0700328 mService = new NetworkPolicyManagerService(mServiceContext, mActivityManager, mStatsService,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700329 mNetworkManager, mIpm, mTime, mPolicyDir, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700330 mService.bindConnectivityManager(mConnManager);
Jeff Sharkey2ef2aeb2011-06-15 11:01:31 -0700331 mService.bindNotificationManager(mNotifManager);
Felipe Lemeef134662016-08-10 14:46:39 -0700332 mPolicyListener = new NetworkPolicyListenerAnswer(mService);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700333
Felipe Lemeef134662016-08-10 14:46:39 -0700334 // Sets some common expectations.
335 when(mPackageManager.getPackageInfo(anyString(), anyInt())).thenAnswer(
336 new Answer<PackageInfo>() {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700337
Felipe Lemeef134662016-08-10 14:46:39 -0700338 @Override
339 public PackageInfo answer(InvocationOnMock invocation) throws Throwable {
340 final String packageName = (String) invocation.getArguments()[0];
341 final PackageInfo info = new PackageInfo();
342 final Signature signature;
343 if ("android".equals(packageName)) {
344 signature = new Signature("F00D");
345 } else {
346 signature = new Signature("DEAD");
347 }
348 info.signatures = new Signature[] {
349 signature
350 };
351 return info;
352 }
353 });
354 when(mPackageManager.getApplicationInfoAsUser(anyString(), anyInt(), anyInt()))
355 .thenReturn(new ApplicationInfo());
356 when(mPackageManager.getPackagesForUid(UID_A)).thenReturn(new String[] {PKG_NAME_A});
Felipe Lemeef134662016-08-10 14:46:39 -0700357 when(mNetworkManager.isBandwidthControlEnabled()).thenReturn(true);
Sudheer Shanka543339f2017-07-28 15:18:07 -0700358 when(mNetworkManager.setDataSaverModeEnabled(anyBoolean())).thenReturn(true);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700359 expectCurrentTime();
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700360
Felipe Lemeef134662016-08-10 14:46:39 -0700361 // Prepare NPMS.
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800362 mService.systemReady(mService.networkScoreAndNetworkManagementServiceReady());
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700363
Felipe Lemeef134662016-08-10 14:46:39 -0700364 // catch INetworkManagementEventObserver during systemReady()
Felipe Leme3d3308d2016-08-23 17:41:47 -0700365 final ArgumentCaptor<INetworkManagementEventObserver> networkObserver =
Felipe Lemeef134662016-08-10 14:46:39 -0700366 ArgumentCaptor.forClass(INetworkManagementEventObserver.class);
367 verify(mNetworkManager).registerObserver(networkObserver.capture());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700368 mNetworkObserver = networkObserver.getValue();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700369
370 NetworkPolicy defaultPolicy = mService.buildDefaultMobilePolicy(0, "");
371 mDefaultWarningBytes = defaultPolicy.warningBytes;
372 mDefaultLimitBytes = defaultPolicy.limitBytes;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700373 }
374
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700375 @After
376 public void removeFiles() throws Exception {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700377 for (File file : mPolicyDir.listFiles()) {
378 file.delete();
379 }
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700380 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700381
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700382 @After
383 public void unregisterLocalServices() throws Exception {
384 // Registered by NetworkPolicyManagerService's constructor.
Felipe Lemeef134662016-08-10 14:46:39 -0700385 LocalServices.removeServiceForTest(NetworkPolicyManagerInternal.class);
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700386
387 // Added in registerLocalServices()
388 LocalServices.removeServiceForTest(ActivityManagerInternal.class);
389 LocalServices.removeServiceForTest(PowerManagerInternal.class);
390 LocalServices.removeServiceForTest(DeviceIdleController.LocalService.class);
391 LocalServices.removeServiceForTest(UsageStatsManagerInternal.class);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700392 }
393
Jeff Sharkey53313d72017-07-13 16:47:32 -0600394 @After
395 public void resetClock() throws Exception {
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600396 RecurrenceRule.sClock = Clock.systemDefaultZone();
Jeff Sharkey53313d72017-07-13 16:47:32 -0600397 }
398
Felipe Lemee88729d2016-08-17 16:43:01 -0700399 @Test
Felipe Leme3d3308d2016-08-23 17:41:47 -0700400 public void testTurnRestrictBackgroundOn() throws Exception {
401 assertRestrictBackgroundOff(); // Sanity check.
402 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
403 setRestrictBackground(true);
404 assertRestrictBackgroundChangedReceived(futureIntent, null);
405 }
406
407 @Test
408 @NetPolicyXml("restrict-background-on.xml")
409 public void testTurnRestrictBackgroundOff() throws Exception {
410 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700411 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700412 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
413 setRestrictBackground(false);
414 assertRestrictBackgroundChangedReceived(futureIntent, null);
415 }
416
417 /**
418 * Adds whitelist when restrict background is on - app should receive an intent.
419 */
420 @Test
421 @NetPolicyXml("restrict-background-on.xml")
422 public void testAddRestrictBackgroundWhitelist_restrictBackgroundOn() throws Exception {
423 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700424 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700425 addRestrictBackgroundWhitelist(true);
426 }
427
428 /**
429 * Adds whitelist when restrict background is off - app should not receive an intent.
430 */
431 @Test
432 public void testAddRestrictBackgroundWhitelist_restrictBackgroundOff() throws Exception {
433 assertRestrictBackgroundOff(); // Sanity check.
434 addRestrictBackgroundWhitelist(false);
435 }
436
437 private void addRestrictBackgroundWhitelist(boolean expectIntent) throws Exception {
Felipe Leme57e3d312016-08-23 14:42:52 -0700438 // Sanity checks.
439 assertWhitelistUids();
440 assertUidPolicy(UID_A, POLICY_NONE);
441
Felipe Leme3d3308d2016-08-23 17:41:47 -0700442 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700443 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700444
Felipe Leme57e3d312016-08-23 14:42:52 -0700445 mService.setUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700446
447 assertWhitelistUids(UID_A);
Felipe Leme57e3d312016-08-23 14:42:52 -0700448 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700449 mPolicyListener.waitAndVerify()
450 .onUidPoliciesChanged(APP_ID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700451 if (expectIntent) {
452 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
453 } else {
454 futureIntent.assertNotReceived();
455 }
456 }
457
458 /**
459 * Removes whitelist when restrict background is on - app should receive an intent.
460 */
461 @Test
462 @NetPolicyXml("uidA-whitelisted-restrict-background-on.xml")
463 public void testRemoveRestrictBackgroundWhitelist_restrictBackgroundOn() throws Exception {
464 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700465 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700466 removeRestrictBackgroundWhitelist(true);
467 }
468
469 /**
470 * Removes whitelist when restrict background is off - app should not receive an intent.
471 */
472 @Test
473 @NetPolicyXml("uidA-whitelisted-restrict-background-off.xml")
474 public void testRemoveRestrictBackgroundWhitelist_restrictBackgroundOff() throws Exception {
475 assertRestrictBackgroundOff(); // Sanity check.
476 removeRestrictBackgroundWhitelist(false);
477 }
478
jackqdyulei29c82ab2017-03-10 14:09:16 -0800479 @Test
480 public void testLowPowerModeObserver_ListenersRegistered()
481 throws Exception {
482 PowerManagerInternal pmInternal = LocalServices.getService(PowerManagerInternal.class);
483
484 verify(pmInternal, atLeast(2)).registerLowPowerModeObserver(any());
485 }
486
487 @Test
488 public void updateRestrictBackgroundByLowPowerMode_RestrictOnBeforeBsm_RestrictOnAfterBsm()
489 throws Exception {
490 setRestrictBackground(true);
491 PowerSaveState stateOn = new PowerSaveState.Builder()
492 .setGlobalBatterySaverEnabled(true)
493 .setBatterySaverEnabled(false)
494 .build();
495 mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
496
497 // RestrictBackground should be on even though battery saver want to turn it off
498 assertThat(mService.getRestrictBackground()).isTrue();
499
500 PowerSaveState stateOff = new PowerSaveState.Builder()
501 .setGlobalBatterySaverEnabled(false)
502 .setBatterySaverEnabled(false)
503 .build();
504 mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
505
506 // RestrictBackground should be on, following its previous state
507 assertThat(mService.getRestrictBackground()).isTrue();
508 }
509
510 @Test
511 public void updateRestrictBackgroundByLowPowerMode_RestrictOffBeforeBsm_RestrictOffAfterBsm()
512 throws Exception {
513 setRestrictBackground(false);
514 PowerSaveState stateOn = new PowerSaveState.Builder()
515 .setGlobalBatterySaverEnabled(true)
516 .setBatterySaverEnabled(true)
517 .build();
518
jackqdyulei29c82ab2017-03-10 14:09:16 -0800519 mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
520
521 // RestrictBackground should be turned on because of battery saver
522 assertThat(mService.getRestrictBackground()).isTrue();
523
524 PowerSaveState stateOff = new PowerSaveState.Builder()
525 .setGlobalBatterySaverEnabled(false)
526 .setBatterySaverEnabled(false)
527 .build();
528 mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
529
530 // RestrictBackground should be off, following its previous state
531 assertThat(mService.getRestrictBackground()).isFalse();
532 }
533
534 @Test
535 public void updateRestrictBackgroundByLowPowerMode_StatusChangedInBsm_DoNotRestore()
536 throws Exception {
537 setRestrictBackground(true);
538 PowerSaveState stateOn = new PowerSaveState.Builder()
539 .setGlobalBatterySaverEnabled(true)
540 .setBatterySaverEnabled(true)
541 .build();
542 mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
543
544 // RestrictBackground should still be on
545 assertThat(mService.getRestrictBackground()).isTrue();
546
547 // User turns off RestrictBackground manually
548 setRestrictBackground(false);
549 PowerSaveState stateOff = new PowerSaveState.Builder().setBatterySaverEnabled(
550 false).build();
551 mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
552
553 // RestrictBackground should be off because user changes it manually
554 assertThat(mService.getRestrictBackground()).isFalse();
555 }
556
Felipe Leme3d3308d2016-08-23 17:41:47 -0700557 private void removeRestrictBackgroundWhitelist(boolean expectIntent) throws Exception {
Felipe Leme57e3d312016-08-23 14:42:52 -0700558 // Sanity checks.
559 assertWhitelistUids(UID_A);
560 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
561
Felipe Leme3d3308d2016-08-23 17:41:47 -0700562 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700563 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700564
Felipe Leme57e3d312016-08-23 14:42:52 -0700565 mService.setUidPolicy(UID_A, POLICY_NONE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700566
567 assertWhitelistUids();
Felipe Leme57e3d312016-08-23 14:42:52 -0700568 assertUidPolicy(UID_A, POLICY_NONE);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700569 mPolicyListener.waitAndVerify().onUidPoliciesChanged(APP_ID_A, POLICY_NONE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700570 if (expectIntent) {
571 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
572 } else {
573 futureIntent.assertNotReceived();
574 }
575 }
576
577 /**
Felipe Leme57e3d312016-08-23 14:42:52 -0700578 * Adds blacklist when restrict background is on - app should not receive an intent.
Felipe Leme3d3308d2016-08-23 17:41:47 -0700579 */
580 @Test
581 @NetPolicyXml("restrict-background-on.xml")
582 public void testAddRestrictBackgroundBlacklist_restrictBackgroundOn() throws Exception {
583 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700584 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme57e3d312016-08-23 14:42:52 -0700585 addRestrictBackgroundBlacklist(false);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700586 }
587
588 /**
589 * Adds blacklist when restrict background is off - app should receive an intent.
590 */
591 @Test
592 public void testAddRestrictBackgroundBlacklist_restrictBackgroundOff() throws Exception {
593 assertRestrictBackgroundOff(); // Sanity check.
594 addRestrictBackgroundBlacklist(true);
595 }
596
597 private void addRestrictBackgroundBlacklist(boolean expectIntent) throws Exception {
598 assertUidPolicy(UID_A, POLICY_NONE); // Sanity check.
599 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700600 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700601
602 mService.setUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
603
604 assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700605 mPolicyListener.waitAndVerify()
606 .onUidPoliciesChanged(APP_ID_A, POLICY_REJECT_METERED_BACKGROUND);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700607 if (expectIntent) {
608 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
609 } else {
610 futureIntent.assertNotReceived();
611 }
612 }
613
614 /**
Felipe Leme57e3d312016-08-23 14:42:52 -0700615 * Removes blacklist when restrict background is on - app should not receive an intent.
Felipe Leme3d3308d2016-08-23 17:41:47 -0700616 */
617 @Test
618 @NetPolicyXml("uidA-blacklisted-restrict-background-on.xml")
619 public void testRemoveRestrictBackgroundBlacklist_restrictBackgroundOn() throws Exception {
620 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700621 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme57e3d312016-08-23 14:42:52 -0700622 removeRestrictBackgroundBlacklist(false);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700623 }
624
625 /**
626 * Removes blacklist when restrict background is off - app should receive an intent.
627 */
628 @Test
629 @NetPolicyXml("uidA-blacklisted-restrict-background-off.xml")
630 public void testRemoveRestrictBackgroundBlacklist_restrictBackgroundOff() throws Exception {
631 assertRestrictBackgroundOff(); // Sanity check.
632 removeRestrictBackgroundBlacklist(true);
633 }
634
635 private void removeRestrictBackgroundBlacklist(boolean expectIntent) throws Exception {
636 assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND); // Sanity check.
637 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700638 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700639
640 mService.setUidPolicy(UID_A, POLICY_NONE);
641
642 assertUidPolicy(UID_A, POLICY_NONE);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700643 mPolicyListener.waitAndVerify()
644 .onUidPoliciesChanged(APP_ID_A, POLICY_NONE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700645 if (expectIntent) {
646 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
647 } else {
648 futureIntent.assertNotReceived();
649 }
650 }
651
Felipe Leme51a63642016-08-30 12:15:09 -0700652 @Test
Felipe Lemec08ecdf2016-08-30 12:57:35 -0700653 @NetPolicyXml("uidA-blacklisted-restrict-background-on.xml")
Felipe Leme3d3308d2016-08-23 17:41:47 -0700654 public void testBlacklistedAppIsNotNotifiedWhenRestrictBackgroundIsOn() throws Exception {
655 // Sanity checks.
656 assertRestrictBackgroundOn();
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700657 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700658 assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
659
660 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
661 setRestrictBackground(true);
662 futureIntent.assertNotReceived();
663 }
664
Felipe Leme51a63642016-08-30 12:15:09 -0700665 @Test
Felipe Lemec08ecdf2016-08-30 12:57:35 -0700666 @NetPolicyXml("uidA-whitelisted-restrict-background-on.xml")
Felipe Leme3d3308d2016-08-23 17:41:47 -0700667 public void testWhitelistedAppIsNotNotifiedWhenRestrictBackgroundIsOn() throws Exception {
668 // Sanity checks.
Felipe Lemec08ecdf2016-08-30 12:57:35 -0700669 assertRestrictBackgroundOn();
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700670 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700671 assertWhitelistUids(UID_A);
672
673 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
674 setRestrictBackground(true);
675 futureIntent.assertNotReceived();
676 }
677
Andreas Gampe84d156b2016-09-03 10:50:38 -0700678 @Test
Felipe Leme57e3d312016-08-23 14:42:52 -0700679 @NetPolicyXml("uidA-whitelisted-restrict-background-on.xml")
680 public void testWhitelistedAppIsNotifiedWhenBlacklisted() throws Exception {
681 // Sanity checks.
682 assertRestrictBackgroundOn();
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700683 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme57e3d312016-08-23 14:42:52 -0700684 assertWhitelistUids(UID_A);
685
686 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
687 mService.setUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
688 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
689 }
690
Felipe Leme3d3308d2016-08-23 17:41:47 -0700691 @Test
Felipe Lemee88729d2016-08-17 16:43:01 -0700692 @NetPolicyXml("restrict-background-lists-whitelist-format.xml")
693 public void testRestrictBackgroundLists_whitelistFormat() throws Exception {
Felipe Leme46b451f2016-08-19 08:46:17 -0700694 restrictBackgroundListsTest();
695 }
696
697 @Test
698 @NetPolicyXml("restrict-background-lists-uid-policy-format.xml")
699 public void testRestrictBackgroundLists_uidPolicyFormat() throws Exception {
700 restrictBackgroundListsTest();
701 }
702
703 private void restrictBackgroundListsTest() throws Exception {
Felipe Leme8546a442016-08-23 09:38:20 -0700704 // UIds that are whitelisted.
Felipe Leme46b451f2016-08-19 08:46:17 -0700705 assertWhitelistUids(UID_A, UID_B, UID_C);
706 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
707 assertUidPolicy(UID_B, POLICY_ALLOW_METERED_BACKGROUND);
708 assertUidPolicy(UID_C, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Lemee88729d2016-08-17 16:43:01 -0700709
Felipe Leme8546a442016-08-23 09:38:20 -0700710 // UIDs that are blacklisted.
Felipe Lemee88729d2016-08-17 16:43:01 -0700711 assertUidPolicy(UID_D, POLICY_NONE);
712 assertUidPolicy(UID_E, POLICY_REJECT_METERED_BACKGROUND);
Felipe Leme8546a442016-08-23 09:38:20 -0700713
714 // UIDS that have legacy policies.
Felipe Leme46b451f2016-08-19 08:46:17 -0700715 assertUidPolicy(UID_F, 2); // POLICY_ALLOW_BACKGROUND_BATTERY_SAVE
716
717 // Remove whitelist.
Felipe Leme57e3d312016-08-23 14:42:52 -0700718 mService.setUidPolicy(UID_A, POLICY_NONE);
Felipe Leme46b451f2016-08-19 08:46:17 -0700719 assertUidPolicy(UID_A, POLICY_NONE);
720 assertWhitelistUids(UID_B, UID_C);
721
722 // Add whitelist when blacklisted.
Felipe Leme57e3d312016-08-23 14:42:52 -0700723 mService.setUidPolicy(UID_E, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme46b451f2016-08-19 08:46:17 -0700724 assertUidPolicy(UID_E, POLICY_ALLOW_METERED_BACKGROUND);
725 assertWhitelistUids(UID_B, UID_C, UID_E);
726
727 // Add blacklist when whitelisted.
728 mService.setUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND);
729 assertUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND);
730 assertWhitelistUids(UID_C, UID_E);
731 }
732
733 /**
734 * Tests scenario where an UID had {@code restrict-background} and {@code uid-policy} tags.
735 */
736 @Test
737 @NetPolicyXml("restrict-background-lists-mixed-format.xml")
738 public void testRestrictBackgroundLists_mixedFormat() throws Exception {
739 assertWhitelistUids(UID_A, UID_C, UID_D);
740 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme57e3d312016-08-23 14:42:52 -0700741 assertUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND); // Blacklist prevails.
Felipe Leme46b451f2016-08-19 08:46:17 -0700742 assertUidPolicy(UID_C, (POLICY_ALLOW_METERED_BACKGROUND | 2));
743 assertUidPolicy(UID_D, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Lemee88729d2016-08-17 16:43:01 -0700744 }
745
Felipe Leme6f51a0a2016-08-24 15:11:51 -0700746 @Test
747 @NetPolicyXml("uids-with-mixed-policies.xml")
748 public void testGetUidsWithPolicy() throws Exception {
Felipe Leme03f90292016-09-08 18:10:32 -0700749 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_NONE));
Felipe Leme6f51a0a2016-08-24 15:11:51 -0700750 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND),
751 UID_B, UID_D);
752 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_ALLOW_METERED_BACKGROUND),
753 UID_E, UID_F);
754 // Legacy (POLICY_ALLOW_BACKGROUND_BATTERY_SAVE)
755 assertContainsInAnyOrder(mService.getUidsWithPolicy(2),
756 UID_C, UID_D, UID_F);
757 }
758
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700759 // NOTE: testPolicyChangeTriggersListener() is too superficial, they
Felipe Lemeef134662016-08-10 14:46:39 -0700760 // don't check for side-effects (like calls to NetworkManagementService) neither cover all
761 // different modes (Data Saver, Battery Saver, Doze, App idle, etc...).
762 // These scenarios are extensively tested on CTS' HostsideRestrictBackgroundNetworkTests.
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700763 @Test
Felipe Lemeef134662016-08-10 14:46:39 -0700764 public void testUidForeground() throws Exception {
765 // push all uids into background
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700766 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE, 0);
767 callOnUidStateChanged(UID_B, ActivityManager.PROCESS_STATE_SERVICE, 0);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700768 assertFalse(mService.isUidForeground(UID_A));
769 assertFalse(mService.isUidForeground(UID_B));
770
Felipe Lemeef134662016-08-10 14:46:39 -0700771 // push one of the uids into foreground
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700772 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_TOP, 0);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700773 assertTrue(mService.isUidForeground(UID_A));
774 assertFalse(mService.isUidForeground(UID_B));
775
776 // and swap another uid into foreground
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700777 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE, 0);
778 callOnUidStateChanged(UID_B, ActivityManager.PROCESS_STATE_TOP, 0);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700779 assertFalse(mService.isUidForeground(UID_A));
780 assertTrue(mService.isUidForeground(UID_B));
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700781 }
782
Jeff Sharkey53313d72017-07-13 16:47:32 -0600783 private static long computeLastCycleBoundary(long currentTime, NetworkPolicy policy) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600784 RecurrenceRule.sClock = Clock.fixed(Instant.ofEpochMilli(currentTime),
785 ZoneId.systemDefault());
786 final Iterator<Pair<ZonedDateTime, ZonedDateTime>> it = policy.cycleIterator();
Jeff Sharkey53313d72017-07-13 16:47:32 -0600787 while (it.hasNext()) {
788 final Pair<ZonedDateTime, ZonedDateTime> cycle = it.next();
789 if (cycle.first.toInstant().toEpochMilli() < currentTime) {
790 return cycle.first.toInstant().toEpochMilli();
791 }
792 }
793 throw new IllegalStateException(
794 "Failed to find current cycle for " + policy + " at " + currentTime);
795 }
796
797 private static long computeNextCycleBoundary(long currentTime, NetworkPolicy policy) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600798 RecurrenceRule.sClock = Clock.fixed(Instant.ofEpochMilli(currentTime),
799 ZoneId.systemDefault());
800 return policy.cycleIterator().next().second.toInstant().toEpochMilli();
Jeff Sharkey53313d72017-07-13 16:47:32 -0600801 }
802
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700803 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700804 public void testLastCycleBoundaryThisMonth() throws Exception {
805 // assume cycle day of "5th", which should be in same month
806 final long currentTime = parseTime("2007-11-14T00:00:00.000Z");
807 final long expectedCycle = parseTime("2007-11-05T00:00:00.000Z");
808
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700809 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800810 sTemplateWifi, 5, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700811 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700812 assertTimeEquals(expectedCycle, actualCycle);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700813 }
814
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700815 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700816 public void testLastCycleBoundaryLastMonth() throws Exception {
817 // assume cycle day of "20th", which should be in last month
818 final long currentTime = parseTime("2007-11-14T00:00:00.000Z");
819 final long expectedCycle = parseTime("2007-10-20T00:00:00.000Z");
820
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700821 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800822 sTemplateWifi, 20, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700823 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700824 assertTimeEquals(expectedCycle, actualCycle);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700825 }
826
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700827 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700828 public void testLastCycleBoundaryThisMonthFebruary() throws Exception {
829 // assume cycle day of "30th" in february; should go to january
830 final long currentTime = parseTime("2007-02-14T00:00:00.000Z");
831 final long expectedCycle = parseTime("2007-01-30T00:00:00.000Z");
832
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700833 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800834 sTemplateWifi, 30, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700835 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700836 assertTimeEquals(expectedCycle, actualCycle);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700837 }
838
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700839 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700840 public void testLastCycleBoundaryLastMonthFebruary() throws Exception {
841 // assume cycle day of "30th" in february, which should clamp
842 final long currentTime = parseTime("2007-03-14T00:00:00.000Z");
Jeff Sharkey53313d72017-07-13 16:47:32 -0600843 final long expectedCycle = parseTime("2007-02-28T23:59:59.999Z");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700844
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700845 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800846 sTemplateWifi, 30, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700847 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700848 assertTimeEquals(expectedCycle, actualCycle);
849 }
850
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700851 @Test
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800852 public void testCycleBoundaryLeapYear() throws Exception {
853 final NetworkPolicy policy = new NetworkPolicy(
854 sTemplateWifi, 29, TIMEZONE_UTC, 1024L, 1024L, false);
855
856 assertTimeEquals(parseTime("2012-01-29T00:00:00.000Z"),
857 computeNextCycleBoundary(parseTime("2012-01-14T00:00:00.000Z"), policy));
858 assertTimeEquals(parseTime("2012-02-29T00:00:00.000Z"),
859 computeNextCycleBoundary(parseTime("2012-02-14T00:00:00.000Z"), policy));
860 assertTimeEquals(parseTime("2012-02-29T00:00:00.000Z"),
861 computeLastCycleBoundary(parseTime("2012-03-14T00:00:00.000Z"), policy));
862 assertTimeEquals(parseTime("2012-03-29T00:00:00.000Z"),
863 computeNextCycleBoundary(parseTime("2012-03-14T00:00:00.000Z"), policy));
864
865 assertTimeEquals(parseTime("2007-01-29T00:00:00.000Z"),
866 computeNextCycleBoundary(parseTime("2007-01-14T00:00:00.000Z"), policy));
Jeff Sharkey53313d72017-07-13 16:47:32 -0600867 assertTimeEquals(parseTime("2007-02-28T23:59:59.999Z"),
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800868 computeNextCycleBoundary(parseTime("2007-02-14T00:00:00.000Z"), policy));
Jeff Sharkey53313d72017-07-13 16:47:32 -0600869 assertTimeEquals(parseTime("2007-02-28T23:59:59.999Z"),
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800870 computeLastCycleBoundary(parseTime("2007-03-14T00:00:00.000Z"), policy));
871 assertTimeEquals(parseTime("2007-03-29T00:00:00.000Z"),
872 computeNextCycleBoundary(parseTime("2007-03-14T00:00:00.000Z"), policy));
873 }
874
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700875 @Test
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800876 public void testNextCycleTimezoneAfterUtc() throws Exception {
877 // US/Central is UTC-6
878 final NetworkPolicy policy = new NetworkPolicy(
879 sTemplateWifi, 10, "US/Central", 1024L, 1024L, false);
880 assertTimeEquals(parseTime("2012-01-10T06:00:00.000Z"),
881 computeNextCycleBoundary(parseTime("2012-01-05T00:00:00.000Z"), policy));
882 }
883
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700884 @Test
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800885 public void testNextCycleTimezoneBeforeUtc() throws Exception {
886 // Israel is UTC+2
887 final NetworkPolicy policy = new NetworkPolicy(
888 sTemplateWifi, 10, "Israel", 1024L, 1024L, false);
889 assertTimeEquals(parseTime("2012-01-09T22:00:00.000Z"),
890 computeNextCycleBoundary(parseTime("2012-01-05T00:00:00.000Z"), policy));
891 }
892
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700893 @Test
Jeff Sharkey15399052013-01-15 14:15:53 -0800894 public void testCycleTodayJanuary() throws Exception {
895 final NetworkPolicy policy = new NetworkPolicy(
896 sTemplateWifi, 14, "US/Pacific", 1024L, 1024L, false);
897
898 assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
899 computeNextCycleBoundary(parseTime("2013-01-13T23:59:59.000-08:00"), policy));
900 assertTimeEquals(parseTime("2013-02-14T00:00:00.000-08:00"),
901 computeNextCycleBoundary(parseTime("2013-01-14T00:00:01.000-08:00"), policy));
902 assertTimeEquals(parseTime("2013-02-14T00:00:00.000-08:00"),
903 computeNextCycleBoundary(parseTime("2013-01-14T15:11:00.000-08:00"), policy));
904
905 assertTimeEquals(parseTime("2012-12-14T00:00:00.000-08:00"),
906 computeLastCycleBoundary(parseTime("2013-01-13T23:59:59.000-08:00"), policy));
907 assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
908 computeLastCycleBoundary(parseTime("2013-01-14T00:00:01.000-08:00"), policy));
909 assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
910 computeLastCycleBoundary(parseTime("2013-01-14T15:11:00.000-08:00"), policy));
911 }
912
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700913 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700914 public void testNetworkPolicyAppliedCycleLastMonth() throws Exception {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700915 NetworkState[] state = null;
916 NetworkStats stats = null;
917
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700918 final int CYCLE_DAY = 15;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600919 final long NOW = parseTime("2007-03-10T00:00Z");
920 final long CYCLE_START = parseTime("2007-02-15T00:00Z");
921 final long CYCLE_END = parseTime("2007-03-15T00:00Z");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700922
Jeff Sharkey53313d72017-07-13 16:47:32 -0600923 setCurrentTimeMillis(NOW);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700924
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700925 // first, pretend that wifi network comes online. no policy active,
926 // which means we shouldn't push limit to interface.
927 state = new NetworkState[] { buildWifi() };
Felipe Lemeef134662016-08-10 14:46:39 -0700928 when(mConnManager.getAllNetworkState()).thenReturn(state);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700929 expectCurrentTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700930
Felipe Lemeef134662016-08-10 14:46:39 -0700931 mPolicyListener.expect().onMeteredIfacesChanged(any());
Erik Klinef851d6d2015-04-20 16:03:48 +0900932 mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION));
Felipe Lemeef134662016-08-10 14:46:39 -0700933 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(any());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700934
935 // now change cycle to be on 15th, and test in early march, to verify we
936 // pick cycle day in previous month.
Felipe Lemeef134662016-08-10 14:46:39 -0700937 when(mConnManager.getAllNetworkState()).thenReturn(state);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700938 expectCurrentTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700939
940 // pretend that 512 bytes total have happened
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700941 stats = new NetworkStats(getElapsedRealtime(), 1)
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700942 .addIfaceValues(TEST_IFACE, 256L, 2L, 256L, 2L);
Jeff Sharkey53313d72017-07-13 16:47:32 -0600943 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, CYCLE_START, CYCLE_END))
Felipe Lemeef134662016-08-10 14:46:39 -0700944 .thenReturn(stats.getTotalBytes());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700945
Felipe Lemeef134662016-08-10 14:46:39 -0700946 mPolicyListener.expect().onMeteredIfacesChanged(any());
Jeff Sharkey163e6442011-10-31 16:37:52 -0700947 setNetworkPolicies(new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800948 sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, 1 * MB_IN_BYTES, 2 * MB_IN_BYTES, false));
Felipe Lemeef134662016-08-10 14:46:39 -0700949 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
950
951 // TODO: consider making strongly ordered mock
952 verifyPolicyDataEnable(TYPE_WIFI, true);
953 verifyRemoveInterfaceQuota(TEST_IFACE);
954 verifySetInterfaceQuota(TEST_IFACE, (2 * MB_IN_BYTES) - 512);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700955 }
956
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700957 @Test
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700958 public void testOverWarningLimitNotification() throws Exception {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700959 NetworkState[] state = null;
960 NetworkStats stats = null;
Felipe Lemeef134662016-08-10 14:46:39 -0700961 Future<String> tagFuture = null;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700962
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700963 final int CYCLE_DAY = 15;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600964 final long NOW = parseTime("2007-03-10T00:00Z");
965 final long CYCLE_START = parseTime("2007-02-15T00:00Z");
966 final long CYCLE_END = parseTime("2007-03-15T00:00Z");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700967
Jeff Sharkey53313d72017-07-13 16:47:32 -0600968 setCurrentTimeMillis(NOW);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700969
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700970 // assign wifi policy
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700971 state = new NetworkState[] {};
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700972 stats = new NetworkStats(getElapsedRealtime(), 1)
973 .addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700974
975 {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700976 expectCurrentTime();
Felipe Lemeef134662016-08-10 14:46:39 -0700977 when(mConnManager.getAllNetworkState()).thenReturn(state);
Jeff Sharkey53313d72017-07-13 16:47:32 -0600978 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, CYCLE_START,
979 CYCLE_END)).thenReturn(stats.getTotalBytes());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700980
Felipe Lemeef134662016-08-10 14:46:39 -0700981 mPolicyListener.expect().onMeteredIfacesChanged(any());
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800982 setNetworkPolicies(new NetworkPolicy(sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, 1
983 * MB_IN_BYTES, 2 * MB_IN_BYTES, false));
Felipe Lemeef134662016-08-10 14:46:39 -0700984 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(any());
985 verifyPolicyDataEnable(TYPE_WIFI, true);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700986 }
987
988 // bring up wifi network
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700989 incrementCurrentTime(MINUTE_IN_MILLIS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700990 state = new NetworkState[] { buildWifi() };
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700991 stats = new NetworkStats(getElapsedRealtime(), 1)
992 .addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700993
994 {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700995 expectCurrentTime();
Felipe Lemeef134662016-08-10 14:46:39 -0700996 when(mConnManager.getAllNetworkState()).thenReturn(state);
Jeff Sharkey53313d72017-07-13 16:47:32 -0600997 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, CYCLE_START,
998 CYCLE_END)).thenReturn(stats.getTotalBytes());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700999
Felipe Lemeef134662016-08-10 14:46:39 -07001000 mPolicyListener.expect().onMeteredIfacesChanged(any());
Erik Klinef851d6d2015-04-20 16:03:48 +09001001 mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION));
Felipe Lemeef134662016-08-10 14:46:39 -07001002 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
1003
1004 verifyPolicyDataEnable(TYPE_WIFI, true);
1005 verifyRemoveInterfaceQuota(TEST_IFACE);
1006 verifySetInterfaceQuota(TEST_IFACE, 2 * MB_IN_BYTES);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001007 }
1008
1009 // go over warning, which should kick notification
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001010 incrementCurrentTime(MINUTE_IN_MILLIS);
1011 stats = new NetworkStats(getElapsedRealtime(), 1)
Jeff Sharkey163e6442011-10-31 16:37:52 -07001012 .addIfaceValues(TEST_IFACE, 1536 * KB_IN_BYTES, 15L, 0L, 0L);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001013
1014 {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001015 expectCurrentTime();
Jeff Sharkey53313d72017-07-13 16:47:32 -06001016 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, CYCLE_START,
1017 CYCLE_END)).thenReturn(stats.getTotalBytes());
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001018 tagFuture = expectEnqueueNotification();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001019
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001020 mNetworkObserver.limitReached(null, TEST_IFACE);
Felipe Lemeef134662016-08-10 14:46:39 -07001021
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001022 assertNotificationType(TYPE_WARNING, tagFuture.get());
Felipe Lemeef134662016-08-10 14:46:39 -07001023 verifyPolicyDataEnable(TYPE_WIFI, true);
1024
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001025 }
1026
1027 // go over limit, which should kick notification and dialog
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001028 incrementCurrentTime(MINUTE_IN_MILLIS);
1029 stats = new NetworkStats(getElapsedRealtime(), 1)
Jeff Sharkey163e6442011-10-31 16:37:52 -07001030 .addIfaceValues(TEST_IFACE, 5 * MB_IN_BYTES, 512L, 0L, 0L);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001031
1032 {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001033 expectCurrentTime();
Jeff Sharkey53313d72017-07-13 16:47:32 -06001034 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, CYCLE_START,
1035 CYCLE_END)).thenReturn(stats.getTotalBytes());
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001036 tagFuture = expectEnqueueNotification();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001037
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001038 mNetworkObserver.limitReached(null, TEST_IFACE);
Felipe Lemeef134662016-08-10 14:46:39 -07001039
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001040 assertNotificationType(TYPE_LIMIT, tagFuture.get());
Felipe Lemeef134662016-08-10 14:46:39 -07001041 verifyPolicyDataEnable(TYPE_WIFI, false);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001042 }
1043
1044 // now snooze policy, which should remove quota
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001045 incrementCurrentTime(MINUTE_IN_MILLIS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001046
1047 {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001048 expectCurrentTime();
Felipe Lemeef134662016-08-10 14:46:39 -07001049 when(mConnManager.getAllNetworkState()).thenReturn(state);
Jeff Sharkey53313d72017-07-13 16:47:32 -06001050 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, CYCLE_START,
1051 CYCLE_END)).thenReturn(stats.getTotalBytes());
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001052 tagFuture = expectEnqueueNotification();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001053
Felipe Lemeef134662016-08-10 14:46:39 -07001054 mPolicyListener.expect().onMeteredIfacesChanged(any());
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001055 mService.snoozeLimit(sTemplateWifi);
Felipe Lemeef134662016-08-10 14:46:39 -07001056 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
1057
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001058 assertNotificationType(TYPE_LIMIT_SNOOZED, tagFuture.get());
Felipe Lemeef134662016-08-10 14:46:39 -07001059 // snoozed interface still has high quota so background data is
1060 // still restricted.
1061 verifyRemoveInterfaceQuota(TEST_IFACE);
1062 verifySetInterfaceQuota(TEST_IFACE, Long.MAX_VALUE);
1063 verifyPolicyDataEnable(TYPE_WIFI, true);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001064 }
1065 }
1066
Felipe Leme9f27e7a2016-08-12 15:19:40 -07001067 @Test
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001068 public void testMeteredNetworkWithoutLimit() throws Exception {
1069 NetworkState[] state = null;
1070 NetworkStats stats = null;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001071
1072 final long TIME_FEB_15 = 1171497600000L;
1073 final long TIME_MAR_10 = 1173484800000L;
1074 final int CYCLE_DAY = 15;
1075
1076 setCurrentTimeMillis(TIME_MAR_10);
1077
1078 // bring up wifi network with metered policy
1079 state = new NetworkState[] { buildWifi() };
1080 stats = new NetworkStats(getElapsedRealtime(), 1)
1081 .addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L);
1082
1083 {
1084 expectCurrentTime();
Felipe Lemeef134662016-08-10 14:46:39 -07001085 when(mConnManager.getAllNetworkState()).thenReturn(state);
1086 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15,
1087 currentTimeMillis())).thenReturn(stats.getTotalBytes());
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001088
Felipe Lemeef134662016-08-10 14:46:39 -07001089 mPolicyListener.expect().onMeteredIfacesChanged(any());
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001090 setNetworkPolicies(new NetworkPolicy(
1091 sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, WARNING_DISABLED, LIMIT_DISABLED,
1092 true));
Felipe Lemeef134662016-08-10 14:46:39 -07001093 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
1094
1095 verifyPolicyDataEnable(TYPE_WIFI, true);
1096 verifyRemoveInterfaceQuota(TEST_IFACE);
1097 verifySetInterfaceQuota(TEST_IFACE, Long.MAX_VALUE);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001098 }
1099 }
1100
Sudheer Shankae7361852017-03-07 11:51:46 -08001101 @Test
1102 public void testOnUidStateChanged_notifyAMS() throws Exception {
1103 final long procStateSeq = 222;
Sudheer Shankaed25ce62017-03-29 20:46:30 -07001104 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE, procStateSeq);
Sudheer Shankae7361852017-03-07 11:51:46 -08001105 verify(mActivityManagerInternal).notifyNetworkPolicyRulesUpdated(UID_A, procStateSeq);
Sudheer Shankae7361852017-03-07 11:51:46 -08001106 }
1107
Sudheer Shankaed25ce62017-03-29 20:46:30 -07001108 private void callOnUidStateChanged(int uid, int procState, long procStateSeq)
1109 throws Exception {
1110 mUidObserver.onUidStateChanged(uid, procState, procStateSeq);
1111 final CountDownLatch latch = new CountDownLatch(1);
1112 mService.mUidEventHandler.post(() -> {
1113 latch.countDown();
1114 });
1115 latch.await(2, TimeUnit.SECONDS);
1116 }
1117
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001118 private void assertCycleDayAsExpected(PersistableBundle config, int carrierCycleDay,
1119 boolean expectValid) {
1120 config.putInt(KEY_MONTHLY_DATA_CYCLE_DAY_INT, carrierCycleDay);
1121 int actualCycleDay = mService.getCycleDayFromCarrierConfig(config,
1122 INVALID_CARRIER_CONFIG_VALUE);
1123 if (expectValid) {
1124 assertEquals(carrierCycleDay, actualCycleDay);
1125 } else {
1126 // INVALID_CARRIER_CONFIG_VALUE is returned for invalid values
1127 assertEquals(INVALID_CARRIER_CONFIG_VALUE, actualCycleDay);
1128 }
1129 }
1130
1131 @Test
1132 public void testGetCycleDayFromCarrierConfig() {
1133 PersistableBundle config = CarrierConfigManager.getDefaultConfig();
1134 final Calendar cal = Calendar.getInstance();
1135 int actualCycleDay;
1136
1137 config.putInt(KEY_MONTHLY_DATA_CYCLE_DAY_INT, DATA_CYCLE_USE_PLATFORM_DEFAULT);
1138 actualCycleDay = mService.getCycleDayFromCarrierConfig(config, DEFAULT_CYCLE_DAY);
1139 assertEquals(DEFAULT_CYCLE_DAY, actualCycleDay);
1140
1141 // null config returns a default value
1142 actualCycleDay = mService.getCycleDayFromCarrierConfig(null, DEFAULT_CYCLE_DAY);
1143 assertEquals(DEFAULT_CYCLE_DAY, actualCycleDay);
1144
1145 // Sane, non-default values
1146 assertCycleDayAsExpected(config, 1, true);
1147 assertCycleDayAsExpected(config, cal.getMaximum(Calendar.DAY_OF_MONTH), true);
1148 assertCycleDayAsExpected(config, cal.getMinimum(Calendar.DAY_OF_MONTH), true);
1149
1150 // Invalid values
1151 assertCycleDayAsExpected(config, 0, false);
1152 assertCycleDayAsExpected(config, DATA_CYCLE_THRESHOLD_DISABLED, false);
1153 assertCycleDayAsExpected(config, cal.getMaximum(Calendar.DAY_OF_MONTH) + 1, false);
1154 assertCycleDayAsExpected(config, cal.getMinimum(Calendar.DAY_OF_MONTH) - 5, false);
1155 }
1156
1157 private void assertWarningBytesAsExpected(PersistableBundle config, long carrierWarningBytes,
1158 long expected) {
1159 config.putLong(KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, carrierWarningBytes);
1160 long actualWarning = mService.getWarningBytesFromCarrierConfig(config,
1161 INVALID_CARRIER_CONFIG_VALUE);
1162 assertEquals(expected, actualWarning);
1163 }
1164
1165 @Test
1166 public void testGetWarningBytesFromCarrierConfig() {
1167 PersistableBundle config = CarrierConfigManager.getDefaultConfig();
1168 long actualWarningBytes;
1169
1170 assertWarningBytesAsExpected(config, DATA_CYCLE_USE_PLATFORM_DEFAULT,
1171 mDefaultWarningBytes);
1172 assertWarningBytesAsExpected(config, DATA_CYCLE_THRESHOLD_DISABLED, WARNING_DISABLED);
1173 assertWarningBytesAsExpected(config, 0, 0);
1174 // not a valid value
1175 assertWarningBytesAsExpected(config, -1000, INVALID_CARRIER_CONFIG_VALUE);
1176
1177 // null config returns a default value
1178 actualWarningBytes = mService.getWarningBytesFromCarrierConfig(null, mDefaultWarningBytes);
1179 assertEquals(mDefaultWarningBytes, actualWarningBytes);
1180 }
1181
1182 private void assertLimitBytesAsExpected(PersistableBundle config, long carrierWarningBytes,
1183 long expected) {
1184 config.putLong(KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG, carrierWarningBytes);
1185 long actualWarning = mService.getLimitBytesFromCarrierConfig(config,
1186 INVALID_CARRIER_CONFIG_VALUE);
1187 assertEquals(expected, actualWarning);
1188 }
1189
1190 @Test
1191 public void testGetLimitBytesFromCarrierConfig() {
1192 PersistableBundle config = CarrierConfigManager.getDefaultConfig();
1193 long actualLimitBytes;
1194
1195 assertLimitBytesAsExpected(config, DATA_CYCLE_USE_PLATFORM_DEFAULT,
1196 mDefaultLimitBytes);
1197 assertLimitBytesAsExpected(config, DATA_CYCLE_THRESHOLD_DISABLED, LIMIT_DISABLED);
1198 assertLimitBytesAsExpected(config, 0, 0);
1199 // not a valid value
1200 assertLimitBytesAsExpected(config, -1000, INVALID_CARRIER_CONFIG_VALUE);
1201
1202 // null config returns a default value
1203 actualLimitBytes = mService.getWarningBytesFromCarrierConfig(null, mDefaultLimitBytes);
1204 assertEquals(mDefaultLimitBytes, actualLimitBytes);
1205 }
1206
1207 private PersistableBundle setupUpdateMobilePolicyCycleTests() throws RemoteException {
1208 when(mConnManager.getAllNetworkState()).thenReturn(new NetworkState[0]);
1209 when(mSubscriptionManager.getActiveSubscriptionIdList()).thenReturn(new int[]{FAKE_SUB_ID});
1210 when(mTelephonyManager.getSubscriberId(FAKE_SUB_ID)).thenReturn(FAKE_SUBSCRIBER_ID);
1211 PersistableBundle bundle = CarrierConfigManager.getDefaultConfig();
1212 when(mCarrierConfigManager.getConfigForSubId(FAKE_SUB_ID)).thenReturn(bundle);
1213 setNetworkPolicies(buildDefaultFakeMobilePolicy());
1214 return bundle;
1215 }
1216
1217 @Test
1218 public void testUpdateMobilePolicyCycleWithNullConfig() throws RemoteException {
1219 when(mConnManager.getAllNetworkState()).thenReturn(new NetworkState[0]);
1220 when(mSubscriptionManager.getActiveSubscriptionIdList()).thenReturn(new int[]{FAKE_SUB_ID});
1221 when(mTelephonyManager.getSubscriberId(FAKE_SUB_ID)).thenReturn(FAKE_SUBSCRIBER_ID);
1222 when(mCarrierConfigManager.getConfigForSubId(FAKE_SUB_ID)).thenReturn(null);
1223 setNetworkPolicies(buildDefaultFakeMobilePolicy());
1224 // smoke test to make sure no errors are raised
1225 mServiceContext.sendBroadcast(
1226 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1227 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1228 );
1229 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1230 true);
1231 }
1232
1233 @Test
1234 public void testUpdateMobilePolicyCycleWithInvalidConfig() throws RemoteException {
1235 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1236 // Test with an invalid CarrierConfig, there should be no changes or crashes.
1237 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, -100);
1238 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, -100);
1239 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG, -100);
1240 mServiceContext.sendBroadcast(
1241 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1242 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1243 );
1244
1245 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1246 true);
1247 }
1248
1249 @Test
1250 public void testUpdateMobilePolicyCycleWithDefaultConfig() throws RemoteException {
1251 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1252 // Test that we respect the platform values when told to
1253 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT,
1254 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1255 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1256 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1257 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1258 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1259 mServiceContext.sendBroadcast(
1260 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1261 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1262 );
1263
1264 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1265 true);
1266 }
1267
1268 @Test
1269 public void testUpdateMobilePolicyCycleWithUserOverrides() throws RemoteException {
1270 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1271
1272 // inferred = false implies that a user manually modified this policy.
1273 NetworkPolicy policy = buildDefaultFakeMobilePolicy();
1274 policy.inferred = false;
1275 setNetworkPolicies(policy);
1276
1277 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1278 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, 9999);
1279 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1280 DATA_CYCLE_THRESHOLD_DISABLED);
1281 mServiceContext.sendBroadcast(
1282 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1283 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1284 );
1285
1286 // The policy still shouldn't change, because we don't want to overwrite user settings.
1287 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1288 false);
1289 }
1290
1291 @Test
1292 public void testUpdateMobilePolicyCycleUpdatesDataCycle() throws RemoteException {
1293 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1294
1295 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1296 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, 9999);
1297 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG, 9999);
1298 mServiceContext.sendBroadcast(
1299 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1300 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1301 );
1302
1303 assertNetworkPolicyEquals(31, 9999, 9999, true);
1304 }
1305
1306 @Test
1307 public void testUpdateMobilePolicyCycleDisableThresholds() throws RemoteException {
1308 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1309
1310 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1311 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1312 DATA_CYCLE_THRESHOLD_DISABLED);
1313 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1314 DATA_CYCLE_THRESHOLD_DISABLED);
1315 mServiceContext.sendBroadcast(
1316 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1317 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1318 );
1319
1320 assertNetworkPolicyEquals(31, WARNING_DISABLED, LIMIT_DISABLED, true);
1321 }
1322
1323 @Test
1324 public void testUpdateMobilePolicyCycleRevertsToDefault() throws RemoteException {
1325 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1326
1327 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1328 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1329 DATA_CYCLE_THRESHOLD_DISABLED);
1330 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1331 DATA_CYCLE_THRESHOLD_DISABLED);
1332 mServiceContext.sendBroadcast(
1333 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1334 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1335 );
1336 assertNetworkPolicyEquals(31, WARNING_DISABLED, LIMIT_DISABLED, true);
1337
1338 // If the user switches carriers to one that doesn't use a CarrierConfig, we should revert
1339 // to the default data limit and warning. The cycle date doesn't need to revert as it's
1340 // arbitrary anyways.
1341 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT,
1342 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1343 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1344 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1345 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1346 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1347 mServiceContext.sendBroadcast(
1348 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1349 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1350 );
1351
1352 assertNetworkPolicyEquals(31, mDefaultWarningBytes, mDefaultLimitBytes,
1353 true);
1354 }
1355
1356 private NetworkPolicy buildDefaultFakeMobilePolicy() {
1357 NetworkPolicy p = mService.buildDefaultMobilePolicy(FAKE_SUB_ID, FAKE_SUBSCRIBER_ID);
1358 // set a deterministic cycle date
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001359 p.cycleRule = new RecurrenceRule(
1360 p.cycleRule.start.withDayOfMonth(DEFAULT_CYCLE_DAY),
1361 p.cycleRule.end, Period.ofMonths(1));
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001362 return p;
1363 }
1364
1365 private static NetworkPolicy buildFakeMobilePolicy(int cycleDay, long warningBytes,
1366 long limitBytes, boolean inferred){
1367 final NetworkTemplate template = buildTemplateMobileAll(FAKE_SUBSCRIBER_ID);
Sudheer Shankaed25ce62017-03-29 20:46:30 -07001368 return new NetworkPolicy(template, cycleDay, new Time().timezone, warningBytes,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001369 limitBytes, SNOOZE_NEVER, SNOOZE_NEVER, true, inferred);
1370 }
1371
1372 private void assertNetworkPolicyEquals(int expectedCycleDay, long expectedWarningBytes,
1373 long expectedLimitBytes, boolean expectedInferred) {
1374 NetworkPolicy[] policies = mService.getNetworkPolicies(
1375 mServiceContext.getOpPackageName());
1376 assertEquals("Unexpected number of network policies", 1, policies.length);
1377 NetworkPolicy actualPolicy = policies[0];
1378 NetworkPolicy expectedPolicy = buildFakeMobilePolicy(expectedCycleDay, expectedWarningBytes,
1379 expectedLimitBytes, expectedInferred);
1380 assertEquals(expectedPolicy, actualPolicy);
1381 }
1382
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001383 private static long parseTime(String time) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06001384 return ZonedDateTime.parse(time).toInstant().toEpochMilli();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001385 }
1386
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07001387 private void setNetworkPolicies(NetworkPolicy... policies) {
1388 mService.setNetworkPolicies(policies);
1389 }
1390
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001391 private static NetworkState buildWifi() {
1392 final NetworkInfo info = new NetworkInfo(TYPE_WIFI, 0, null, null);
1393 info.setDetailedState(DetailedState.CONNECTED, null, null);
1394 final LinkProperties prop = new LinkProperties();
1395 prop.setInterfaceName(TEST_IFACE);
Stephen Chena1c92b72017-02-06 13:18:11 -08001396 final NetworkCapabilities networkCapabilities = new NetworkCapabilities();
1397 return new NetworkState(info, prop, networkCapabilities, null, null, TEST_SSID);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001398 }
1399
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001400 private void expectCurrentTime() throws Exception {
Felipe Lemeef134662016-08-10 14:46:39 -07001401 when(mTime.forceRefresh()).thenReturn(false);
1402 when(mTime.hasCache()).thenReturn(true);
1403 when(mTime.currentTimeMillis()).thenReturn(currentTimeMillis());
1404 when(mTime.getCacheAge()).thenReturn(0L);
1405 when(mTime.getCacheCertainty()).thenReturn(0L);
Jeff Sharkey2ef2aeb2011-06-15 11:01:31 -07001406 }
1407
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001408 private Future<String> expectEnqueueNotification() throws Exception {
Felipe Lemeef134662016-08-10 14:46:39 -07001409 final FutureAnswer<String> futureAnswer = new FutureAnswer<String>(2);
1410 doAnswer(futureAnswer).when(mNotifManager).enqueueNotificationWithTag(
1411 anyString(), anyString(), anyString() /* capture here (index 2)*/,
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001412 anyInt(), isA(Notification.class), anyInt());
Felipe Lemeef134662016-08-10 14:46:39 -07001413 return futureAnswer;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001414 }
1415
Felipe Leme3d3308d2016-08-23 17:41:47 -07001416 private void expectHasInternetPermission(int uid, boolean hasIt) throws Exception {
1417 when(mIpm.checkUidPermission(Manifest.permission.INTERNET, uid)).thenReturn(
1418 hasIt ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED);
1419 }
1420
Felipe Lemeef134662016-08-10 14:46:39 -07001421 private void verifySetInterfaceQuota(String iface, long quotaBytes) throws Exception {
1422 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001423 }
1424
Felipe Lemeef134662016-08-10 14:46:39 -07001425 private void verifyRemoveInterfaceQuota(String iface) throws Exception {
1426 verify(mNetworkManager, atLeastOnce()).removeInterfaceQuota(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001427 }
1428
Felipe Lemeef134662016-08-10 14:46:39 -07001429 private Future<Void> verifyPolicyDataEnable(int type, boolean enabled) throws Exception {
Jeff Sharkey32566012014-12-02 18:30:14 -08001430 // TODO: bring back this test
1431 return null;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001432 }
1433
Felipe Lemeef134662016-08-10 14:46:39 -07001434 private void verifyAdvisePersistThreshold() throws Exception {
1435 verify(mStatsService).advisePersistThreshold(anyLong());
Jeff Sharkey0cf6de02012-05-04 15:03:30 -07001436 }
1437
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001438 private static class TestAbstractFuture<T> extends AbstractFuture<T> {
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001439 @Override
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001440 public T get() throws InterruptedException, ExecutionException {
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001441 try {
1442 return get(5, TimeUnit.SECONDS);
1443 } catch (TimeoutException e) {
1444 throw new RuntimeException(e);
1445 }
1446 }
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001447 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001448
Felipe Lemeef134662016-08-10 14:46:39 -07001449 private static class FutureAnswer<T> extends TestAbstractFuture<T> implements Answer<Void> {
1450 private final int index;
1451
1452 FutureAnswer(int index) {
1453 this.index = index;
1454 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001455 @Override
Felipe Lemeef134662016-08-10 14:46:39 -07001456 public Void answer(InvocationOnMock invocation) throws Throwable {
1457 @SuppressWarnings("unchecked")
1458 T captured = (T) invocation.getArguments()[index];
1459 set(captured);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001460 return null;
1461 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001462 }
1463
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -07001464 private static void assertTimeEquals(long expected, long actual) {
1465 if (expected != actual) {
1466 fail("expected " + formatTime(expected) + " but was actually " + formatTime(actual));
1467 }
1468 }
1469
1470 private static String formatTime(long millis) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06001471 return Instant.ofEpochMilli(millis) + " [" + millis + "]";
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -07001472 }
1473
1474 private static void assertEqualsFuzzy(long expected, long actual, long fuzzy) {
1475 final long low = expected - fuzzy;
1476 final long high = expected + fuzzy;
1477 if (actual < low || actual > high) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06001478 fail("value " + formatTime(actual) + " is outside [" + formatTime(low) + ","
1479 + formatTime(high) + "]");
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -07001480 }
1481 }
1482
1483 private static void assertUnique(LinkedHashSet<Long> seen, Long value) {
1484 if (!seen.add(value)) {
1485 fail("found duplicate time " + value + " in series " + seen.toString());
1486 }
1487 }
1488
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001489 private static void assertNotificationType(int expected, String actualTag) {
Felipe Lemeef134662016-08-10 14:46:39 -07001490 assertEquals("notification type mismatch for '" + actualTag +"'",
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001491 Integer.toString(expected), actualTag.substring(actualTag.lastIndexOf(':') + 1));
1492 }
1493
Felipe Lemee88729d2016-08-17 16:43:01 -07001494 private void assertUidPolicy(int uid, int expected) {
1495 final int actual = mService.getUidPolicy(uid);
1496 if (expected != actual) {
1497 fail("Wrong policy for UID " + uid + ": expected " + uidPoliciesToString(expected)
1498 + ", actual " + uidPoliciesToString(actual));
1499 }
1500 }
1501
Felipe Leme46b451f2016-08-19 08:46:17 -07001502 private void assertWhitelistUids(int... uids) {
Felipe Leme57e3d312016-08-23 14:42:52 -07001503 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_ALLOW_METERED_BACKGROUND), uids);
Felipe Leme46b451f2016-08-19 08:46:17 -07001504 }
1505
Felipe Leme3d3308d2016-08-23 17:41:47 -07001506 private void assertRestrictBackgroundOn() throws Exception {
1507 assertTrue("restrictBackground should be set", mService.getRestrictBackground());
1508 }
1509
1510 private void assertRestrictBackgroundOff() throws Exception {
1511 assertFalse("restrictBackground should not be set", mService.getRestrictBackground());
1512 }
1513
1514 private FutureIntent newRestrictBackgroundChangedFuture() {
1515 return mServiceContext
1516 .nextBroadcastIntent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
1517 }
1518
1519 private void assertRestrictBackgroundChangedReceived(Future<Intent> future,
1520 String expectedPackage) throws Exception {
1521 final String action = ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED;
1522 final Intent intent = future.get(5, TimeUnit.SECONDS);
1523 assertNotNull("Didn't get a " + action + "intent in 5 seconds");
1524 assertEquals("Wrong package on " + action + " intent", expectedPackage, intent.getPackage());
1525 }
1526
Felipe Lemee88729d2016-08-17 16:43:01 -07001527 // TODO: replace by Truth, Hamcrest, or a similar tool.
1528 private void assertContainsInAnyOrder(int[] actual, int...expected) {
1529 final StringBuilder errors = new StringBuilder();
1530 if (actual.length != expected.length) {
1531 errors.append("\tsize does not match\n");
1532 }
1533 final List<Integer> actualList =
1534 Arrays.stream(actual).boxed().collect(Collectors.<Integer>toList());
1535 final List<Integer> expectedList =
1536 Arrays.stream(expected).boxed().collect(Collectors.<Integer>toList());
1537 if (!actualList.containsAll(expectedList)) {
1538 errors.append("\tmissing elements on actual list\n");
1539 }
1540 if (!expectedList.containsAll(actualList)) {
1541 errors.append("\tmissing elements on expected list\n");
1542 }
1543 if (errors.length() > 0) {
1544 fail("assertContainsInAnyOrder(expected=" + Arrays.toString(expected)
1545 + ", actual=" + Arrays.toString(actual) +") failed: \n" + errors);
1546 }
1547 }
1548
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001549 private long getElapsedRealtime() {
1550 return mElapsedRealtime;
1551 }
1552
1553 private void setCurrentTimeMillis(long currentTimeMillis) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001554 RecurrenceRule.sClock = Clock.fixed(Instant.ofEpochMilli(currentTimeMillis),
1555 ZoneId.systemDefault());
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001556 mStartTime = currentTimeMillis;
1557 mElapsedRealtime = 0L;
1558 }
1559
1560 private long currentTimeMillis() {
1561 return mStartTime + mElapsedRealtime;
1562 }
1563
1564 private void incrementCurrentTime(long duration) {
1565 mElapsedRealtime += duration;
1566 }
1567
Felipe Leme3d3308d2016-08-23 17:41:47 -07001568 private FutureIntent mRestrictBackgroundChanged;
1569
1570 private void setRestrictBackground(boolean flag) throws Exception {
Felipe Leme3d3308d2016-08-23 17:41:47 -07001571 mService.setRestrictBackground(flag);
1572 // Sanity check.
1573 assertEquals("restrictBackground not set", flag, mService.getRestrictBackground());
1574 }
1575
Felipe Lemeef134662016-08-10 14:46:39 -07001576 /**
1577 * Creates a mock and registers it to {@link LocalServices}.
1578 */
Felipe Leme9f27e7a2016-08-12 15:19:40 -07001579 private static <T> T addLocalServiceMock(Class<T> clazz) {
Felipe Lemeef134662016-08-10 14:46:39 -07001580 final T mock = mock(clazz);
Felipe Lemeef134662016-08-10 14:46:39 -07001581 LocalServices.addService(clazz, mock);
Felipe Lemeef134662016-08-10 14:46:39 -07001582 return mock;
1583 }
1584
1585 /**
Felipe Lemeef134662016-08-10 14:46:39 -07001586 * Custom Mockito answer used to verify async {@link INetworkPolicyListener} calls.
1587 *
1588 * <p>Typical usage:
1589 * <pre><code>
1590 * mPolicyListener.expect().someCallback(any());
1591 * // do something on objects under test
1592 * mPolicyListener.waitAndVerify().someCallback(eq(expectedValue));
1593 * </code></pre>
1594 */
1595 final class NetworkPolicyListenerAnswer implements Answer<Void> {
1596 private CountDownLatch latch;
1597 private final INetworkPolicyListener listener;
1598
1599 NetworkPolicyListenerAnswer(NetworkPolicyManagerService service) {
1600 this.listener = mock(INetworkPolicyListener.class);
1601 // RemoteCallbackList needs a binder to use as key
1602 when(listener.asBinder()).thenReturn(new Binder());
1603 service.registerListener(listener);
1604 }
1605
1606 @Override
1607 public Void answer(InvocationOnMock invocation) throws Throwable {
1608 Log.d(TAG,"counting down on answer: " + invocation);
1609 latch.countDown();
1610 return null;
1611 }
1612
1613 INetworkPolicyListener expect() {
1614 assertNull("expect() called before waitAndVerify()", latch);
1615 latch = new CountDownLatch(1);
1616 return doAnswer(this).when(listener);
1617 }
1618
1619 INetworkPolicyListener waitAndVerify() {
1620 assertNotNull("waitAndVerify() called before expect()", latch);
1621 try {
1622 assertTrue("callback not called in 5 seconds", latch.await(5, TimeUnit.SECONDS));
1623 } catch (InterruptedException e) {
1624 fail("Thread interrupted before callback called");
1625 } finally {
1626 latch = null;
1627 }
1628 return verify(listener, atLeastOnce());
1629 }
Felipe Leme3d3308d2016-08-23 17:41:47 -07001630
1631 INetworkPolicyListener verifyNotCalled() {
1632 return verify(listener, never());
1633 }
1634
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001635 }
Felipe Lemee88729d2016-08-17 16:43:01 -07001636
1637 private void setNetpolicyXml(Context context) throws Exception {
1638 mPolicyDir = context.getFilesDir();
1639 if (mPolicyDir.exists()) {
1640 IoUtils.deleteContents(mPolicyDir);
1641 }
1642 if (!TextUtils.isEmpty(mNetpolicyXml)) {
1643 final String assetPath = NETPOLICY_DIR + "/" + mNetpolicyXml;
1644 final File netConfigFile = new File(mPolicyDir, "netpolicy.xml");
1645 Log.d(TAG, "Creating " + netConfigFile + " from asset " + assetPath);
1646 try (final InputStream in = context.getResources().getAssets().open(assetPath);
1647 final OutputStream out = new FileOutputStream(netConfigFile)) {
1648 Streams.copy(in, out);
1649 }
1650 }
1651 }
1652
1653 /**
1654 * Annotation used to define the relative path of the {@code netpolicy.xml} file.
1655 */
1656 @Retention(RetentionPolicy.RUNTIME)
1657 @Target(ElementType.METHOD)
1658 public @interface NetPolicyXml {
1659
1660 public String value() default "";
1661
1662 }
1663
1664 /**
1665 * Rule used to set {@code mNetPolicyXml} according to the {@link NetPolicyXml} annotation.
1666 */
1667 public static class NetPolicyMethodRule implements MethodRule {
1668
1669 @Override
1670 public Statement apply(Statement base, FrameworkMethod method, Object target) {
1671 for (Annotation annotation : method.getAnnotations()) {
1672 if ((annotation instanceof NetPolicyXml)) {
1673 final String path = ((NetPolicyXml) annotation).value();
1674 if (!path.isEmpty()) {
1675 ((NetworkPolicyManagerServiceTest) target).mNetpolicyXml = path;
1676 break;
1677 }
1678 }
1679 }
1680 return base;
1681 }
1682 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001683}