blob: d31d550ae90242d6f435d35fd0590a8b0c247283 [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 Sharkey2e471452018-01-19 18:02:47 +090021import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -070022import static android.net.NetworkPolicy.LIMIT_DISABLED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070023import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -070024import static android.net.NetworkPolicy.WARNING_DISABLED;
Felipe Leme46b451f2016-08-19 08:46:17 -070025import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070026import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070027import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemee88729d2016-08-17 16:43:01 -070028import static android.net.NetworkPolicyManager.uidPoliciesToString;
Jeff Sharkeye0c29952018-02-20 17:24:55 -070029import static android.net.NetworkStats.IFACE_ALL;
30import static android.net.NetworkStats.SET_ALL;
31import static android.net.NetworkStats.TAG_ALL;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070032import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080033import static android.net.TrafficStats.MB_IN_BYTES;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070034import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070035import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
Jeff Sharkey53313d72017-07-13 16:47:32 -060036import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070037import static android.telephony.CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG;
38import static android.telephony.CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG;
39import static android.telephony.CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -070040import static android.telephony.SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED;
Jeff Sharkey9bf31502012-03-09 17:07:21 -080041import static android.text.format.Time.TIMEZONE_UTC;
Felipe Lemeef134662016-08-10 14:46:39 -070042
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070043import static com.android.server.net.NetworkPolicyManagerService.TYPE_LIMIT;
44import static com.android.server.net.NetworkPolicyManagerService.TYPE_LIMIT_SNOOZED;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -070045import static com.android.server.net.NetworkPolicyManagerService.TYPE_RAPID;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070046import static com.android.server.net.NetworkPolicyManagerService.TYPE_WARNING;
Jeff Sharkey53313d72017-07-13 16:47:32 -060047
Felipe Leme9f27e7a2016-08-12 15:19:40 -070048import static org.junit.Assert.assertEquals;
49import static org.junit.Assert.assertFalse;
50import static org.junit.Assert.assertNotNull;
51import static org.junit.Assert.assertNull;
52import static org.junit.Assert.assertTrue;
53import static org.junit.Assert.fail;
Jeff Sharkey53313d72017-07-13 16:47:32 -060054import static org.mockito.ArgumentMatchers.any;
Sudheer Shanka543339f2017-07-28 15:18:07 -070055import static org.mockito.ArgumentMatchers.anyBoolean;
Jeff Sharkey53313d72017-07-13 16:47:32 -060056import static org.mockito.ArgumentMatchers.anyInt;
57import static org.mockito.ArgumentMatchers.anyLong;
58import static org.mockito.ArgumentMatchers.anyString;
59import static org.mockito.ArgumentMatchers.eq;
60import static org.mockito.ArgumentMatchers.isA;
61import static org.mockito.ArgumentMatchers.isNull;
jackqdyulei29c82ab2017-03-10 14:09:16 -080062import static org.mockito.Mockito.atLeast;
Felipe Lemeef134662016-08-10 14:46:39 -070063import static org.mockito.Mockito.atLeastOnce;
64import static org.mockito.Mockito.doAnswer;
65import static org.mockito.Mockito.mock;
Felipe Leme3d3308d2016-08-23 17:41:47 -070066import static org.mockito.Mockito.never;
Jeff Sharkey2e471452018-01-19 18:02:47 +090067import static org.mockito.Mockito.reset;
Felipe Lemeef134662016-08-10 14:46:39 -070068import static org.mockito.Mockito.verify;
69import static org.mockito.Mockito.when;
70
Felipe Leme3d3308d2016-08-23 17:41:47 -070071import android.Manifest;
Felipe Lemeef134662016-08-10 14:46:39 -070072import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -080073import android.app.ActivityManagerInternal;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070074import android.app.IActivityManager;
Felipe Lemeef134662016-08-10 14:46:39 -070075import android.app.IUidObserver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070076import android.app.Notification;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -070077import android.app.NotificationManager;
Felipe Lemeef134662016-08-10 14:46:39 -070078import android.app.usage.UsageStatsManagerInternal;
79import android.content.Context;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070080import android.content.Intent;
Felipe Lemeef134662016-08-10 14:46:39 -070081import android.content.pm.ApplicationInfo;
Felipe Leme3d3308d2016-08-23 17:41:47 -070082import android.content.pm.IPackageManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070083import android.content.pm.PackageInfo;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070084import android.content.pm.PackageManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070085import android.content.pm.Signature;
Felipe Leme3d3308d2016-08-23 17:41:47 -070086import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070087import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070088import android.net.INetworkManagementEventObserver;
Jeff Sharkey9599cc52011-05-22 14:59:31 -070089import android.net.INetworkPolicyListener;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070090import android.net.LinkProperties;
Jeff Sharkey2e471452018-01-19 18:02:47 +090091import android.net.Network;
Stephen Chena1c92b72017-02-06 13:18:11 -080092import android.net.NetworkCapabilities;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070093import android.net.NetworkInfo;
94import android.net.NetworkInfo.DetailedState;
95import android.net.NetworkPolicy;
96import android.net.NetworkState;
97import android.net.NetworkStats;
Jeff Sharkey2e471452018-01-19 18:02:47 +090098import android.net.NetworkStatsHistory;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070099import android.net.NetworkTemplate;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900100import android.net.StringNetworkSpecifier;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700101import android.os.Binder;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700102import android.os.INetworkManagementService;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700103import android.os.PersistableBundle;
Felipe Lemeef134662016-08-10 14:46:39 -0700104import android.os.PowerManagerInternal;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800105import android.os.PowerSaveState;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700106import android.os.RemoteException;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700107import android.os.SimpleClock;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700108import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700109import android.os.UserHandle;
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700110import android.support.test.InstrumentationRegistry;
111import android.support.test.runner.AndroidJUnit4;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700112import android.telephony.CarrierConfigManager;
113import android.telephony.SubscriptionManager;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900114import android.telephony.SubscriptionPlan;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700115import android.telephony.TelephonyManager;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700116import android.test.suitebuilder.annotation.MediumTest;
Felipe Lemee88729d2016-08-17 16:43:01 -0700117import android.text.TextUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700118import android.text.format.Time;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900119import android.util.DataUnit;
Felipe Lemeef134662016-08-10 14:46:39 -0700120import android.util.Log;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600121import android.util.Pair;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600122import android.util.RecurrenceRule;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700123
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700124import com.android.internal.telephony.PhoneConstants;
Lorenzo Colitti281a17c2016-10-28 12:56:03 +0900125import com.android.internal.util.test.BroadcastInterceptingContext;
126import com.android.internal.util.test.BroadcastInterceptingContext.FutureIntent;
Felipe Lemeef134662016-08-10 14:46:39 -0700127import com.android.server.net.NetworkPolicyManagerInternal;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700128import com.android.server.net.NetworkPolicyManagerService;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700129import com.android.server.net.NetworkStatsManagerInternal;
Felipe Lemeef134662016-08-10 14:46:39 -0700130
131import libcore.io.IoUtils;
Felipe Lemee88729d2016-08-17 16:43:01 -0700132import libcore.io.Streams;
Felipe Lemeef134662016-08-10 14:46:39 -0700133
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700134import com.google.common.util.concurrent.AbstractFuture;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700135
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700136import org.junit.After;
137import org.junit.Before;
Felipe Lemee88729d2016-08-17 16:43:01 -0700138import org.junit.Rule;
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700139import org.junit.Test;
Felipe Lemee88729d2016-08-17 16:43:01 -0700140import org.junit.rules.MethodRule;
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700141import org.junit.runner.RunWith;
Felipe Lemee88729d2016-08-17 16:43:01 -0700142import org.junit.runners.model.FrameworkMethod;
143import org.junit.runners.model.Statement;
Felipe Lemeef134662016-08-10 14:46:39 -0700144import org.mockito.ArgumentCaptor;
145import org.mockito.Mock;
146import org.mockito.MockitoAnnotations;
147import org.mockito.invocation.InvocationOnMock;
148import org.mockito.stubbing.Answer;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700149
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700150import java.io.File;
Felipe Lemee88729d2016-08-17 16:43:01 -0700151import java.io.FileOutputStream;
152import java.io.InputStream;
153import java.io.OutputStream;
154import java.lang.annotation.Annotation;
155import java.lang.annotation.ElementType;
156import java.lang.annotation.Retention;
157import java.lang.annotation.RetentionPolicy;
158import java.lang.annotation.Target;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600159import java.time.Clock;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600160import java.time.Instant;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600161import java.time.Period;
162import java.time.ZoneId;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700163import java.time.ZoneOffset;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600164import java.time.ZonedDateTime;
Felipe Lemee88729d2016-08-17 16:43:01 -0700165import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700166import java.util.Calendar;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600167import java.util.Iterator;
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700168import java.util.LinkedHashSet;
Felipe Lemeef134662016-08-10 14:46:39 -0700169import java.util.List;
170import java.util.concurrent.CountDownLatch;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700171import java.util.concurrent.ExecutionException;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700172import java.util.concurrent.Future;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700173import java.util.concurrent.TimeUnit;
174import java.util.concurrent.TimeoutException;
Felipe Lemee88729d2016-08-17 16:43:01 -0700175import java.util.stream.Collectors;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700176
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700177/**
178 * Tests for {@link NetworkPolicyManagerService}.
Felipe Lemeb8d572e2016-12-05 13:41:43 -0800179 *
180 * <p>Typical usage:
181 *
182 * <pre><code>
183 m -j32 FrameworksServicesTests && adb install -r -g \
184 ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk && \
185 adb shell am instrument -e class "com.android.server.NetworkPolicyManagerServiceTest" -w \
186 "com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner"
187 * </code></pre>
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700188 */
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700189@RunWith(AndroidJUnit4.class)
Felipe Leme3d3308d2016-08-23 17:41:47 -0700190@MediumTest
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700191public class NetworkPolicyManagerServiceTest {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700192 private static final String TAG = "NetworkPolicyManagerServiceTest";
193
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700194 private static final long TEST_START = 1194220800000L;
195 private static final String TEST_IFACE = "test0";
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700196 private static final String TEST_SSID = "AndroidAP";
Jeff Sharkey2e471452018-01-19 18:02:47 +0900197 private static final String TEST_IMSI = "310210";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700198 private static final int TEST_SUB_ID = 42;
199 private static final int TEST_NET_ID = 24;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700200
Jeff Sharkeye8914c32012-05-01 16:26:09 -0700201 private static NetworkTemplate sTemplateWifi = NetworkTemplate.buildTemplateWifi(TEST_SSID);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700202
Felipe Lemee88729d2016-08-17 16:43:01 -0700203 /**
204 * Path on assets where files used by {@link NetPolicyXml} are located.
205 */
206 private static final String NETPOLICY_DIR = "NetworkPolicyManagerServiceTest/netpolicy";
207
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700208 private BroadcastInterceptingContext mServiceContext;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700209 private File mPolicyDir;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700210
Felipe Lemee88729d2016-08-17 16:43:01 -0700211 /**
212 * Relative path of the XML file that will be used as {@code netpolicy.xml}.
213 *
214 * <p>Typically set through a {@link NetPolicyXml} annotation in the test method.
215 */
216 private String mNetpolicyXml;
217
Felipe Lemeef134662016-08-10 14:46:39 -0700218 private @Mock IActivityManager mActivityManager;
Felipe Lemeef134662016-08-10 14:46:39 -0700219 private @Mock INetworkManagementService mNetworkManager;
Felipe Lemeef134662016-08-10 14:46:39 -0700220 private @Mock IConnectivityManager mConnManager;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700221 private @Mock NotificationManager mNotifManager;
Felipe Lemeef134662016-08-10 14:46:39 -0700222 private @Mock PackageManager mPackageManager;
Felipe Leme3d3308d2016-08-23 17:41:47 -0700223 private @Mock IPackageManager mIpm;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700224 private @Mock SubscriptionManager mSubscriptionManager;
225 private @Mock CarrierConfigManager mCarrierConfigManager;
226 private @Mock TelephonyManager mTelephonyManager;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700227
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700228 private ActivityManagerInternal mActivityManagerInternal;
229 private NetworkStatsManagerInternal mStatsService;
Sudheer Shankae7361852017-03-07 11:51:46 -0800230
Felipe Lemeef134662016-08-10 14:46:39 -0700231 private IUidObserver mUidObserver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700232 private INetworkManagementEventObserver mNetworkObserver;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700233
Felipe Lemeef134662016-08-10 14:46:39 -0700234 private NetworkPolicyListenerAnswer mPolicyListener;
235 private NetworkPolicyManagerService mService;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700236
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700237 /**
238 * In some of the tests while initializing NetworkPolicyManagerService,
239 * ACTION_RESTRICT_BACKGROUND_CHANGED is broadcasted. This is for capturing that broadcast.
240 */
241 private FutureIntent mFutureIntent;
242
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700243 private long mStartTime;
244 private long mElapsedRealtime;
245
Jeff Sharkeycae04a22012-03-22 15:18:52 -0700246 private static final int USER_ID = 0;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700247 private static final int FAKE_SUB_ID = 3737373;
248 private static final String FAKE_SUBSCRIBER_ID = "FAKE_SUB_ID";
249 private static final int DEFAULT_CYCLE_DAY = 1;
250 private static final int INVALID_CARRIER_CONFIG_VALUE = -9999;
251 private long mDefaultWarningBytes; // filled in with the actual default before tests are run
252 private long mDefaultLimitBytes; // filled in with the actual default before tests are run
Jeff Sharkeycae04a22012-03-22 15:18:52 -0700253
Felipe Lemee88729d2016-08-17 16:43:01 -0700254 private static final int APP_ID_A = android.os.Process.FIRST_APPLICATION_UID + 4;
255 private static final int APP_ID_B = android.os.Process.FIRST_APPLICATION_UID + 8;
256 private static final int APP_ID_C = android.os.Process.FIRST_APPLICATION_UID + 15;
257 private static final int APP_ID_D = android.os.Process.FIRST_APPLICATION_UID + 16;
258 private static final int APP_ID_E = android.os.Process.FIRST_APPLICATION_UID + 23;
259 private static final int APP_ID_F = android.os.Process.FIRST_APPLICATION_UID + 42;
Jeff Sharkeycae04a22012-03-22 15:18:52 -0700260
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700261 private static final int UID_A = UserHandle.getUid(USER_ID, APP_ID_A);
262 private static final int UID_B = UserHandle.getUid(USER_ID, APP_ID_B);
Felipe Lemee88729d2016-08-17 16:43:01 -0700263 private static final int UID_C = UserHandle.getUid(USER_ID, APP_ID_C);
264 private static final int UID_D = UserHandle.getUid(USER_ID, APP_ID_D);
265 private static final int UID_E = UserHandle.getUid(USER_ID, APP_ID_E);
266 private static final int UID_F = UserHandle.getUid(USER_ID, APP_ID_F);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700267
Felipe Lemeef134662016-08-10 14:46:39 -0700268 private static final String PKG_NAME_A = "name.is.A,pkg.A";
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700269 private static final String PKG_NAME_B = "name.is.B,pkg.B";
270 private static final String PKG_NAME_C = "name.is.C,pkg.C";
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700271
Felipe Lemee88729d2016-08-17 16:43:01 -0700272 public final @Rule NetPolicyMethodRule mNetPolicyXmlRule = new NetPolicyMethodRule();
273
Jeff Sharkey9911a282018-02-14 22:29:11 -0700274 private final Clock mClock = new SimpleClock(ZoneOffset.UTC) {
275 @Override
276 public long millis() {
277 return currentTimeMillis();
278 }
279 };
280
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700281 private void registerLocalServices() {
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700282 addLocalServiceMock(DeviceIdleController.LocalService.class);
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700283
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700284 final UsageStatsManagerInternal usageStats =
285 addLocalServiceMock(UsageStatsManagerInternal.class);
286 when(usageStats.getIdleUidsForUser(anyInt())).thenReturn(new int[]{});
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700287
Sudheer Shankae7361852017-03-07 11:51:46 -0800288 mActivityManagerInternal = addLocalServiceMock(ActivityManagerInternal.class);
jackqdyulei29c82ab2017-03-10 14:09:16 -0800289
290 final PowerSaveState state = new PowerSaveState.Builder()
291 .setBatterySaverEnabled(false).build();
292 final PowerManagerInternal pmInternal = addLocalServiceMock(PowerManagerInternal.class);
293 when(pmInternal.getLowPowerState(anyInt())).thenReturn(state);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700294
295 mStatsService = addLocalServiceMock(NetworkStatsManagerInternal.class);
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700296 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700297
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700298 @Before
299 public void callSystemReady() throws Exception {
Felipe Lemeef134662016-08-10 14:46:39 -0700300 MockitoAnnotations.initMocks(this);
301
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700302 final Context context = InstrumentationRegistry.getContext();
Felipe Lemeef134662016-08-10 14:46:39 -0700303
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700304 setCurrentTimeMillis(TEST_START);
305
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700306 registerLocalServices();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700307 // Intercept various broadcasts, and pretend that uids have packages.
308 // Also return mock service instances for a few critical services.
Felipe Lemeef134662016-08-10 14:46:39 -0700309 mServiceContext = new BroadcastInterceptingContext(context) {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700310 @Override
311 public PackageManager getPackageManager() {
Felipe Lemeef134662016-08-10 14:46:39 -0700312 return mPackageManager;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700313 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700314
315 @Override
316 public void startActivity(Intent intent) {
317 // ignored
318 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700319
320 @Override
321 public Object getSystemService(String name) {
322 switch (name) {
323 case Context.TELEPHONY_SUBSCRIPTION_SERVICE:
324 return mSubscriptionManager;
325 case Context.CARRIER_CONFIG_SERVICE:
326 return mCarrierConfigManager;
327 case Context.TELEPHONY_SERVICE:
328 return mTelephonyManager;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700329 case Context.NOTIFICATION_SERVICE:
330 return mNotifManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700331 default:
332 return super.getSystemService(name);
333 }
334 }
Jeff Sharkey2e471452018-01-19 18:02:47 +0900335
336 @Override
337 public void enforceCallingOrSelfPermission(String permission, String message) {
338 // Assume that we're AID_SYSTEM
339 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700340 };
341
Felipe Lemee88729d2016-08-17 16:43:01 -0700342 setNetpolicyXml(context);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700343
Felipe Lemeef134662016-08-10 14:46:39 -0700344 doAnswer(new Answer<Void>() {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700345
Felipe Lemeef134662016-08-10 14:46:39 -0700346 @Override
347 public Void answer(InvocationOnMock invocation) throws Throwable {
348 mUidObserver = (IUidObserver) invocation.getArguments()[0];
349 Log.d(TAG, "set mUidObserver to " + mUidObserver);
350 return null;
351 }
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800352 }).when(mActivityManager).registerUidObserver(any(), anyInt(),
Felipe Lemeb8d572e2016-12-05 13:41:43 -0800353 eq(ActivityManager.PROCESS_STATE_UNKNOWN), isNull(String.class));
Felipe Lemeef134662016-08-10 14:46:39 -0700354
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700355 mFutureIntent = newRestrictBackgroundChangedFuture();
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700356 mService = new NetworkPolicyManagerService(mServiceContext, mActivityManager,
Jeff Sharkey9911a282018-02-14 22:29:11 -0700357 mNetworkManager, mIpm, mClock, mPolicyDir, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700358 mService.bindConnectivityManager(mConnManager);
Felipe Lemeef134662016-08-10 14:46:39 -0700359 mPolicyListener = new NetworkPolicyListenerAnswer(mService);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700360
Felipe Lemeef134662016-08-10 14:46:39 -0700361 // Sets some common expectations.
362 when(mPackageManager.getPackageInfo(anyString(), anyInt())).thenAnswer(
363 new Answer<PackageInfo>() {
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700364
Felipe Lemeef134662016-08-10 14:46:39 -0700365 @Override
366 public PackageInfo answer(InvocationOnMock invocation) throws Throwable {
367 final String packageName = (String) invocation.getArguments()[0];
368 final PackageInfo info = new PackageInfo();
369 final Signature signature;
370 if ("android".equals(packageName)) {
371 signature = new Signature("F00D");
372 } else {
373 signature = new Signature("DEAD");
374 }
375 info.signatures = new Signature[] {
376 signature
377 };
378 return info;
379 }
380 });
381 when(mPackageManager.getApplicationInfoAsUser(anyString(), anyInt(), anyInt()))
382 .thenReturn(new ApplicationInfo());
383 when(mPackageManager.getPackagesForUid(UID_A)).thenReturn(new String[] {PKG_NAME_A});
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700384 when(mPackageManager.getPackagesForUid(UID_B)).thenReturn(new String[] {PKG_NAME_B});
385 when(mPackageManager.getPackagesForUid(UID_C)).thenReturn(new String[] {PKG_NAME_C});
386 when(mPackageManager.getApplicationInfo(eq(PKG_NAME_A), anyInt()))
387 .thenReturn(buildApplicationInfo(PKG_NAME_A));
388 when(mPackageManager.getApplicationInfo(eq(PKG_NAME_B), anyInt()))
389 .thenReturn(buildApplicationInfo(PKG_NAME_B));
390 when(mPackageManager.getApplicationInfo(eq(PKG_NAME_C), anyInt()))
391 .thenReturn(buildApplicationInfo(PKG_NAME_C));
Felipe Lemeef134662016-08-10 14:46:39 -0700392 when(mNetworkManager.isBandwidthControlEnabled()).thenReturn(true);
Sudheer Shanka543339f2017-07-28 15:18:07 -0700393 when(mNetworkManager.setDataSaverModeEnabled(anyBoolean())).thenReturn(true);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700394
Felipe Lemeef134662016-08-10 14:46:39 -0700395 // Prepare NPMS.
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800396 mService.systemReady(mService.networkScoreAndNetworkManagementServiceReady());
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700397
Felipe Lemeef134662016-08-10 14:46:39 -0700398 // catch INetworkManagementEventObserver during systemReady()
Felipe Leme3d3308d2016-08-23 17:41:47 -0700399 final ArgumentCaptor<INetworkManagementEventObserver> networkObserver =
Felipe Lemeef134662016-08-10 14:46:39 -0700400 ArgumentCaptor.forClass(INetworkManagementEventObserver.class);
401 verify(mNetworkManager).registerObserver(networkObserver.capture());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700402 mNetworkObserver = networkObserver.getValue();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700403
404 NetworkPolicy defaultPolicy = mService.buildDefaultMobilePolicy(0, "");
405 mDefaultWarningBytes = defaultPolicy.warningBytes;
406 mDefaultLimitBytes = defaultPolicy.limitBytes;
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700407 }
408
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700409 @After
410 public void removeFiles() throws Exception {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700411 for (File file : mPolicyDir.listFiles()) {
412 file.delete();
413 }
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700414 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700415
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700416 @After
417 public void unregisterLocalServices() throws Exception {
418 // Registered by NetworkPolicyManagerService's constructor.
Felipe Lemeef134662016-08-10 14:46:39 -0700419 LocalServices.removeServiceForTest(NetworkPolicyManagerInternal.class);
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700420
421 // Added in registerLocalServices()
422 LocalServices.removeServiceForTest(ActivityManagerInternal.class);
423 LocalServices.removeServiceForTest(PowerManagerInternal.class);
424 LocalServices.removeServiceForTest(DeviceIdleController.LocalService.class);
425 LocalServices.removeServiceForTest(UsageStatsManagerInternal.class);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700426 LocalServices.removeServiceForTest(NetworkStatsManagerInternal.class);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700427 }
428
Jeff Sharkey53313d72017-07-13 16:47:32 -0600429 @After
430 public void resetClock() throws Exception {
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600431 RecurrenceRule.sClock = Clock.systemDefaultZone();
Jeff Sharkey53313d72017-07-13 16:47:32 -0600432 }
433
Felipe Lemee88729d2016-08-17 16:43:01 -0700434 @Test
Felipe Leme3d3308d2016-08-23 17:41:47 -0700435 public void testTurnRestrictBackgroundOn() throws Exception {
436 assertRestrictBackgroundOff(); // Sanity check.
437 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
438 setRestrictBackground(true);
439 assertRestrictBackgroundChangedReceived(futureIntent, null);
440 }
441
442 @Test
443 @NetPolicyXml("restrict-background-on.xml")
444 public void testTurnRestrictBackgroundOff() throws Exception {
445 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700446 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700447 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
448 setRestrictBackground(false);
449 assertRestrictBackgroundChangedReceived(futureIntent, null);
450 }
451
452 /**
453 * Adds whitelist when restrict background is on - app should receive an intent.
454 */
455 @Test
456 @NetPolicyXml("restrict-background-on.xml")
457 public void testAddRestrictBackgroundWhitelist_restrictBackgroundOn() throws Exception {
458 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700459 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700460 addRestrictBackgroundWhitelist(true);
461 }
462
463 /**
464 * Adds whitelist when restrict background is off - app should not receive an intent.
465 */
466 @Test
467 public void testAddRestrictBackgroundWhitelist_restrictBackgroundOff() throws Exception {
468 assertRestrictBackgroundOff(); // Sanity check.
469 addRestrictBackgroundWhitelist(false);
470 }
471
472 private void addRestrictBackgroundWhitelist(boolean expectIntent) throws Exception {
Felipe Leme57e3d312016-08-23 14:42:52 -0700473 // Sanity checks.
474 assertWhitelistUids();
475 assertUidPolicy(UID_A, POLICY_NONE);
476
Felipe Leme3d3308d2016-08-23 17:41:47 -0700477 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700478 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700479
Felipe Leme57e3d312016-08-23 14:42:52 -0700480 mService.setUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700481
482 assertWhitelistUids(UID_A);
Felipe Leme57e3d312016-08-23 14:42:52 -0700483 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700484 mPolicyListener.waitAndVerify()
485 .onUidPoliciesChanged(APP_ID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700486 if (expectIntent) {
487 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
488 } else {
489 futureIntent.assertNotReceived();
490 }
491 }
492
493 /**
494 * Removes whitelist when restrict background is on - app should receive an intent.
495 */
496 @Test
497 @NetPolicyXml("uidA-whitelisted-restrict-background-on.xml")
498 public void testRemoveRestrictBackgroundWhitelist_restrictBackgroundOn() throws Exception {
499 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700500 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700501 removeRestrictBackgroundWhitelist(true);
502 }
503
504 /**
505 * Removes whitelist when restrict background is off - app should not receive an intent.
506 */
507 @Test
508 @NetPolicyXml("uidA-whitelisted-restrict-background-off.xml")
509 public void testRemoveRestrictBackgroundWhitelist_restrictBackgroundOff() throws Exception {
510 assertRestrictBackgroundOff(); // Sanity check.
511 removeRestrictBackgroundWhitelist(false);
512 }
513
jackqdyulei29c82ab2017-03-10 14:09:16 -0800514 @Test
515 public void testLowPowerModeObserver_ListenersRegistered()
516 throws Exception {
517 PowerManagerInternal pmInternal = LocalServices.getService(PowerManagerInternal.class);
518
519 verify(pmInternal, atLeast(2)).registerLowPowerModeObserver(any());
520 }
521
522 @Test
523 public void updateRestrictBackgroundByLowPowerMode_RestrictOnBeforeBsm_RestrictOnAfterBsm()
524 throws Exception {
525 setRestrictBackground(true);
526 PowerSaveState stateOn = new PowerSaveState.Builder()
527 .setGlobalBatterySaverEnabled(true)
528 .setBatterySaverEnabled(false)
529 .build();
530 mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
531
532 // RestrictBackground should be on even though battery saver want to turn it off
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700533 assertTrue(mService.getRestrictBackground());
jackqdyulei29c82ab2017-03-10 14:09:16 -0800534
535 PowerSaveState stateOff = new PowerSaveState.Builder()
536 .setGlobalBatterySaverEnabled(false)
537 .setBatterySaverEnabled(false)
538 .build();
539 mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
540
541 // RestrictBackground should be on, following its previous state
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700542 assertTrue(mService.getRestrictBackground());
jackqdyulei29c82ab2017-03-10 14:09:16 -0800543 }
544
545 @Test
546 public void updateRestrictBackgroundByLowPowerMode_RestrictOffBeforeBsm_RestrictOffAfterBsm()
547 throws Exception {
548 setRestrictBackground(false);
549 PowerSaveState stateOn = new PowerSaveState.Builder()
550 .setGlobalBatterySaverEnabled(true)
551 .setBatterySaverEnabled(true)
552 .build();
553
jackqdyulei29c82ab2017-03-10 14:09:16 -0800554 mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
555
556 // RestrictBackground should be turned on because of battery saver
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700557 assertTrue(mService.getRestrictBackground());
jackqdyulei29c82ab2017-03-10 14:09:16 -0800558
559 PowerSaveState stateOff = new PowerSaveState.Builder()
560 .setGlobalBatterySaverEnabled(false)
561 .setBatterySaverEnabled(false)
562 .build();
563 mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
564
565 // RestrictBackground should be off, following its previous state
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700566 assertFalse(mService.getRestrictBackground());
jackqdyulei29c82ab2017-03-10 14:09:16 -0800567 }
568
569 @Test
570 public void updateRestrictBackgroundByLowPowerMode_StatusChangedInBsm_DoNotRestore()
571 throws Exception {
572 setRestrictBackground(true);
573 PowerSaveState stateOn = new PowerSaveState.Builder()
574 .setGlobalBatterySaverEnabled(true)
575 .setBatterySaverEnabled(true)
576 .build();
577 mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
578
579 // RestrictBackground should still be on
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700580 assertTrue(mService.getRestrictBackground());
jackqdyulei29c82ab2017-03-10 14:09:16 -0800581
582 // User turns off RestrictBackground manually
583 setRestrictBackground(false);
584 PowerSaveState stateOff = new PowerSaveState.Builder().setBatterySaverEnabled(
585 false).build();
586 mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
587
588 // RestrictBackground should be off because user changes it manually
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700589 assertFalse(mService.getRestrictBackground());
jackqdyulei29c82ab2017-03-10 14:09:16 -0800590 }
591
Felipe Leme3d3308d2016-08-23 17:41:47 -0700592 private void removeRestrictBackgroundWhitelist(boolean expectIntent) throws Exception {
Felipe Leme57e3d312016-08-23 14:42:52 -0700593 // Sanity checks.
594 assertWhitelistUids(UID_A);
595 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
596
Felipe Leme3d3308d2016-08-23 17:41:47 -0700597 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700598 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700599
Felipe Leme57e3d312016-08-23 14:42:52 -0700600 mService.setUidPolicy(UID_A, POLICY_NONE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700601
602 assertWhitelistUids();
Felipe Leme57e3d312016-08-23 14:42:52 -0700603 assertUidPolicy(UID_A, POLICY_NONE);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700604 mPolicyListener.waitAndVerify().onUidPoliciesChanged(APP_ID_A, POLICY_NONE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700605 if (expectIntent) {
606 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
607 } else {
608 futureIntent.assertNotReceived();
609 }
610 }
611
612 /**
Felipe Leme57e3d312016-08-23 14:42:52 -0700613 * Adds blacklist when restrict background is on - app should not receive an intent.
Felipe Leme3d3308d2016-08-23 17:41:47 -0700614 */
615 @Test
616 @NetPolicyXml("restrict-background-on.xml")
617 public void testAddRestrictBackgroundBlacklist_restrictBackgroundOn() throws Exception {
618 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700619 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme57e3d312016-08-23 14:42:52 -0700620 addRestrictBackgroundBlacklist(false);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700621 }
622
623 /**
624 * Adds blacklist when restrict background is off - app should receive an intent.
625 */
626 @Test
627 public void testAddRestrictBackgroundBlacklist_restrictBackgroundOff() throws Exception {
628 assertRestrictBackgroundOff(); // Sanity check.
629 addRestrictBackgroundBlacklist(true);
630 }
631
632 private void addRestrictBackgroundBlacklist(boolean expectIntent) throws Exception {
633 assertUidPolicy(UID_A, POLICY_NONE); // Sanity check.
634 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700635 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700636
637 mService.setUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
638
639 assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700640 mPolicyListener.waitAndVerify()
641 .onUidPoliciesChanged(APP_ID_A, POLICY_REJECT_METERED_BACKGROUND);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700642 if (expectIntent) {
643 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
644 } else {
645 futureIntent.assertNotReceived();
646 }
647 }
648
649 /**
Felipe Leme57e3d312016-08-23 14:42:52 -0700650 * Removes blacklist when restrict background is on - app should not receive an intent.
Felipe Leme3d3308d2016-08-23 17:41:47 -0700651 */
652 @Test
653 @NetPolicyXml("uidA-blacklisted-restrict-background-on.xml")
654 public void testRemoveRestrictBackgroundBlacklist_restrictBackgroundOn() throws Exception {
655 assertRestrictBackgroundOn(); // Sanity check.
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700656 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme57e3d312016-08-23 14:42:52 -0700657 removeRestrictBackgroundBlacklist(false);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700658 }
659
660 /**
661 * Removes blacklist when restrict background is off - app should receive an intent.
662 */
663 @Test
664 @NetPolicyXml("uidA-blacklisted-restrict-background-off.xml")
665 public void testRemoveRestrictBackgroundBlacklist_restrictBackgroundOff() throws Exception {
666 assertRestrictBackgroundOff(); // Sanity check.
667 removeRestrictBackgroundBlacklist(true);
668 }
669
670 private void removeRestrictBackgroundBlacklist(boolean expectIntent) throws Exception {
671 assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND); // Sanity check.
672 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700673 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
Felipe Leme3d3308d2016-08-23 17:41:47 -0700674
675 mService.setUidPolicy(UID_A, POLICY_NONE);
676
677 assertUidPolicy(UID_A, POLICY_NONE);
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700678 mPolicyListener.waitAndVerify()
679 .onUidPoliciesChanged(APP_ID_A, POLICY_NONE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700680 if (expectIntent) {
681 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
682 } else {
683 futureIntent.assertNotReceived();
684 }
685 }
686
Felipe Leme51a63642016-08-30 12:15:09 -0700687 @Test
Felipe Lemec08ecdf2016-08-30 12:57:35 -0700688 @NetPolicyXml("uidA-blacklisted-restrict-background-on.xml")
Felipe Leme3d3308d2016-08-23 17:41:47 -0700689 public void testBlacklistedAppIsNotNotifiedWhenRestrictBackgroundIsOn() throws Exception {
690 // Sanity checks.
691 assertRestrictBackgroundOn();
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700692 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700693 assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
694
695 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
696 setRestrictBackground(true);
697 futureIntent.assertNotReceived();
698 }
699
Felipe Leme51a63642016-08-30 12:15:09 -0700700 @Test
Felipe Lemec08ecdf2016-08-30 12:57:35 -0700701 @NetPolicyXml("uidA-whitelisted-restrict-background-on.xml")
Felipe Leme3d3308d2016-08-23 17:41:47 -0700702 public void testWhitelistedAppIsNotNotifiedWhenRestrictBackgroundIsOn() throws Exception {
703 // Sanity checks.
Felipe Lemec08ecdf2016-08-30 12:57:35 -0700704 assertRestrictBackgroundOn();
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700705 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700706 assertWhitelistUids(UID_A);
707
708 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
709 setRestrictBackground(true);
710 futureIntent.assertNotReceived();
711 }
712
Andreas Gampe84d156b2016-09-03 10:50:38 -0700713 @Test
Felipe Leme57e3d312016-08-23 14:42:52 -0700714 @NetPolicyXml("uidA-whitelisted-restrict-background-on.xml")
715 public void testWhitelistedAppIsNotifiedWhenBlacklisted() throws Exception {
716 // Sanity checks.
717 assertRestrictBackgroundOn();
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700718 assertRestrictBackgroundChangedReceived(mFutureIntent, null);
Felipe Leme57e3d312016-08-23 14:42:52 -0700719 assertWhitelistUids(UID_A);
720
721 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
722 mService.setUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
723 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
724 }
725
Felipe Leme3d3308d2016-08-23 17:41:47 -0700726 @Test
Felipe Lemee88729d2016-08-17 16:43:01 -0700727 @NetPolicyXml("restrict-background-lists-whitelist-format.xml")
728 public void testRestrictBackgroundLists_whitelistFormat() throws Exception {
Felipe Leme46b451f2016-08-19 08:46:17 -0700729 restrictBackgroundListsTest();
730 }
731
732 @Test
733 @NetPolicyXml("restrict-background-lists-uid-policy-format.xml")
734 public void testRestrictBackgroundLists_uidPolicyFormat() throws Exception {
735 restrictBackgroundListsTest();
736 }
737
738 private void restrictBackgroundListsTest() throws Exception {
Felipe Leme8546a442016-08-23 09:38:20 -0700739 // UIds that are whitelisted.
Felipe Leme46b451f2016-08-19 08:46:17 -0700740 assertWhitelistUids(UID_A, UID_B, UID_C);
741 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
742 assertUidPolicy(UID_B, POLICY_ALLOW_METERED_BACKGROUND);
743 assertUidPolicy(UID_C, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Lemee88729d2016-08-17 16:43:01 -0700744
Felipe Leme8546a442016-08-23 09:38:20 -0700745 // UIDs that are blacklisted.
Felipe Lemee88729d2016-08-17 16:43:01 -0700746 assertUidPolicy(UID_D, POLICY_NONE);
747 assertUidPolicy(UID_E, POLICY_REJECT_METERED_BACKGROUND);
Felipe Leme8546a442016-08-23 09:38:20 -0700748
749 // UIDS that have legacy policies.
Felipe Leme46b451f2016-08-19 08:46:17 -0700750 assertUidPolicy(UID_F, 2); // POLICY_ALLOW_BACKGROUND_BATTERY_SAVE
751
752 // Remove whitelist.
Felipe Leme57e3d312016-08-23 14:42:52 -0700753 mService.setUidPolicy(UID_A, POLICY_NONE);
Felipe Leme46b451f2016-08-19 08:46:17 -0700754 assertUidPolicy(UID_A, POLICY_NONE);
755 assertWhitelistUids(UID_B, UID_C);
756
757 // Add whitelist when blacklisted.
Felipe Leme57e3d312016-08-23 14:42:52 -0700758 mService.setUidPolicy(UID_E, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme46b451f2016-08-19 08:46:17 -0700759 assertUidPolicy(UID_E, POLICY_ALLOW_METERED_BACKGROUND);
760 assertWhitelistUids(UID_B, UID_C, UID_E);
761
762 // Add blacklist when whitelisted.
763 mService.setUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND);
764 assertUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND);
765 assertWhitelistUids(UID_C, UID_E);
766 }
767
768 /**
769 * Tests scenario where an UID had {@code restrict-background} and {@code uid-policy} tags.
770 */
771 @Test
772 @NetPolicyXml("restrict-background-lists-mixed-format.xml")
773 public void testRestrictBackgroundLists_mixedFormat() throws Exception {
774 assertWhitelistUids(UID_A, UID_C, UID_D);
775 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Leme57e3d312016-08-23 14:42:52 -0700776 assertUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND); // Blacklist prevails.
Felipe Leme46b451f2016-08-19 08:46:17 -0700777 assertUidPolicy(UID_C, (POLICY_ALLOW_METERED_BACKGROUND | 2));
778 assertUidPolicy(UID_D, POLICY_ALLOW_METERED_BACKGROUND);
Felipe Lemee88729d2016-08-17 16:43:01 -0700779 }
780
Felipe Leme6f51a0a2016-08-24 15:11:51 -0700781 @Test
782 @NetPolicyXml("uids-with-mixed-policies.xml")
783 public void testGetUidsWithPolicy() throws Exception {
Felipe Leme03f90292016-09-08 18:10:32 -0700784 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_NONE));
Felipe Leme6f51a0a2016-08-24 15:11:51 -0700785 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND),
786 UID_B, UID_D);
787 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_ALLOW_METERED_BACKGROUND),
788 UID_E, UID_F);
789 // Legacy (POLICY_ALLOW_BACKGROUND_BATTERY_SAVE)
790 assertContainsInAnyOrder(mService.getUidsWithPolicy(2),
791 UID_C, UID_D, UID_F);
792 }
793
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700794 // NOTE: testPolicyChangeTriggersListener() is too superficial, they
Felipe Lemeef134662016-08-10 14:46:39 -0700795 // don't check for side-effects (like calls to NetworkManagementService) neither cover all
796 // different modes (Data Saver, Battery Saver, Doze, App idle, etc...).
797 // These scenarios are extensively tested on CTS' HostsideRestrictBackgroundNetworkTests.
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700798 @Test
Felipe Lemeef134662016-08-10 14:46:39 -0700799 public void testUidForeground() throws Exception {
800 // push all uids into background
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700801 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE, 0);
802 callOnUidStateChanged(UID_B, ActivityManager.PROCESS_STATE_SERVICE, 0);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700803 assertFalse(mService.isUidForeground(UID_A));
804 assertFalse(mService.isUidForeground(UID_B));
805
Felipe Lemeef134662016-08-10 14:46:39 -0700806 // push one of the uids into foreground
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700807 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_TOP, 0);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700808 assertTrue(mService.isUidForeground(UID_A));
809 assertFalse(mService.isUidForeground(UID_B));
810
811 // and swap another uid into foreground
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700812 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE, 0);
813 callOnUidStateChanged(UID_B, ActivityManager.PROCESS_STATE_TOP, 0);
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700814 assertFalse(mService.isUidForeground(UID_A));
815 assertTrue(mService.isUidForeground(UID_B));
Jeff Sharkey9599cc52011-05-22 14:59:31 -0700816 }
817
Jeff Sharkey53313d72017-07-13 16:47:32 -0600818 private static long computeLastCycleBoundary(long currentTime, NetworkPolicy policy) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600819 RecurrenceRule.sClock = Clock.fixed(Instant.ofEpochMilli(currentTime),
820 ZoneId.systemDefault());
821 final Iterator<Pair<ZonedDateTime, ZonedDateTime>> it = policy.cycleIterator();
Jeff Sharkey53313d72017-07-13 16:47:32 -0600822 while (it.hasNext()) {
823 final Pair<ZonedDateTime, ZonedDateTime> cycle = it.next();
824 if (cycle.first.toInstant().toEpochMilli() < currentTime) {
825 return cycle.first.toInstant().toEpochMilli();
826 }
827 }
828 throw new IllegalStateException(
829 "Failed to find current cycle for " + policy + " at " + currentTime);
830 }
831
832 private static long computeNextCycleBoundary(long currentTime, NetworkPolicy policy) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600833 RecurrenceRule.sClock = Clock.fixed(Instant.ofEpochMilli(currentTime),
834 ZoneId.systemDefault());
835 return policy.cycleIterator().next().second.toInstant().toEpochMilli();
Jeff Sharkey53313d72017-07-13 16:47:32 -0600836 }
837
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700838 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700839 public void testLastCycleBoundaryThisMonth() throws Exception {
840 // assume cycle day of "5th", which should be in same month
841 final long currentTime = parseTime("2007-11-14T00:00:00.000Z");
842 final long expectedCycle = parseTime("2007-11-05T00:00:00.000Z");
843
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700844 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800845 sTemplateWifi, 5, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700846 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700847 assertTimeEquals(expectedCycle, actualCycle);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700848 }
849
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700850 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700851 public void testLastCycleBoundaryLastMonth() throws Exception {
852 // assume cycle day of "20th", which should be in last month
853 final long currentTime = parseTime("2007-11-14T00:00:00.000Z");
854 final long expectedCycle = parseTime("2007-10-20T00:00:00.000Z");
855
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700856 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800857 sTemplateWifi, 20, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700858 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700859 assertTimeEquals(expectedCycle, actualCycle);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700860 }
861
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700862 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700863 public void testLastCycleBoundaryThisMonthFebruary() throws Exception {
864 // assume cycle day of "30th" in february; should go to january
865 final long currentTime = parseTime("2007-02-14T00:00:00.000Z");
866 final long expectedCycle = parseTime("2007-01-30T00:00:00.000Z");
867
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700868 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800869 sTemplateWifi, 30, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700870 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700871 assertTimeEquals(expectedCycle, actualCycle);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700872 }
873
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700874 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700875 public void testLastCycleBoundaryLastMonthFebruary() throws Exception {
876 // assume cycle day of "30th" in february, which should clamp
877 final long currentTime = parseTime("2007-03-14T00:00:00.000Z");
Jeff Sharkey53313d72017-07-13 16:47:32 -0600878 final long expectedCycle = parseTime("2007-02-28T23:59:59.999Z");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700879
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700880 final NetworkPolicy policy = new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800881 sTemplateWifi, 30, TIMEZONE_UTC, 1024L, 1024L, false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700882 final long actualCycle = computeLastCycleBoundary(currentTime, policy);
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -0700883 assertTimeEquals(expectedCycle, actualCycle);
884 }
885
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700886 @Test
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800887 public void testCycleBoundaryLeapYear() throws Exception {
888 final NetworkPolicy policy = new NetworkPolicy(
889 sTemplateWifi, 29, TIMEZONE_UTC, 1024L, 1024L, false);
890
891 assertTimeEquals(parseTime("2012-01-29T00:00:00.000Z"),
892 computeNextCycleBoundary(parseTime("2012-01-14T00:00:00.000Z"), policy));
893 assertTimeEquals(parseTime("2012-02-29T00:00:00.000Z"),
894 computeNextCycleBoundary(parseTime("2012-02-14T00:00:00.000Z"), policy));
895 assertTimeEquals(parseTime("2012-02-29T00:00:00.000Z"),
896 computeLastCycleBoundary(parseTime("2012-03-14T00:00:00.000Z"), policy));
897 assertTimeEquals(parseTime("2012-03-29T00:00:00.000Z"),
898 computeNextCycleBoundary(parseTime("2012-03-14T00:00:00.000Z"), policy));
899
900 assertTimeEquals(parseTime("2007-01-29T00:00:00.000Z"),
901 computeNextCycleBoundary(parseTime("2007-01-14T00:00:00.000Z"), policy));
Jeff Sharkey53313d72017-07-13 16:47:32 -0600902 assertTimeEquals(parseTime("2007-02-28T23:59:59.999Z"),
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800903 computeNextCycleBoundary(parseTime("2007-02-14T00:00:00.000Z"), policy));
Jeff Sharkey53313d72017-07-13 16:47:32 -0600904 assertTimeEquals(parseTime("2007-02-28T23:59:59.999Z"),
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800905 computeLastCycleBoundary(parseTime("2007-03-14T00:00:00.000Z"), policy));
906 assertTimeEquals(parseTime("2007-03-29T00:00:00.000Z"),
907 computeNextCycleBoundary(parseTime("2007-03-14T00:00:00.000Z"), policy));
908 }
909
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700910 @Test
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800911 public void testNextCycleTimezoneAfterUtc() throws Exception {
912 // US/Central is UTC-6
913 final NetworkPolicy policy = new NetworkPolicy(
914 sTemplateWifi, 10, "US/Central", 1024L, 1024L, false);
915 assertTimeEquals(parseTime("2012-01-10T06:00:00.000Z"),
916 computeNextCycleBoundary(parseTime("2012-01-05T00:00:00.000Z"), policy));
917 }
918
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700919 @Test
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800920 public void testNextCycleTimezoneBeforeUtc() throws Exception {
921 // Israel is UTC+2
922 final NetworkPolicy policy = new NetworkPolicy(
923 sTemplateWifi, 10, "Israel", 1024L, 1024L, false);
924 assertTimeEquals(parseTime("2012-01-09T22:00:00.000Z"),
925 computeNextCycleBoundary(parseTime("2012-01-05T00:00:00.000Z"), policy));
926 }
927
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700928 @Test
Jeff Sharkey15399052013-01-15 14:15:53 -0800929 public void testCycleTodayJanuary() throws Exception {
930 final NetworkPolicy policy = new NetworkPolicy(
931 sTemplateWifi, 14, "US/Pacific", 1024L, 1024L, false);
932
933 assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
934 computeNextCycleBoundary(parseTime("2013-01-13T23:59:59.000-08:00"), policy));
935 assertTimeEquals(parseTime("2013-02-14T00:00:00.000-08:00"),
936 computeNextCycleBoundary(parseTime("2013-01-14T00:00:01.000-08:00"), policy));
937 assertTimeEquals(parseTime("2013-02-14T00:00:00.000-08:00"),
938 computeNextCycleBoundary(parseTime("2013-01-14T15:11:00.000-08:00"), policy));
939
940 assertTimeEquals(parseTime("2012-12-14T00:00:00.000-08:00"),
941 computeLastCycleBoundary(parseTime("2013-01-13T23:59:59.000-08:00"), policy));
942 assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
943 computeLastCycleBoundary(parseTime("2013-01-14T00:00:01.000-08:00"), policy));
944 assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
945 computeLastCycleBoundary(parseTime("2013-01-14T15:11:00.000-08:00"), policy));
946 }
947
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700948 @Test
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700949 public void testNetworkPolicyAppliedCycleLastMonth() throws Exception {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700950 NetworkState[] state = null;
951 NetworkStats stats = null;
952
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700953 final int CYCLE_DAY = 15;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600954 final long NOW = parseTime("2007-03-10T00:00Z");
955 final long CYCLE_START = parseTime("2007-02-15T00:00Z");
956 final long CYCLE_END = parseTime("2007-03-15T00:00Z");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700957
Jeff Sharkey53313d72017-07-13 16:47:32 -0600958 setCurrentTimeMillis(NOW);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700959
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700960 // first, pretend that wifi network comes online. no policy active,
961 // which means we shouldn't push limit to interface.
962 state = new NetworkState[] { buildWifi() };
Felipe Lemeef134662016-08-10 14:46:39 -0700963 when(mConnManager.getAllNetworkState()).thenReturn(state);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700964
Felipe Lemeef134662016-08-10 14:46:39 -0700965 mPolicyListener.expect().onMeteredIfacesChanged(any());
Erik Klinef851d6d2015-04-20 16:03:48 +0900966 mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION));
Felipe Lemeef134662016-08-10 14:46:39 -0700967 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(any());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700968
969 // now change cycle to be on 15th, and test in early march, to verify we
970 // pick cycle day in previous month.
Felipe Lemeef134662016-08-10 14:46:39 -0700971 when(mConnManager.getAllNetworkState()).thenReturn(state);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700972
973 // pretend that 512 bytes total have happened
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700974 stats = new NetworkStats(getElapsedRealtime(), 1)
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700975 .addIfaceValues(TEST_IFACE, 256L, 2L, 256L, 2L);
Jeff Sharkey53313d72017-07-13 16:47:32 -0600976 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, CYCLE_START, CYCLE_END))
Felipe Lemeef134662016-08-10 14:46:39 -0700977 .thenReturn(stats.getTotalBytes());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700978
Felipe Lemeef134662016-08-10 14:46:39 -0700979 mPolicyListener.expect().onMeteredIfacesChanged(any());
Jeff Sharkey163e6442011-10-31 16:37:52 -0700980 setNetworkPolicies(new NetworkPolicy(
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800981 sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, 1 * MB_IN_BYTES, 2 * MB_IN_BYTES, false));
Felipe Lemeef134662016-08-10 14:46:39 -0700982 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
983
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700984 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
985 (2 * MB_IN_BYTES) - 512);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700986 }
987
Felipe Leme9f27e7a2016-08-12 15:19:40 -0700988 @Test
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700989 public void testNotificationWarningLimitSnooze() throws Exception {
Jeff Sharkey2e471452018-01-19 18:02:47 +0900990 // Create a place to store fake usage
991 final NetworkStatsHistory history = new NetworkStatsHistory(TimeUnit.HOURS.toMillis(1));
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700992 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey2e471452018-01-19 18:02:47 +0900993 when(mStatsService.getNetworkTotalBytes(any(), anyLong(), anyLong()))
994 .thenAnswer(new Answer<Long>() {
995 @Override
996 public Long answer(InvocationOnMock invocation) throws Throwable {
997 final NetworkStatsHistory.Entry entry = history.getValues(
998 invocation.getArgument(1), invocation.getArgument(2), null);
999 return entry.rxBytes + entry.txBytes;
1000 }
1001 });
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001002 when(mStatsService.getNetworkUidBytes(any(), anyLong(), anyLong()))
1003 .thenAnswer(new Answer<NetworkStats>() {
1004 @Override
1005 public NetworkStats answer(InvocationOnMock invocation) throws Throwable {
1006 return stats;
1007 }
1008 });
Jeff Sharkey2e471452018-01-19 18:02:47 +09001009
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001010 // Get active mobile network in place
1011 expectMobileDefaults();
1012 mService.updateNetworks();
1013
1014 // Define simple data plan
Jeff Sharkey2e471452018-01-19 18:02:47 +09001015 final SubscriptionPlan plan = SubscriptionPlan.Builder
1016 .createRecurringMonthly(ZonedDateTime.parse("2015-11-01T00:00:00.00Z"))
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001017 .setDataLimit(DataUnit.MEGABYTES.toBytes(1800), LIMIT_BEHAVIOR_DISABLED)
Jeff Sharkey2e471452018-01-19 18:02:47 +09001018 .build();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001019 mService.setSubscriptionPlans(TEST_SUB_ID, new SubscriptionPlan[] { plan },
Jeff Sharkey2e471452018-01-19 18:02:47 +09001020 mServiceContext.getOpPackageName());
1021
Jeff Sharkey2e471452018-01-19 18:02:47 +09001022 // We're 20% through the month (6 days)
1023 final long start = parseTime("2015-11-01T00:00Z");
1024 final long end = parseTime("2015-11-07T00:00Z");
1025 setCurrentTimeMillis(end);
1026
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001027 // Normal usage means no notification
1028 {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001029 history.clear();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001030 history.recordData(start, end,
1031 new NetworkStats.Entry(DataUnit.MEGABYTES.toBytes(360), 0L, 0L, 0L, 0));
1032
1033 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1034 expectMobileDefaults();
1035
1036 mService.updateNetworks();
1037
1038 verify(mTelephonyManager, atLeastOnce()).setPolicyDataEnabled(true, TEST_SUB_ID);
1039 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
1040 DataUnit.MEGABYTES.toBytes(1800 - 360));
1041 verify(mNotifManager, never()).notifyAsUser(any(), anyInt(), any(), any());
1042 }
1043
1044 // Push over warning
1045 {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001046 history.clear();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001047 history.recordData(start, end,
1048 new NetworkStats.Entry(DataUnit.MEGABYTES.toBytes(1799), 0L, 0L, 0L, 0));
1049
1050 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1051 expectMobileDefaults();
1052
1053 mService.updateNetworks();
1054
1055 verify(mTelephonyManager, atLeastOnce()).setPolicyDataEnabled(true, TEST_SUB_ID);
1056 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
1057 DataUnit.MEGABYTES.toBytes(1800 - 1799));
1058 verify(mNotifManager, atLeastOnce()).notifyAsUser(any(), eq(TYPE_WARNING),
1059 isA(Notification.class), eq(UserHandle.ALL));
1060 }
1061
1062 // Push over limit
1063 {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001064 history.clear();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001065 history.recordData(start, end,
1066 new NetworkStats.Entry(DataUnit.MEGABYTES.toBytes(1810), 0L, 0L, 0L, 0));
1067
1068 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1069 expectMobileDefaults();
1070
1071 mService.updateNetworks();
1072
1073 verify(mTelephonyManager, atLeastOnce()).setPolicyDataEnabled(false, TEST_SUB_ID);
1074 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE, 1);
1075 verify(mNotifManager, atLeastOnce()).notifyAsUser(any(), eq(TYPE_LIMIT),
1076 isA(Notification.class), eq(UserHandle.ALL));
1077 }
1078
1079 // Snooze limit
1080 {
1081 reset(mTelephonyManager, mNetworkManager, mNotifManager);
1082 expectMobileDefaults();
1083
1084 mService.snoozeLimit(NetworkTemplate.buildTemplateMobileAll(TEST_IMSI));
1085 mService.updateNetworks();
1086
1087 verify(mTelephonyManager, atLeastOnce()).setPolicyDataEnabled(true, TEST_SUB_ID);
1088 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
1089 Long.MAX_VALUE);
1090 verify(mNotifManager, atLeastOnce()).notifyAsUser(any(), eq(TYPE_LIMIT_SNOOZED),
1091 isA(Notification.class), eq(UserHandle.ALL));
1092 }
1093 }
1094
1095 @Test
1096 public void testNotificationRapid() throws Exception {
1097 // Create a place to store fake usage
1098 final NetworkStatsHistory history = new NetworkStatsHistory(TimeUnit.HOURS.toMillis(1));
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001099 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001100 when(mStatsService.getNetworkTotalBytes(any(), anyLong(), anyLong()))
1101 .thenAnswer(new Answer<Long>() {
1102 @Override
1103 public Long answer(InvocationOnMock invocation) throws Throwable {
1104 final NetworkStatsHistory.Entry entry = history.getValues(
1105 invocation.getArgument(1), invocation.getArgument(2), null);
1106 return entry.rxBytes + entry.txBytes;
1107 }
1108 });
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001109 when(mStatsService.getNetworkUidBytes(any(), anyLong(), anyLong()))
1110 .thenAnswer(new Answer<NetworkStats>() {
1111 @Override
1112 public NetworkStats answer(InvocationOnMock invocation) throws Throwable {
1113 return stats;
1114 }
1115 });
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001116
1117 // Get active mobile network in place
1118 expectMobileDefaults();
1119 mService.updateNetworks();
1120
1121 // Define simple data plan which gives us effectively 60MB/day
1122 final SubscriptionPlan plan = SubscriptionPlan.Builder
1123 .createRecurringMonthly(ZonedDateTime.parse("2015-11-01T00:00:00.00Z"))
1124 .setDataLimit(DataUnit.MEGABYTES.toBytes(1800), LIMIT_BEHAVIOR_DISABLED)
1125 .build();
1126 mService.setSubscriptionPlans(TEST_SUB_ID, new SubscriptionPlan[] { plan },
1127 mServiceContext.getOpPackageName());
1128
1129 // We're 20% through the month (6 days)
1130 final long start = parseTime("2015-11-01T00:00Z");
1131 final long end = parseTime("2015-11-07T00:00Z");
1132 setCurrentTimeMillis(end);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001133
1134 // Using 20% data in 20% time is normal
Jeff Sharkey2e471452018-01-19 18:02:47 +09001135 {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001136 history.clear();
Jeff Sharkey2e471452018-01-19 18:02:47 +09001137 history.recordData(start, end,
1138 new NetworkStats.Entry(DataUnit.MEGABYTES.toBytes(360), 0L, 0L, 0L, 0));
1139
1140 reset(mNotifManager);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001141 mService.updateNetworks();
1142 verify(mNotifManager, never()).notifyAsUser(any(), anyInt(), any(), any());
Jeff Sharkey2e471452018-01-19 18:02:47 +09001143 }
1144
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001145 // Using 80% data in 20% time is alarming; but spread equally among
1146 // three UIDs means we get generic alert
Jeff Sharkey2e471452018-01-19 18:02:47 +09001147 {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001148 history.clear();
Jeff Sharkey2e471452018-01-19 18:02:47 +09001149 history.recordData(start, end,
1150 new NetworkStats.Entry(DataUnit.MEGABYTES.toBytes(1440), 0L, 0L, 0L, 0));
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001151 stats.clear();
1152 stats.addValues(IFACE_ALL, UID_A, SET_ALL, TAG_ALL,
1153 DataUnit.MEGABYTES.toBytes(480), 0, 0, 0, 0);
1154 stats.addValues(IFACE_ALL, UID_B, SET_ALL, TAG_ALL,
1155 DataUnit.MEGABYTES.toBytes(480), 0, 0, 0, 0);
1156 stats.addValues(IFACE_ALL, UID_C, SET_ALL, TAG_ALL,
1157 DataUnit.MEGABYTES.toBytes(480), 0, 0, 0, 0);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001158
1159 reset(mNotifManager);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001160 mService.updateNetworks();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001161
1162 final ArgumentCaptor<Notification> notif = ArgumentCaptor.forClass(Notification.class);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001163 verify(mNotifManager, atLeastOnce()).notifyAsUser(any(), eq(TYPE_RAPID),
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001164 notif.capture(), eq(UserHandle.ALL));
1165
1166 final String text = notif.getValue().extras.getCharSequence(Notification.EXTRA_TEXT)
1167 .toString();
1168 assertFalse(text.contains(PKG_NAME_A));
1169 assertFalse(text.contains(PKG_NAME_B));
1170 assertFalse(text.contains(PKG_NAME_C));
1171 }
1172
1173 // Using 80% data in 20% time is alarming; but mostly done by one UID
1174 // means we get specific alert
1175 {
1176 history.clear();
1177 history.recordData(start, end,
1178 new NetworkStats.Entry(DataUnit.MEGABYTES.toBytes(1440), 0L, 0L, 0L, 0));
1179 stats.clear();
1180 stats.addValues(IFACE_ALL, UID_A, SET_ALL, TAG_ALL,
1181 DataUnit.MEGABYTES.toBytes(960), 0, 0, 0, 0);
1182 stats.addValues(IFACE_ALL, UID_B, SET_ALL, TAG_ALL,
1183 DataUnit.MEGABYTES.toBytes(480), 0, 0, 0, 0);
1184
1185 reset(mNotifManager);
1186 mService.updateNetworks();
1187
1188 final ArgumentCaptor<Notification> notif = ArgumentCaptor.forClass(Notification.class);
1189 verify(mNotifManager, atLeastOnce()).notifyAsUser(any(), eq(TYPE_RAPID),
1190 notif.capture(), eq(UserHandle.ALL));
1191
1192 final String text = notif.getValue().extras.getCharSequence(Notification.EXTRA_TEXT)
1193 .toString();
1194 assertTrue(text.contains(PKG_NAME_A));
1195 assertFalse(text.contains(PKG_NAME_B));
1196 assertFalse(text.contains(PKG_NAME_C));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001197 }
1198 }
1199
1200 @Test
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001201 public void testMeteredNetworkWithoutLimit() throws Exception {
1202 NetworkState[] state = null;
1203 NetworkStats stats = null;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001204
1205 final long TIME_FEB_15 = 1171497600000L;
1206 final long TIME_MAR_10 = 1173484800000L;
1207 final int CYCLE_DAY = 15;
1208
1209 setCurrentTimeMillis(TIME_MAR_10);
1210
1211 // bring up wifi network with metered policy
1212 state = new NetworkState[] { buildWifi() };
1213 stats = new NetworkStats(getElapsedRealtime(), 1)
1214 .addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L);
1215
1216 {
Felipe Lemeef134662016-08-10 14:46:39 -07001217 when(mConnManager.getAllNetworkState()).thenReturn(state);
1218 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15,
1219 currentTimeMillis())).thenReturn(stats.getTotalBytes());
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001220
Felipe Lemeef134662016-08-10 14:46:39 -07001221 mPolicyListener.expect().onMeteredIfacesChanged(any());
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001222 setNetworkPolicies(new NetworkPolicy(
1223 sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, WARNING_DISABLED, LIMIT_DISABLED,
1224 true));
Felipe Lemeef134662016-08-10 14:46:39 -07001225 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
1226
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001227 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
1228 Long.MAX_VALUE);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001229 }
1230 }
1231
Sudheer Shankae7361852017-03-07 11:51:46 -08001232 @Test
1233 public void testOnUidStateChanged_notifyAMS() throws Exception {
1234 final long procStateSeq = 222;
Sudheer Shankaed25ce62017-03-29 20:46:30 -07001235 callOnUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE, procStateSeq);
Sudheer Shankae7361852017-03-07 11:51:46 -08001236 verify(mActivityManagerInternal).notifyNetworkPolicyRulesUpdated(UID_A, procStateSeq);
Sudheer Shankae7361852017-03-07 11:51:46 -08001237 }
1238
Sudheer Shankaed25ce62017-03-29 20:46:30 -07001239 private void callOnUidStateChanged(int uid, int procState, long procStateSeq)
1240 throws Exception {
1241 mUidObserver.onUidStateChanged(uid, procState, procStateSeq);
1242 final CountDownLatch latch = new CountDownLatch(1);
1243 mService.mUidEventHandler.post(() -> {
1244 latch.countDown();
1245 });
1246 latch.await(2, TimeUnit.SECONDS);
1247 }
1248
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001249 private void assertCycleDayAsExpected(PersistableBundle config, int carrierCycleDay,
1250 boolean expectValid) {
1251 config.putInt(KEY_MONTHLY_DATA_CYCLE_DAY_INT, carrierCycleDay);
1252 int actualCycleDay = mService.getCycleDayFromCarrierConfig(config,
1253 INVALID_CARRIER_CONFIG_VALUE);
1254 if (expectValid) {
1255 assertEquals(carrierCycleDay, actualCycleDay);
1256 } else {
1257 // INVALID_CARRIER_CONFIG_VALUE is returned for invalid values
1258 assertEquals(INVALID_CARRIER_CONFIG_VALUE, actualCycleDay);
1259 }
1260 }
1261
1262 @Test
1263 public void testGetCycleDayFromCarrierConfig() {
1264 PersistableBundle config = CarrierConfigManager.getDefaultConfig();
1265 final Calendar cal = Calendar.getInstance();
1266 int actualCycleDay;
1267
1268 config.putInt(KEY_MONTHLY_DATA_CYCLE_DAY_INT, DATA_CYCLE_USE_PLATFORM_DEFAULT);
1269 actualCycleDay = mService.getCycleDayFromCarrierConfig(config, DEFAULT_CYCLE_DAY);
1270 assertEquals(DEFAULT_CYCLE_DAY, actualCycleDay);
1271
1272 // null config returns a default value
1273 actualCycleDay = mService.getCycleDayFromCarrierConfig(null, DEFAULT_CYCLE_DAY);
1274 assertEquals(DEFAULT_CYCLE_DAY, actualCycleDay);
1275
1276 // Sane, non-default values
1277 assertCycleDayAsExpected(config, 1, true);
1278 assertCycleDayAsExpected(config, cal.getMaximum(Calendar.DAY_OF_MONTH), true);
1279 assertCycleDayAsExpected(config, cal.getMinimum(Calendar.DAY_OF_MONTH), true);
1280
1281 // Invalid values
1282 assertCycleDayAsExpected(config, 0, false);
1283 assertCycleDayAsExpected(config, DATA_CYCLE_THRESHOLD_DISABLED, false);
1284 assertCycleDayAsExpected(config, cal.getMaximum(Calendar.DAY_OF_MONTH) + 1, false);
1285 assertCycleDayAsExpected(config, cal.getMinimum(Calendar.DAY_OF_MONTH) - 5, false);
1286 }
1287
1288 private void assertWarningBytesAsExpected(PersistableBundle config, long carrierWarningBytes,
1289 long expected) {
1290 config.putLong(KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, carrierWarningBytes);
1291 long actualWarning = mService.getWarningBytesFromCarrierConfig(config,
1292 INVALID_CARRIER_CONFIG_VALUE);
1293 assertEquals(expected, actualWarning);
1294 }
1295
1296 @Test
1297 public void testGetWarningBytesFromCarrierConfig() {
1298 PersistableBundle config = CarrierConfigManager.getDefaultConfig();
1299 long actualWarningBytes;
1300
1301 assertWarningBytesAsExpected(config, DATA_CYCLE_USE_PLATFORM_DEFAULT,
1302 mDefaultWarningBytes);
1303 assertWarningBytesAsExpected(config, DATA_CYCLE_THRESHOLD_DISABLED, WARNING_DISABLED);
1304 assertWarningBytesAsExpected(config, 0, 0);
1305 // not a valid value
1306 assertWarningBytesAsExpected(config, -1000, INVALID_CARRIER_CONFIG_VALUE);
1307
1308 // null config returns a default value
1309 actualWarningBytes = mService.getWarningBytesFromCarrierConfig(null, mDefaultWarningBytes);
1310 assertEquals(mDefaultWarningBytes, actualWarningBytes);
1311 }
1312
1313 private void assertLimitBytesAsExpected(PersistableBundle config, long carrierWarningBytes,
1314 long expected) {
1315 config.putLong(KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG, carrierWarningBytes);
1316 long actualWarning = mService.getLimitBytesFromCarrierConfig(config,
1317 INVALID_CARRIER_CONFIG_VALUE);
1318 assertEquals(expected, actualWarning);
1319 }
1320
1321 @Test
1322 public void testGetLimitBytesFromCarrierConfig() {
1323 PersistableBundle config = CarrierConfigManager.getDefaultConfig();
1324 long actualLimitBytes;
1325
1326 assertLimitBytesAsExpected(config, DATA_CYCLE_USE_PLATFORM_DEFAULT,
1327 mDefaultLimitBytes);
1328 assertLimitBytesAsExpected(config, DATA_CYCLE_THRESHOLD_DISABLED, LIMIT_DISABLED);
1329 assertLimitBytesAsExpected(config, 0, 0);
1330 // not a valid value
1331 assertLimitBytesAsExpected(config, -1000, INVALID_CARRIER_CONFIG_VALUE);
1332
1333 // null config returns a default value
1334 actualLimitBytes = mService.getWarningBytesFromCarrierConfig(null, mDefaultLimitBytes);
1335 assertEquals(mDefaultLimitBytes, actualLimitBytes);
1336 }
1337
1338 private PersistableBundle setupUpdateMobilePolicyCycleTests() throws RemoteException {
1339 when(mConnManager.getAllNetworkState()).thenReturn(new NetworkState[0]);
1340 when(mSubscriptionManager.getActiveSubscriptionIdList()).thenReturn(new int[]{FAKE_SUB_ID});
1341 when(mTelephonyManager.getSubscriberId(FAKE_SUB_ID)).thenReturn(FAKE_SUBSCRIBER_ID);
1342 PersistableBundle bundle = CarrierConfigManager.getDefaultConfig();
1343 when(mCarrierConfigManager.getConfigForSubId(FAKE_SUB_ID)).thenReturn(bundle);
1344 setNetworkPolicies(buildDefaultFakeMobilePolicy());
1345 return bundle;
1346 }
1347
1348 @Test
1349 public void testUpdateMobilePolicyCycleWithNullConfig() throws RemoteException {
1350 when(mConnManager.getAllNetworkState()).thenReturn(new NetworkState[0]);
1351 when(mSubscriptionManager.getActiveSubscriptionIdList()).thenReturn(new int[]{FAKE_SUB_ID});
1352 when(mTelephonyManager.getSubscriberId(FAKE_SUB_ID)).thenReturn(FAKE_SUBSCRIBER_ID);
1353 when(mCarrierConfigManager.getConfigForSubId(FAKE_SUB_ID)).thenReturn(null);
1354 setNetworkPolicies(buildDefaultFakeMobilePolicy());
1355 // smoke test to make sure no errors are raised
1356 mServiceContext.sendBroadcast(
1357 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1358 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1359 );
1360 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1361 true);
1362 }
1363
1364 @Test
1365 public void testUpdateMobilePolicyCycleWithInvalidConfig() throws RemoteException {
1366 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1367 // Test with an invalid CarrierConfig, there should be no changes or crashes.
1368 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, -100);
1369 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, -100);
1370 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG, -100);
1371 mServiceContext.sendBroadcast(
1372 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1373 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1374 );
1375
1376 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1377 true);
1378 }
1379
1380 @Test
1381 public void testUpdateMobilePolicyCycleWithDefaultConfig() throws RemoteException {
1382 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1383 // Test that we respect the platform values when told to
1384 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT,
1385 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1386 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1387 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1388 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1389 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1390 mServiceContext.sendBroadcast(
1391 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1392 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1393 );
1394
1395 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1396 true);
1397 }
1398
1399 @Test
1400 public void testUpdateMobilePolicyCycleWithUserOverrides() throws RemoteException {
1401 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1402
1403 // inferred = false implies that a user manually modified this policy.
1404 NetworkPolicy policy = buildDefaultFakeMobilePolicy();
1405 policy.inferred = false;
1406 setNetworkPolicies(policy);
1407
1408 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1409 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, 9999);
1410 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1411 DATA_CYCLE_THRESHOLD_DISABLED);
1412 mServiceContext.sendBroadcast(
1413 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1414 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1415 );
1416
1417 // The policy still shouldn't change, because we don't want to overwrite user settings.
1418 assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1419 false);
1420 }
1421
1422 @Test
1423 public void testUpdateMobilePolicyCycleUpdatesDataCycle() throws RemoteException {
1424 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1425
1426 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1427 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, 9999);
1428 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG, 9999);
1429 mServiceContext.sendBroadcast(
1430 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1431 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1432 );
1433
1434 assertNetworkPolicyEquals(31, 9999, 9999, true);
1435 }
1436
1437 @Test
1438 public void testUpdateMobilePolicyCycleDisableThresholds() throws RemoteException {
1439 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1440
1441 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1442 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1443 DATA_CYCLE_THRESHOLD_DISABLED);
1444 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1445 DATA_CYCLE_THRESHOLD_DISABLED);
1446 mServiceContext.sendBroadcast(
1447 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1448 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1449 );
1450
1451 assertNetworkPolicyEquals(31, WARNING_DISABLED, LIMIT_DISABLED, true);
1452 }
1453
1454 @Test
1455 public void testUpdateMobilePolicyCycleRevertsToDefault() throws RemoteException {
1456 PersistableBundle bundle = setupUpdateMobilePolicyCycleTests();
1457
1458 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1459 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1460 DATA_CYCLE_THRESHOLD_DISABLED);
1461 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1462 DATA_CYCLE_THRESHOLD_DISABLED);
1463 mServiceContext.sendBroadcast(
1464 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1465 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1466 );
1467 assertNetworkPolicyEquals(31, WARNING_DISABLED, LIMIT_DISABLED, true);
1468
1469 // If the user switches carriers to one that doesn't use a CarrierConfig, we should revert
1470 // to the default data limit and warning. The cycle date doesn't need to revert as it's
1471 // arbitrary anyways.
1472 bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT,
1473 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1474 bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1475 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1476 bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1477 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1478 mServiceContext.sendBroadcast(
1479 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1480 .putExtra(PhoneConstants.SUBSCRIPTION_KEY, FAKE_SUB_ID)
1481 );
1482
1483 assertNetworkPolicyEquals(31, mDefaultWarningBytes, mDefaultLimitBytes,
1484 true);
1485 }
1486
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001487 private ApplicationInfo buildApplicationInfo(String label) {
1488 final ApplicationInfo ai = new ApplicationInfo();
1489 ai.nonLocalizedLabel = label;
1490 return ai;
1491 }
1492
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001493 private NetworkInfo buildNetworkInfo() {
1494 final NetworkInfo ni = new NetworkInfo(ConnectivityManager.TYPE_MOBILE,
1495 TelephonyManager.NETWORK_TYPE_LTE, null, null);
1496 ni.setDetailedState(NetworkInfo.DetailedState.CONNECTED, null, null);
1497 return ni;
1498 }
1499
1500 private LinkProperties buildLinkProperties(String iface) {
1501 final LinkProperties lp = new LinkProperties();
1502 lp.setInterfaceName(iface);
1503 return lp;
1504 }
1505
1506 private NetworkCapabilities buildNetworkCapabilities(int subId) {
1507 final NetworkCapabilities nc = new NetworkCapabilities();
1508 nc.addTransportType(TRANSPORT_CELLULAR);
1509 nc.setNetworkSpecifier(new StringNetworkSpecifier(String.valueOf(subId)));
1510 return nc;
1511 }
1512
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001513 private NetworkPolicy buildDefaultFakeMobilePolicy() {
1514 NetworkPolicy p = mService.buildDefaultMobilePolicy(FAKE_SUB_ID, FAKE_SUBSCRIBER_ID);
1515 // set a deterministic cycle date
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001516 p.cycleRule = new RecurrenceRule(
1517 p.cycleRule.start.withDayOfMonth(DEFAULT_CYCLE_DAY),
1518 p.cycleRule.end, Period.ofMonths(1));
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001519 return p;
1520 }
1521
1522 private static NetworkPolicy buildFakeMobilePolicy(int cycleDay, long warningBytes,
1523 long limitBytes, boolean inferred){
1524 final NetworkTemplate template = buildTemplateMobileAll(FAKE_SUBSCRIBER_ID);
Sudheer Shankaed25ce62017-03-29 20:46:30 -07001525 return new NetworkPolicy(template, cycleDay, new Time().timezone, warningBytes,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001526 limitBytes, SNOOZE_NEVER, SNOOZE_NEVER, true, inferred);
1527 }
1528
1529 private void assertNetworkPolicyEquals(int expectedCycleDay, long expectedWarningBytes,
1530 long expectedLimitBytes, boolean expectedInferred) {
1531 NetworkPolicy[] policies = mService.getNetworkPolicies(
1532 mServiceContext.getOpPackageName());
1533 assertEquals("Unexpected number of network policies", 1, policies.length);
1534 NetworkPolicy actualPolicy = policies[0];
1535 NetworkPolicy expectedPolicy = buildFakeMobilePolicy(expectedCycleDay, expectedWarningBytes,
1536 expectedLimitBytes, expectedInferred);
1537 assertEquals(expectedPolicy, actualPolicy);
1538 }
1539
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001540 private static long parseTime(String time) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06001541 return ZonedDateTime.parse(time).toInstant().toEpochMilli();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001542 }
1543
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07001544 private void setNetworkPolicies(NetworkPolicy... policies) {
1545 mService.setNetworkPolicies(policies);
1546 }
1547
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001548 private static NetworkState buildWifi() {
1549 final NetworkInfo info = new NetworkInfo(TYPE_WIFI, 0, null, null);
1550 info.setDetailedState(DetailedState.CONNECTED, null, null);
1551 final LinkProperties prop = new LinkProperties();
1552 prop.setInterfaceName(TEST_IFACE);
Stephen Chena1c92b72017-02-06 13:18:11 -08001553 final NetworkCapabilities networkCapabilities = new NetworkCapabilities();
1554 return new NetworkState(info, prop, networkCapabilities, null, null, TEST_SSID);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001555 }
1556
Felipe Leme3d3308d2016-08-23 17:41:47 -07001557 private void expectHasInternetPermission(int uid, boolean hasIt) throws Exception {
1558 when(mIpm.checkUidPermission(Manifest.permission.INTERNET, uid)).thenReturn(
1559 hasIt ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED);
1560 }
1561
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001562 private void expectMobileDefaults() throws Exception {
1563 when(mSubscriptionManager.getActiveSubscriptionIdList()).thenReturn(
1564 new int[] { TEST_SUB_ID });
1565 when(mTelephonyManager.getSubscriberId(TEST_SUB_ID)).thenReturn(TEST_IMSI);
1566 when(mConnManager.getAllNetworkState()).thenReturn(new NetworkState[] {
1567 new NetworkState(buildNetworkInfo(),
1568 buildLinkProperties(TEST_IFACE),
1569 buildNetworkCapabilities(TEST_SUB_ID),
1570 new Network(TEST_NET_ID), TEST_IMSI, null)
1571 });
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001572 }
1573
Felipe Lemeef134662016-08-10 14:46:39 -07001574 private void verifyAdvisePersistThreshold() throws Exception {
1575 verify(mStatsService).advisePersistThreshold(anyLong());
Jeff Sharkey0cf6de02012-05-04 15:03:30 -07001576 }
1577
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001578 private static class TestAbstractFuture<T> extends AbstractFuture<T> {
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001579 @Override
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001580 public T get() throws InterruptedException, ExecutionException {
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001581 try {
1582 return get(5, TimeUnit.SECONDS);
1583 } catch (TimeoutException e) {
1584 throw new RuntimeException(e);
1585 }
1586 }
Jeff Sharkey7ee86582011-11-14 18:02:21 -08001587 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001588
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -07001589 private static void assertTimeEquals(long expected, long actual) {
1590 if (expected != actual) {
1591 fail("expected " + formatTime(expected) + " but was actually " + formatTime(actual));
1592 }
1593 }
1594
1595 private static String formatTime(long millis) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06001596 return Instant.ofEpochMilli(millis) + " [" + millis + "]";
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -07001597 }
1598
1599 private static void assertEqualsFuzzy(long expected, long actual, long fuzzy) {
1600 final long low = expected - fuzzy;
1601 final long high = expected + fuzzy;
1602 if (actual < low || actual > high) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06001603 fail("value " + formatTime(actual) + " is outside [" + formatTime(low) + ","
1604 + formatTime(high) + "]");
Jeff Sharkeyaf82ea22011-08-04 15:38:48 -07001605 }
1606 }
1607
1608 private static void assertUnique(LinkedHashSet<Long> seen, Long value) {
1609 if (!seen.add(value)) {
1610 fail("found duplicate time " + value + " in series " + seen.toString());
1611 }
1612 }
1613
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001614 private static void assertNotificationType(int expected, String actualTag) {
Felipe Lemeef134662016-08-10 14:46:39 -07001615 assertEquals("notification type mismatch for '" + actualTag +"'",
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001616 Integer.toString(expected), actualTag.substring(actualTag.lastIndexOf(':') + 1));
1617 }
1618
Felipe Lemee88729d2016-08-17 16:43:01 -07001619 private void assertUidPolicy(int uid, int expected) {
1620 final int actual = mService.getUidPolicy(uid);
1621 if (expected != actual) {
1622 fail("Wrong policy for UID " + uid + ": expected " + uidPoliciesToString(expected)
1623 + ", actual " + uidPoliciesToString(actual));
1624 }
1625 }
1626
Felipe Leme46b451f2016-08-19 08:46:17 -07001627 private void assertWhitelistUids(int... uids) {
Felipe Leme57e3d312016-08-23 14:42:52 -07001628 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_ALLOW_METERED_BACKGROUND), uids);
Felipe Leme46b451f2016-08-19 08:46:17 -07001629 }
1630
Felipe Leme3d3308d2016-08-23 17:41:47 -07001631 private void assertRestrictBackgroundOn() throws Exception {
1632 assertTrue("restrictBackground should be set", mService.getRestrictBackground());
1633 }
1634
1635 private void assertRestrictBackgroundOff() throws Exception {
1636 assertFalse("restrictBackground should not be set", mService.getRestrictBackground());
1637 }
1638
1639 private FutureIntent newRestrictBackgroundChangedFuture() {
1640 return mServiceContext
1641 .nextBroadcastIntent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
1642 }
1643
1644 private void assertRestrictBackgroundChangedReceived(Future<Intent> future,
1645 String expectedPackage) throws Exception {
1646 final String action = ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED;
1647 final Intent intent = future.get(5, TimeUnit.SECONDS);
1648 assertNotNull("Didn't get a " + action + "intent in 5 seconds");
1649 assertEquals("Wrong package on " + action + " intent", expectedPackage, intent.getPackage());
1650 }
1651
Felipe Lemee88729d2016-08-17 16:43:01 -07001652 // TODO: replace by Truth, Hamcrest, or a similar tool.
1653 private void assertContainsInAnyOrder(int[] actual, int...expected) {
1654 final StringBuilder errors = new StringBuilder();
1655 if (actual.length != expected.length) {
1656 errors.append("\tsize does not match\n");
1657 }
1658 final List<Integer> actualList =
1659 Arrays.stream(actual).boxed().collect(Collectors.<Integer>toList());
1660 final List<Integer> expectedList =
1661 Arrays.stream(expected).boxed().collect(Collectors.<Integer>toList());
1662 if (!actualList.containsAll(expectedList)) {
1663 errors.append("\tmissing elements on actual list\n");
1664 }
1665 if (!expectedList.containsAll(actualList)) {
1666 errors.append("\tmissing elements on expected list\n");
1667 }
1668 if (errors.length() > 0) {
1669 fail("assertContainsInAnyOrder(expected=" + Arrays.toString(expected)
1670 + ", actual=" + Arrays.toString(actual) +") failed: \n" + errors);
1671 }
1672 }
1673
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001674 private long getElapsedRealtime() {
1675 return mElapsedRealtime;
1676 }
1677
1678 private void setCurrentTimeMillis(long currentTimeMillis) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001679 RecurrenceRule.sClock = Clock.fixed(Instant.ofEpochMilli(currentTimeMillis),
1680 ZoneId.systemDefault());
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001681 mStartTime = currentTimeMillis;
1682 mElapsedRealtime = 0L;
1683 }
1684
1685 private long currentTimeMillis() {
1686 return mStartTime + mElapsedRealtime;
1687 }
1688
1689 private void incrementCurrentTime(long duration) {
1690 mElapsedRealtime += duration;
1691 }
1692
Felipe Leme3d3308d2016-08-23 17:41:47 -07001693 private FutureIntent mRestrictBackgroundChanged;
1694
1695 private void setRestrictBackground(boolean flag) throws Exception {
Felipe Leme3d3308d2016-08-23 17:41:47 -07001696 mService.setRestrictBackground(flag);
1697 // Sanity check.
1698 assertEquals("restrictBackground not set", flag, mService.getRestrictBackground());
1699 }
1700
Felipe Lemeef134662016-08-10 14:46:39 -07001701 /**
1702 * Creates a mock and registers it to {@link LocalServices}.
1703 */
Felipe Leme9f27e7a2016-08-12 15:19:40 -07001704 private static <T> T addLocalServiceMock(Class<T> clazz) {
Felipe Lemeef134662016-08-10 14:46:39 -07001705 final T mock = mock(clazz);
Felipe Lemeef134662016-08-10 14:46:39 -07001706 LocalServices.addService(clazz, mock);
Felipe Lemeef134662016-08-10 14:46:39 -07001707 return mock;
1708 }
1709
1710 /**
Felipe Lemeef134662016-08-10 14:46:39 -07001711 * Custom Mockito answer used to verify async {@link INetworkPolicyListener} calls.
1712 *
1713 * <p>Typical usage:
1714 * <pre><code>
1715 * mPolicyListener.expect().someCallback(any());
1716 * // do something on objects under test
1717 * mPolicyListener.waitAndVerify().someCallback(eq(expectedValue));
1718 * </code></pre>
1719 */
1720 final class NetworkPolicyListenerAnswer implements Answer<Void> {
1721 private CountDownLatch latch;
1722 private final INetworkPolicyListener listener;
1723
1724 NetworkPolicyListenerAnswer(NetworkPolicyManagerService service) {
1725 this.listener = mock(INetworkPolicyListener.class);
1726 // RemoteCallbackList needs a binder to use as key
1727 when(listener.asBinder()).thenReturn(new Binder());
1728 service.registerListener(listener);
1729 }
1730
1731 @Override
1732 public Void answer(InvocationOnMock invocation) throws Throwable {
1733 Log.d(TAG,"counting down on answer: " + invocation);
1734 latch.countDown();
1735 return null;
1736 }
1737
1738 INetworkPolicyListener expect() {
1739 assertNull("expect() called before waitAndVerify()", latch);
1740 latch = new CountDownLatch(1);
1741 return doAnswer(this).when(listener);
1742 }
1743
1744 INetworkPolicyListener waitAndVerify() {
1745 assertNotNull("waitAndVerify() called before expect()", latch);
1746 try {
1747 assertTrue("callback not called in 5 seconds", latch.await(5, TimeUnit.SECONDS));
1748 } catch (InterruptedException e) {
1749 fail("Thread interrupted before callback called");
1750 } finally {
1751 latch = null;
1752 }
1753 return verify(listener, atLeastOnce());
1754 }
Felipe Leme3d3308d2016-08-23 17:41:47 -07001755
1756 INetworkPolicyListener verifyNotCalled() {
1757 return verify(listener, never());
1758 }
1759
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001760 }
Felipe Lemee88729d2016-08-17 16:43:01 -07001761
1762 private void setNetpolicyXml(Context context) throws Exception {
1763 mPolicyDir = context.getFilesDir();
1764 if (mPolicyDir.exists()) {
1765 IoUtils.deleteContents(mPolicyDir);
1766 }
1767 if (!TextUtils.isEmpty(mNetpolicyXml)) {
1768 final String assetPath = NETPOLICY_DIR + "/" + mNetpolicyXml;
1769 final File netConfigFile = new File(mPolicyDir, "netpolicy.xml");
1770 Log.d(TAG, "Creating " + netConfigFile + " from asset " + assetPath);
1771 try (final InputStream in = context.getResources().getAssets().open(assetPath);
1772 final OutputStream out = new FileOutputStream(netConfigFile)) {
1773 Streams.copy(in, out);
1774 }
1775 }
1776 }
1777
1778 /**
1779 * Annotation used to define the relative path of the {@code netpolicy.xml} file.
1780 */
1781 @Retention(RetentionPolicy.RUNTIME)
1782 @Target(ElementType.METHOD)
1783 public @interface NetPolicyXml {
1784
1785 public String value() default "";
1786
1787 }
1788
1789 /**
1790 * Rule used to set {@code mNetPolicyXml} according to the {@link NetPolicyXml} annotation.
1791 */
1792 public static class NetPolicyMethodRule implements MethodRule {
1793
1794 @Override
1795 public Statement apply(Statement base, FrameworkMethod method, Object target) {
1796 for (Annotation annotation : method.getAnnotations()) {
1797 if ((annotation instanceof NetPolicyXml)) {
1798 final String path = ((NetPolicyXml) annotation).value();
1799 if (!path.isEmpty()) {
1800 ((NetworkPolicyManagerServiceTest) target).mNetpolicyXml = path;
1801 break;
1802 }
1803 }
1804 }
1805 return base;
1806 }
1807 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001808}