NetworkPolicyManagerServiceTest.java revision 8025580449081ddd21f449f8719bc87d1cc9fc7b
1/* 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 19import static android.net.ConnectivityManager.CONNECTIVITY_ACTION; 20import static android.net.ConnectivityManager.TYPE_WIFI; 21import static android.net.NetworkPolicy.LIMIT_DISABLED; 22import static android.net.NetworkPolicy.WARNING_DISABLED; 23import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND; 24import static android.net.NetworkPolicyManager.POLICY_NONE; 25import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND; 26import static android.net.NetworkPolicyManager.computeLastCycleBoundary; 27import static android.net.NetworkPolicyManager.computeNextCycleBoundary; 28import static android.net.NetworkPolicyManager.uidPoliciesToString; 29import static android.net.TrafficStats.KB_IN_BYTES; 30import static android.net.TrafficStats.MB_IN_BYTES; 31import static android.text.format.DateUtils.DAY_IN_MILLIS; 32import static android.text.format.DateUtils.MINUTE_IN_MILLIS; 33import static android.text.format.Time.TIMEZONE_UTC; 34 35import static com.android.server.net.NetworkPolicyManagerService.TYPE_LIMIT; 36import static com.android.server.net.NetworkPolicyManagerService.TYPE_LIMIT_SNOOZED; 37import static com.android.server.net.NetworkPolicyManagerService.TYPE_WARNING; 38 39import static org.junit.Assert.assertEquals; 40import static org.junit.Assert.assertFalse; 41import static org.junit.Assert.assertNotNull; 42import static org.junit.Assert.assertNull; 43import static org.junit.Assert.assertTrue; 44import static org.junit.Assert.fail; 45import static org.mockito.Matchers.any; 46import static org.mockito.Matchers.anyInt; 47import static org.mockito.Matchers.anyLong; 48import static org.mockito.Matchers.anyString; 49import static org.mockito.Matchers.eq; 50import static org.mockito.Matchers.isA; 51import static org.mockito.Matchers.isNull; 52import static org.mockito.Mockito.atLeastOnce; 53import static org.mockito.Mockito.doAnswer; 54import static org.mockito.Mockito.mock; 55import static org.mockito.Mockito.never; 56import static org.mockito.Mockito.verify; 57import static org.mockito.Mockito.when; 58 59import android.Manifest; 60import android.app.ActivityManager; 61import android.app.IActivityManager; 62import android.app.INotificationManager; 63import android.app.IUidObserver; 64import android.app.Notification; 65import android.app.usage.UsageStatsManagerInternal; 66import android.content.Context; 67import android.content.Intent; 68import android.content.pm.ApplicationInfo; 69import android.content.pm.IPackageManager; 70import android.content.pm.PackageInfo; 71import android.content.pm.PackageManager; 72import android.content.pm.Signature; 73import android.net.ConnectivityManager; 74import android.net.IConnectivityManager; 75import android.net.INetworkManagementEventObserver; 76import android.net.INetworkPolicyListener; 77import android.net.INetworkStatsService; 78import android.net.LinkProperties; 79import android.net.NetworkCapabilities; 80import android.net.NetworkInfo; 81import android.net.NetworkInfo.DetailedState; 82import android.net.NetworkPolicy; 83import android.net.NetworkState; 84import android.net.NetworkStats; 85import android.net.NetworkTemplate; 86import android.os.Binder; 87import android.os.INetworkManagementService; 88import android.os.PowerManagerInternal; 89import android.os.UserHandle; 90import android.support.test.InstrumentationRegistry; 91import android.support.test.filters.MediumTest; 92import android.support.test.runner.AndroidJUnit4; 93import android.text.TextUtils; 94import android.text.format.Time; 95import android.util.Log; 96import android.util.TrustedTime; 97 98import com.android.internal.util.test.BroadcastInterceptingContext; 99import com.android.internal.util.test.BroadcastInterceptingContext.FutureIntent; 100import com.android.server.net.NetworkPolicyManagerInternal; 101import com.android.server.net.NetworkPolicyManagerService; 102 103import libcore.io.IoUtils; 104import libcore.io.Streams; 105 106import com.google.common.util.concurrent.AbstractFuture; 107 108import org.junit.After; 109import org.junit.Before; 110import org.junit.BeforeClass; 111import org.junit.Rule; 112import org.junit.Test; 113import org.junit.rules.MethodRule; 114import org.junit.runner.RunWith; 115import org.junit.runners.model.FrameworkMethod; 116import org.junit.runners.model.Statement; 117import org.mockito.ArgumentCaptor; 118import org.mockito.Mock; 119import org.mockito.MockitoAnnotations; 120import org.mockito.invocation.InvocationOnMock; 121import org.mockito.stubbing.Answer; 122 123import java.io.File; 124import java.io.FileOutputStream; 125import java.io.InputStream; 126import java.io.OutputStream; 127import java.lang.annotation.Annotation; 128import java.lang.annotation.ElementType; 129import java.lang.annotation.Retention; 130import java.lang.annotation.RetentionPolicy; 131import java.lang.annotation.Target; 132import java.util.Arrays; 133import java.util.LinkedHashSet; 134import java.util.List; 135import java.util.concurrent.CountDownLatch; 136import java.util.concurrent.ExecutionException; 137import java.util.concurrent.Future; 138import java.util.concurrent.TimeUnit; 139import java.util.concurrent.TimeoutException; 140import java.util.stream.Collectors; 141 142/** 143 * Tests for {@link NetworkPolicyManagerService}. 144 * 145 * <p>Typical usage: 146 * 147 * <pre><code> 148 m -j32 FrameworksServicesTests && adb install -r -g \ 149 ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk && \ 150 adb shell am instrument -e class "com.android.server.NetworkPolicyManagerServiceTest" -w \ 151 "com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner" 152 * </code></pre> 153 */ 154@RunWith(AndroidJUnit4.class) 155@MediumTest 156public class NetworkPolicyManagerServiceTest { 157 private static final String TAG = "NetworkPolicyManagerServiceTest"; 158 159 private static final long TEST_START = 1194220800000L; 160 private static final String TEST_IFACE = "test0"; 161 private static final String TEST_SSID = "AndroidAP"; 162 163 private static NetworkTemplate sTemplateWifi = NetworkTemplate.buildTemplateWifi(TEST_SSID); 164 165 /** 166 * Path on assets where files used by {@link NetPolicyXml} are located. 167 */ 168 private static final String NETPOLICY_DIR = "NetworkPolicyManagerServiceTest/netpolicy"; 169 170 private BroadcastInterceptingContext mServiceContext; 171 private File mPolicyDir; 172 173 /** 174 * Relative path of the XML file that will be used as {@code netpolicy.xml}. 175 * 176 * <p>Typically set through a {@link NetPolicyXml} annotation in the test method. 177 */ 178 private String mNetpolicyXml; 179 180 private @Mock IActivityManager mActivityManager; 181 private @Mock INetworkStatsService mStatsService; 182 private @Mock INetworkManagementService mNetworkManager; 183 private @Mock TrustedTime mTime; 184 private @Mock IConnectivityManager mConnManager; 185 private @Mock INotificationManager mNotifManager; 186 private @Mock PackageManager mPackageManager; 187 private @Mock IPackageManager mIpm; 188 189 private IUidObserver mUidObserver; 190 private INetworkManagementEventObserver mNetworkObserver; 191 192 private NetworkPolicyListenerAnswer mPolicyListener; 193 private NetworkPolicyManagerService mService; 194 195 private long mStartTime; 196 private long mElapsedRealtime; 197 198 private static final int USER_ID = 0; 199 200 private static final int APP_ID_A = android.os.Process.FIRST_APPLICATION_UID + 4; 201 private static final int APP_ID_B = android.os.Process.FIRST_APPLICATION_UID + 8; 202 private static final int APP_ID_C = android.os.Process.FIRST_APPLICATION_UID + 15; 203 private static final int APP_ID_D = android.os.Process.FIRST_APPLICATION_UID + 16; 204 private static final int APP_ID_E = android.os.Process.FIRST_APPLICATION_UID + 23; 205 private static final int APP_ID_F = android.os.Process.FIRST_APPLICATION_UID + 42; 206 207 private static final int UID_A = UserHandle.getUid(USER_ID, APP_ID_A); 208 private static final int UID_B = UserHandle.getUid(USER_ID, APP_ID_B); 209 private static final int UID_C = UserHandle.getUid(USER_ID, APP_ID_C); 210 private static final int UID_D = UserHandle.getUid(USER_ID, APP_ID_D); 211 private static final int UID_E = UserHandle.getUid(USER_ID, APP_ID_E); 212 private static final int UID_F = UserHandle.getUid(USER_ID, APP_ID_F); 213 214 private static final String PKG_NAME_A = "name.is.A,pkg.A"; 215 216 public final @Rule NetPolicyMethodRule mNetPolicyXmlRule = new NetPolicyMethodRule(); 217 218 @BeforeClass 219 public static void registerLocalServices() { 220 addLocalServiceMock(PowerManagerInternal.class); 221 addLocalServiceMock(DeviceIdleController.LocalService.class); 222 final UsageStatsManagerInternal usageStats = 223 addLocalServiceMock(UsageStatsManagerInternal.class); 224 when(usageStats.getIdleUidsForUser(anyInt())).thenReturn(new int[]{}); 225 } 226 227 @Before 228 public void callSystemReady() throws Exception { 229 MockitoAnnotations.initMocks(this); 230 231 final Context context = InstrumentationRegistry.getContext(); 232 233 setCurrentTimeMillis(TEST_START); 234 235 // intercept various broadcasts, and pretend that uids have packages 236 mServiceContext = new BroadcastInterceptingContext(context) { 237 @Override 238 public PackageManager getPackageManager() { 239 return mPackageManager; 240 } 241 242 @Override 243 public void startActivity(Intent intent) { 244 // ignored 245 } 246 }; 247 248 setNetpolicyXml(context); 249 250 doAnswer(new Answer<Void>() { 251 252 @Override 253 public Void answer(InvocationOnMock invocation) throws Throwable { 254 mUidObserver = (IUidObserver) invocation.getArguments()[0]; 255 Log.d(TAG, "set mUidObserver to " + mUidObserver); 256 return null; 257 } 258 }).when(mActivityManager).registerUidObserver(any(), anyInt(), 259 eq(ActivityManager.PROCESS_STATE_UNKNOWN), isNull(String.class)); 260 261 mService = new NetworkPolicyManagerService(mServiceContext, mActivityManager, mStatsService, 262 mNetworkManager, mIpm, mTime, mPolicyDir, true); 263 mService.bindConnectivityManager(mConnManager); 264 mService.bindNotificationManager(mNotifManager); 265 mPolicyListener = new NetworkPolicyListenerAnswer(mService); 266 267 // Sets some common expectations. 268 when(mPackageManager.getPackageInfo(anyString(), anyInt())).thenAnswer( 269 new Answer<PackageInfo>() { 270 271 @Override 272 public PackageInfo answer(InvocationOnMock invocation) throws Throwable { 273 final String packageName = (String) invocation.getArguments()[0]; 274 final PackageInfo info = new PackageInfo(); 275 final Signature signature; 276 if ("android".equals(packageName)) { 277 signature = new Signature("F00D"); 278 } else { 279 signature = new Signature("DEAD"); 280 } 281 info.signatures = new Signature[] { 282 signature 283 }; 284 return info; 285 } 286 }); 287 when(mPackageManager.getApplicationInfoAsUser(anyString(), anyInt(), anyInt())) 288 .thenReturn(new ApplicationInfo()); 289 when(mPackageManager.getPackagesForUid(UID_A)).thenReturn(new String[] {PKG_NAME_A}); 290 when(mNetworkManager.isBandwidthControlEnabled()).thenReturn(true); 291 expectCurrentTime(); 292 293 // Prepare NPMS. 294 mService.systemReady(mService.networkScoreAndNetworkManagementServiceReady()); 295 296 // catch INetworkManagementEventObserver during systemReady() 297 final ArgumentCaptor<INetworkManagementEventObserver> networkObserver = 298 ArgumentCaptor.forClass(INetworkManagementEventObserver.class); 299 verify(mNetworkManager).registerObserver(networkObserver.capture()); 300 mNetworkObserver = networkObserver.getValue(); 301 } 302 303 @After 304 public void removeFiles() throws Exception { 305 for (File file : mPolicyDir.listFiles()) { 306 file.delete(); 307 } 308 } 309 310 @After 311 public void unregisterLocalServices() throws Exception { 312 // Registered by NetworkPolicyManagerService's constructor. 313 LocalServices.removeServiceForTest(NetworkPolicyManagerInternal.class); 314 } 315 316 @Test 317 public void testTurnRestrictBackgroundOn() throws Exception { 318 assertRestrictBackgroundOff(); // Sanity check. 319 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture(); 320 setRestrictBackground(true); 321 assertRestrictBackgroundChangedReceived(futureIntent, null); 322 } 323 324 @Test 325 @NetPolicyXml("restrict-background-on.xml") 326 public void testTurnRestrictBackgroundOff() throws Exception { 327 assertRestrictBackgroundOn(); // Sanity check. 328 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture(); 329 setRestrictBackground(false); 330 assertRestrictBackgroundChangedReceived(futureIntent, null); 331 } 332 333 /** 334 * Adds whitelist when restrict background is on - app should receive an intent. 335 */ 336 @Test 337 @NetPolicyXml("restrict-background-on.xml") 338 public void testAddRestrictBackgroundWhitelist_restrictBackgroundOn() throws Exception { 339 assertRestrictBackgroundOn(); // Sanity check. 340 addRestrictBackgroundWhitelist(true); 341 } 342 343 /** 344 * Adds whitelist when restrict background is off - app should not receive an intent. 345 */ 346 @Test 347 public void testAddRestrictBackgroundWhitelist_restrictBackgroundOff() throws Exception { 348 assertRestrictBackgroundOff(); // Sanity check. 349 addRestrictBackgroundWhitelist(false); 350 } 351 352 private void addRestrictBackgroundWhitelist(boolean expectIntent) throws Exception { 353 // Sanity checks. 354 assertWhitelistUids(); 355 assertUidPolicy(UID_A, POLICY_NONE); 356 357 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture(); 358 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt()); 359 360 mService.setUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND); 361 362 assertWhitelistUids(UID_A); 363 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND); 364 mPolicyListener.waitAndVerify() 365 .onUidPoliciesChanged(APP_ID_A, POLICY_ALLOW_METERED_BACKGROUND); 366 if (expectIntent) { 367 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A); 368 } else { 369 futureIntent.assertNotReceived(); 370 } 371 } 372 373 /** 374 * Removes whitelist when restrict background is on - app should receive an intent. 375 */ 376 @Test 377 @NetPolicyXml("uidA-whitelisted-restrict-background-on.xml") 378 public void testRemoveRestrictBackgroundWhitelist_restrictBackgroundOn() throws Exception { 379 assertRestrictBackgroundOn(); // Sanity check. 380 removeRestrictBackgroundWhitelist(true); 381 } 382 383 /** 384 * Removes whitelist when restrict background is off - app should not receive an intent. 385 */ 386 @Test 387 @NetPolicyXml("uidA-whitelisted-restrict-background-off.xml") 388 public void testRemoveRestrictBackgroundWhitelist_restrictBackgroundOff() throws Exception { 389 assertRestrictBackgroundOff(); // Sanity check. 390 removeRestrictBackgroundWhitelist(false); 391 } 392 393 private void removeRestrictBackgroundWhitelist(boolean expectIntent) throws Exception { 394 // Sanity checks. 395 assertWhitelistUids(UID_A); 396 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND); 397 398 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture(); 399 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt()); 400 401 mService.setUidPolicy(UID_A, POLICY_NONE); 402 403 assertWhitelistUids(); 404 assertUidPolicy(UID_A, POLICY_NONE); 405 mPolicyListener.waitAndVerify().onUidPoliciesChanged(APP_ID_A, POLICY_NONE); 406 if (expectIntent) { 407 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A); 408 } else { 409 futureIntent.assertNotReceived(); 410 } 411 } 412 413 /** 414 * Adds blacklist when restrict background is on - app should not receive an intent. 415 */ 416 @Test 417 @NetPolicyXml("restrict-background-on.xml") 418 public void testAddRestrictBackgroundBlacklist_restrictBackgroundOn() throws Exception { 419 assertRestrictBackgroundOn(); // Sanity check. 420 addRestrictBackgroundBlacklist(false); 421 } 422 423 /** 424 * Adds blacklist when restrict background is off - app should receive an intent. 425 */ 426 @Test 427 public void testAddRestrictBackgroundBlacklist_restrictBackgroundOff() throws Exception { 428 assertRestrictBackgroundOff(); // Sanity check. 429 addRestrictBackgroundBlacklist(true); 430 } 431 432 private void addRestrictBackgroundBlacklist(boolean expectIntent) throws Exception { 433 assertUidPolicy(UID_A, POLICY_NONE); // Sanity check. 434 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture(); 435 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt()); 436 437 mService.setUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND); 438 439 assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND); 440 mPolicyListener.waitAndVerify() 441 .onUidPoliciesChanged(APP_ID_A, POLICY_REJECT_METERED_BACKGROUND); 442 if (expectIntent) { 443 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A); 444 } else { 445 futureIntent.assertNotReceived(); 446 } 447 } 448 449 /** 450 * Removes blacklist when restrict background is on - app should not receive an intent. 451 */ 452 @Test 453 @NetPolicyXml("uidA-blacklisted-restrict-background-on.xml") 454 public void testRemoveRestrictBackgroundBlacklist_restrictBackgroundOn() throws Exception { 455 assertRestrictBackgroundOn(); // Sanity check. 456 removeRestrictBackgroundBlacklist(false); 457 } 458 459 /** 460 * Removes blacklist when restrict background is off - app should receive an intent. 461 */ 462 @Test 463 @NetPolicyXml("uidA-blacklisted-restrict-background-off.xml") 464 public void testRemoveRestrictBackgroundBlacklist_restrictBackgroundOff() throws Exception { 465 assertRestrictBackgroundOff(); // Sanity check. 466 removeRestrictBackgroundBlacklist(true); 467 } 468 469 private void removeRestrictBackgroundBlacklist(boolean expectIntent) throws Exception { 470 assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND); // Sanity check. 471 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture(); 472 mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt()); 473 474 mService.setUidPolicy(UID_A, POLICY_NONE); 475 476 assertUidPolicy(UID_A, POLICY_NONE); 477 mPolicyListener.waitAndVerify() 478 .onUidPoliciesChanged(APP_ID_A, POLICY_NONE); 479 if (expectIntent) { 480 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A); 481 } else { 482 futureIntent.assertNotReceived(); 483 } 484 } 485 486 @Test 487 @NetPolicyXml("uidA-blacklisted-restrict-background-on.xml") 488 public void testBlacklistedAppIsNotNotifiedWhenRestrictBackgroundIsOn() throws Exception { 489 // Sanity checks. 490 assertRestrictBackgroundOn(); 491 assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND); 492 493 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture(); 494 setRestrictBackground(true); 495 futureIntent.assertNotReceived(); 496 } 497 498 @Test 499 @NetPolicyXml("uidA-whitelisted-restrict-background-on.xml") 500 public void testWhitelistedAppIsNotNotifiedWhenRestrictBackgroundIsOn() throws Exception { 501 // Sanity checks. 502 assertRestrictBackgroundOn(); 503 assertWhitelistUids(UID_A); 504 505 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture(); 506 setRestrictBackground(true); 507 futureIntent.assertNotReceived(); 508 } 509 510 @Test 511 @NetPolicyXml("uidA-whitelisted-restrict-background-on.xml") 512 public void testWhitelistedAppIsNotifiedWhenBlacklisted() throws Exception { 513 // Sanity checks. 514 assertRestrictBackgroundOn(); 515 assertWhitelistUids(UID_A); 516 517 final FutureIntent futureIntent = newRestrictBackgroundChangedFuture(); 518 mService.setUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND); 519 assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A); 520 } 521 522 @Test 523 @NetPolicyXml("restrict-background-lists-whitelist-format.xml") 524 public void testRestrictBackgroundLists_whitelistFormat() throws Exception { 525 restrictBackgroundListsTest(); 526 } 527 528 @Test 529 @NetPolicyXml("restrict-background-lists-uid-policy-format.xml") 530 public void testRestrictBackgroundLists_uidPolicyFormat() throws Exception { 531 restrictBackgroundListsTest(); 532 } 533 534 private void restrictBackgroundListsTest() throws Exception { 535 // UIds that are whitelisted. 536 assertWhitelistUids(UID_A, UID_B, UID_C); 537 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND); 538 assertUidPolicy(UID_B, POLICY_ALLOW_METERED_BACKGROUND); 539 assertUidPolicy(UID_C, POLICY_ALLOW_METERED_BACKGROUND); 540 541 // UIDs that are blacklisted. 542 assertUidPolicy(UID_D, POLICY_NONE); 543 assertUidPolicy(UID_E, POLICY_REJECT_METERED_BACKGROUND); 544 545 // UIDS that have legacy policies. 546 assertUidPolicy(UID_F, 2); // POLICY_ALLOW_BACKGROUND_BATTERY_SAVE 547 548 // Remove whitelist. 549 mService.setUidPolicy(UID_A, POLICY_NONE); 550 assertUidPolicy(UID_A, POLICY_NONE); 551 assertWhitelistUids(UID_B, UID_C); 552 553 // Add whitelist when blacklisted. 554 mService.setUidPolicy(UID_E, POLICY_ALLOW_METERED_BACKGROUND); 555 assertUidPolicy(UID_E, POLICY_ALLOW_METERED_BACKGROUND); 556 assertWhitelistUids(UID_B, UID_C, UID_E); 557 558 // Add blacklist when whitelisted. 559 mService.setUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND); 560 assertUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND); 561 assertWhitelistUids(UID_C, UID_E); 562 } 563 564 /** 565 * Tests scenario where an UID had {@code restrict-background} and {@code uid-policy} tags. 566 */ 567 @Test 568 @NetPolicyXml("restrict-background-lists-mixed-format.xml") 569 public void testRestrictBackgroundLists_mixedFormat() throws Exception { 570 assertWhitelistUids(UID_A, UID_C, UID_D); 571 assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND); 572 assertUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND); // Blacklist prevails. 573 assertUidPolicy(UID_C, (POLICY_ALLOW_METERED_BACKGROUND | 2)); 574 assertUidPolicy(UID_D, POLICY_ALLOW_METERED_BACKGROUND); 575 } 576 577 @Test 578 @NetPolicyXml("uids-with-mixed-policies.xml") 579 public void testGetUidsWithPolicy() throws Exception { 580 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_NONE)); 581 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND), 582 UID_B, UID_D); 583 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_ALLOW_METERED_BACKGROUND), 584 UID_E, UID_F); 585 // Legacy (POLICY_ALLOW_BACKGROUND_BATTERY_SAVE) 586 assertContainsInAnyOrder(mService.getUidsWithPolicy(2), 587 UID_C, UID_D, UID_F); 588 } 589 590 // NOTE: testPolicyChangeTriggersListener() is too superficial, they 591 // don't check for side-effects (like calls to NetworkManagementService) neither cover all 592 // different modes (Data Saver, Battery Saver, Doze, App idle, etc...). 593 // These scenarios are extensively tested on CTS' HostsideRestrictBackgroundNetworkTests. 594 @Test 595 public void testUidForeground() throws Exception { 596 // push all uids into background 597 mUidObserver.onUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE, 0); 598 mUidObserver.onUidStateChanged(UID_B, ActivityManager.PROCESS_STATE_SERVICE, 0); 599 assertFalse(mService.isUidForeground(UID_A)); 600 assertFalse(mService.isUidForeground(UID_B)); 601 602 // push one of the uids into foreground 603 mUidObserver.onUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_TOP, 0); 604 assertTrue(mService.isUidForeground(UID_A)); 605 assertFalse(mService.isUidForeground(UID_B)); 606 607 // and swap another uid into foreground 608 mUidObserver.onUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE, 0); 609 mUidObserver.onUidStateChanged(UID_B, ActivityManager.PROCESS_STATE_TOP, 0); 610 assertFalse(mService.isUidForeground(UID_A)); 611 assertTrue(mService.isUidForeground(UID_B)); 612 } 613 614 @Test 615 public void testLastCycleBoundaryThisMonth() throws Exception { 616 // assume cycle day of "5th", which should be in same month 617 final long currentTime = parseTime("2007-11-14T00:00:00.000Z"); 618 final long expectedCycle = parseTime("2007-11-05T00:00:00.000Z"); 619 620 final NetworkPolicy policy = new NetworkPolicy( 621 sTemplateWifi, 5, TIMEZONE_UTC, 1024L, 1024L, false); 622 final long actualCycle = computeLastCycleBoundary(currentTime, policy); 623 assertTimeEquals(expectedCycle, actualCycle); 624 } 625 626 @Test 627 public void testLastCycleBoundaryLastMonth() throws Exception { 628 // assume cycle day of "20th", which should be in last month 629 final long currentTime = parseTime("2007-11-14T00:00:00.000Z"); 630 final long expectedCycle = parseTime("2007-10-20T00:00:00.000Z"); 631 632 final NetworkPolicy policy = new NetworkPolicy( 633 sTemplateWifi, 20, TIMEZONE_UTC, 1024L, 1024L, false); 634 final long actualCycle = computeLastCycleBoundary(currentTime, policy); 635 assertTimeEquals(expectedCycle, actualCycle); 636 } 637 638 @Test 639 public void testLastCycleBoundaryThisMonthFebruary() throws Exception { 640 // assume cycle day of "30th" in february; should go to january 641 final long currentTime = parseTime("2007-02-14T00:00:00.000Z"); 642 final long expectedCycle = parseTime("2007-01-30T00:00:00.000Z"); 643 644 final NetworkPolicy policy = new NetworkPolicy( 645 sTemplateWifi, 30, TIMEZONE_UTC, 1024L, 1024L, false); 646 final long actualCycle = computeLastCycleBoundary(currentTime, policy); 647 assertTimeEquals(expectedCycle, actualCycle); 648 } 649 650 @Test 651 public void testLastCycleBoundaryLastMonthFebruary() throws Exception { 652 // assume cycle day of "30th" in february, which should clamp 653 final long currentTime = parseTime("2007-03-14T00:00:00.000Z"); 654 final long expectedCycle = parseTime("2007-02-28T23:59:59.000Z"); 655 656 final NetworkPolicy policy = new NetworkPolicy( 657 sTemplateWifi, 30, TIMEZONE_UTC, 1024L, 1024L, false); 658 final long actualCycle = computeLastCycleBoundary(currentTime, policy); 659 assertTimeEquals(expectedCycle, actualCycle); 660 } 661 662 @Test 663 public void testCycleBoundaryLeapYear() throws Exception { 664 final NetworkPolicy policy = new NetworkPolicy( 665 sTemplateWifi, 29, TIMEZONE_UTC, 1024L, 1024L, false); 666 667 assertTimeEquals(parseTime("2012-01-29T00:00:00.000Z"), 668 computeNextCycleBoundary(parseTime("2012-01-14T00:00:00.000Z"), policy)); 669 assertTimeEquals(parseTime("2012-02-29T00:00:00.000Z"), 670 computeNextCycleBoundary(parseTime("2012-02-14T00:00:00.000Z"), policy)); 671 assertTimeEquals(parseTime("2012-02-29T00:00:00.000Z"), 672 computeLastCycleBoundary(parseTime("2012-03-14T00:00:00.000Z"), policy)); 673 assertTimeEquals(parseTime("2012-03-29T00:00:00.000Z"), 674 computeNextCycleBoundary(parseTime("2012-03-14T00:00:00.000Z"), policy)); 675 676 assertTimeEquals(parseTime("2007-01-29T00:00:00.000Z"), 677 computeNextCycleBoundary(parseTime("2007-01-14T00:00:00.000Z"), policy)); 678 assertTimeEquals(parseTime("2007-02-28T23:59:59.000Z"), 679 computeNextCycleBoundary(parseTime("2007-02-14T00:00:00.000Z"), policy)); 680 assertTimeEquals(parseTime("2007-02-28T23:59:59.000Z"), 681 computeLastCycleBoundary(parseTime("2007-03-14T00:00:00.000Z"), policy)); 682 assertTimeEquals(parseTime("2007-03-29T00:00:00.000Z"), 683 computeNextCycleBoundary(parseTime("2007-03-14T00:00:00.000Z"), policy)); 684 } 685 686 @Test 687 public void testNextCycleTimezoneAfterUtc() throws Exception { 688 // US/Central is UTC-6 689 final NetworkPolicy policy = new NetworkPolicy( 690 sTemplateWifi, 10, "US/Central", 1024L, 1024L, false); 691 assertTimeEquals(parseTime("2012-01-10T06:00:00.000Z"), 692 computeNextCycleBoundary(parseTime("2012-01-05T00:00:00.000Z"), policy)); 693 } 694 695 @Test 696 public void testNextCycleTimezoneBeforeUtc() throws Exception { 697 // Israel is UTC+2 698 final NetworkPolicy policy = new NetworkPolicy( 699 sTemplateWifi, 10, "Israel", 1024L, 1024L, false); 700 assertTimeEquals(parseTime("2012-01-09T22:00:00.000Z"), 701 computeNextCycleBoundary(parseTime("2012-01-05T00:00:00.000Z"), policy)); 702 } 703 704 @Test 705 public void testNextCycleSane() throws Exception { 706 final NetworkPolicy policy = new NetworkPolicy( 707 sTemplateWifi, 31, TIMEZONE_UTC, WARNING_DISABLED, LIMIT_DISABLED, false); 708 final LinkedHashSet<Long> seen = new LinkedHashSet<Long>(); 709 710 // walk forwards, ensuring that cycle boundaries don't get stuck 711 long currentCycle = computeNextCycleBoundary(parseTime("2011-08-01T00:00:00.000Z"), policy); 712 for (int i = 0; i < 128; i++) { 713 long nextCycle = computeNextCycleBoundary(currentCycle, policy); 714 assertEqualsFuzzy(DAY_IN_MILLIS * 30, nextCycle - currentCycle, DAY_IN_MILLIS * 3); 715 assertUnique(seen, nextCycle); 716 currentCycle = nextCycle; 717 } 718 } 719 720 @Test 721 public void testLastCycleSane() throws Exception { 722 final NetworkPolicy policy = new NetworkPolicy( 723 sTemplateWifi, 31, TIMEZONE_UTC, WARNING_DISABLED, LIMIT_DISABLED, false); 724 final LinkedHashSet<Long> seen = new LinkedHashSet<Long>(); 725 726 // walk backwards, ensuring that cycle boundaries look sane 727 long currentCycle = computeLastCycleBoundary(parseTime("2011-08-04T00:00:00.000Z"), policy); 728 for (int i = 0; i < 128; i++) { 729 long lastCycle = computeLastCycleBoundary(currentCycle, policy); 730 assertEqualsFuzzy(DAY_IN_MILLIS * 30, currentCycle - lastCycle, DAY_IN_MILLIS * 3); 731 assertUnique(seen, lastCycle); 732 currentCycle = lastCycle; 733 } 734 } 735 736 @Test 737 public void testCycleTodayJanuary() throws Exception { 738 final NetworkPolicy policy = new NetworkPolicy( 739 sTemplateWifi, 14, "US/Pacific", 1024L, 1024L, false); 740 741 assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"), 742 computeNextCycleBoundary(parseTime("2013-01-13T23:59:59.000-08:00"), policy)); 743 assertTimeEquals(parseTime("2013-02-14T00:00:00.000-08:00"), 744 computeNextCycleBoundary(parseTime("2013-01-14T00:00:01.000-08:00"), policy)); 745 assertTimeEquals(parseTime("2013-02-14T00:00:00.000-08:00"), 746 computeNextCycleBoundary(parseTime("2013-01-14T15:11:00.000-08:00"), policy)); 747 748 assertTimeEquals(parseTime("2012-12-14T00:00:00.000-08:00"), 749 computeLastCycleBoundary(parseTime("2013-01-13T23:59:59.000-08:00"), policy)); 750 assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"), 751 computeLastCycleBoundary(parseTime("2013-01-14T00:00:01.000-08:00"), policy)); 752 assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"), 753 computeLastCycleBoundary(parseTime("2013-01-14T15:11:00.000-08:00"), policy)); 754 } 755 756 @Test 757 public void testLastCycleBoundaryDST() throws Exception { 758 final long currentTime = parseTime("1989-01-02T07:30:00.000"); 759 final long expectedCycle = parseTime("1988-12-03T02:00:00.000Z"); 760 761 final NetworkPolicy policy = new NetworkPolicy( 762 sTemplateWifi, 3, "America/Argentina/Buenos_Aires", 1024L, 1024L, false); 763 final long actualCycle = computeLastCycleBoundary(currentTime, policy); 764 assertTimeEquals(expectedCycle, actualCycle); 765 } 766 767 @Test 768 public void testLastCycleBoundaryJanuaryDST() throws Exception { 769 final long currentTime = parseTime("1989-01-26T21:00:00.000Z"); 770 final long expectedCycle = parseTime("1989-01-01T01:59:59.000Z"); 771 772 final NetworkPolicy policy = new NetworkPolicy( 773 sTemplateWifi, 32, "America/Argentina/Buenos_Aires", 1024L, 1024L, false); 774 final long actualCycle = computeLastCycleBoundary(currentTime, policy); 775 assertTimeEquals(expectedCycle, actualCycle); 776 } 777 778 @Test 779 public void testNetworkPolicyAppliedCycleLastMonth() throws Exception { 780 NetworkState[] state = null; 781 NetworkStats stats = null; 782 783 final long TIME_FEB_15 = 1171497600000L; 784 final long TIME_MAR_10 = 1173484800000L; 785 final int CYCLE_DAY = 15; 786 787 setCurrentTimeMillis(TIME_MAR_10); 788 789 // first, pretend that wifi network comes online. no policy active, 790 // which means we shouldn't push limit to interface. 791 state = new NetworkState[] { buildWifi() }; 792 when(mConnManager.getAllNetworkState()).thenReturn(state); 793 expectCurrentTime(); 794 795 mPolicyListener.expect().onMeteredIfacesChanged(any()); 796 mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION)); 797 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(any()); 798 799 // now change cycle to be on 15th, and test in early march, to verify we 800 // pick cycle day in previous month. 801 when(mConnManager.getAllNetworkState()).thenReturn(state); 802 expectCurrentTime(); 803 804 // pretend that 512 bytes total have happened 805 stats = new NetworkStats(getElapsedRealtime(), 1) 806 .addIfaceValues(TEST_IFACE, 256L, 2L, 256L, 2L); 807 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15, TIME_MAR_10)) 808 .thenReturn(stats.getTotalBytes()); 809 810 mPolicyListener.expect().onMeteredIfacesChanged(any()); 811 setNetworkPolicies(new NetworkPolicy( 812 sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, 1 * MB_IN_BYTES, 2 * MB_IN_BYTES, false)); 813 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE})); 814 815 // TODO: consider making strongly ordered mock 816 verifyPolicyDataEnable(TYPE_WIFI, true); 817 verifyRemoveInterfaceQuota(TEST_IFACE); 818 verifySetInterfaceQuota(TEST_IFACE, (2 * MB_IN_BYTES) - 512); 819 } 820 821 @Test 822 public void testOverWarningLimitNotification() throws Exception { 823 NetworkState[] state = null; 824 NetworkStats stats = null; 825 Future<String> tagFuture = null; 826 827 final long TIME_FEB_15 = 1171497600000L; 828 final long TIME_MAR_10 = 1173484800000L; 829 final int CYCLE_DAY = 15; 830 831 setCurrentTimeMillis(TIME_MAR_10); 832 833 // assign wifi policy 834 state = new NetworkState[] {}; 835 stats = new NetworkStats(getElapsedRealtime(), 1) 836 .addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L); 837 838 { 839 expectCurrentTime(); 840 when(mConnManager.getAllNetworkState()).thenReturn(state); 841 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15, 842 currentTimeMillis())).thenReturn(stats.getTotalBytes()); 843 844 mPolicyListener.expect().onMeteredIfacesChanged(any()); 845 setNetworkPolicies(new NetworkPolicy(sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, 1 846 * MB_IN_BYTES, 2 * MB_IN_BYTES, false)); 847 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(any()); 848 verifyPolicyDataEnable(TYPE_WIFI, true); 849 } 850 851 // bring up wifi network 852 incrementCurrentTime(MINUTE_IN_MILLIS); 853 state = new NetworkState[] { buildWifi() }; 854 stats = new NetworkStats(getElapsedRealtime(), 1) 855 .addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L); 856 857 { 858 expectCurrentTime(); 859 when(mConnManager.getAllNetworkState()).thenReturn(state); 860 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15, 861 currentTimeMillis())).thenReturn(stats.getTotalBytes()); 862 863 mPolicyListener.expect().onMeteredIfacesChanged(any()); 864 mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION)); 865 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE})); 866 867 verifyPolicyDataEnable(TYPE_WIFI, true); 868 verifyRemoveInterfaceQuota(TEST_IFACE); 869 verifySetInterfaceQuota(TEST_IFACE, 2 * MB_IN_BYTES); 870 } 871 872 // go over warning, which should kick notification 873 incrementCurrentTime(MINUTE_IN_MILLIS); 874 stats = new NetworkStats(getElapsedRealtime(), 1) 875 .addIfaceValues(TEST_IFACE, 1536 * KB_IN_BYTES, 15L, 0L, 0L); 876 877 { 878 expectCurrentTime(); 879 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15, 880 currentTimeMillis())).thenReturn(stats.getTotalBytes()); 881 tagFuture = expectEnqueueNotification(); 882 883 mNetworkObserver.limitReached(null, TEST_IFACE); 884 885 assertNotificationType(TYPE_WARNING, tagFuture.get()); 886 verifyPolicyDataEnable(TYPE_WIFI, true); 887 888 } 889 890 // go over limit, which should kick notification and dialog 891 incrementCurrentTime(MINUTE_IN_MILLIS); 892 stats = new NetworkStats(getElapsedRealtime(), 1) 893 .addIfaceValues(TEST_IFACE, 5 * MB_IN_BYTES, 512L, 0L, 0L); 894 895 { 896 expectCurrentTime(); 897 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15, 898 currentTimeMillis())).thenReturn(stats.getTotalBytes()); 899 tagFuture = expectEnqueueNotification(); 900 901 mNetworkObserver.limitReached(null, TEST_IFACE); 902 903 assertNotificationType(TYPE_LIMIT, tagFuture.get()); 904 verifyPolicyDataEnable(TYPE_WIFI, false); 905 } 906 907 // now snooze policy, which should remove quota 908 incrementCurrentTime(MINUTE_IN_MILLIS); 909 910 { 911 expectCurrentTime(); 912 when(mConnManager.getAllNetworkState()).thenReturn(state); 913 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15, 914 currentTimeMillis())).thenReturn(stats.getTotalBytes()); 915 tagFuture = expectEnqueueNotification(); 916 917 mPolicyListener.expect().onMeteredIfacesChanged(any()); 918 mService.snoozeLimit(sTemplateWifi); 919 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE})); 920 921 assertNotificationType(TYPE_LIMIT_SNOOZED, tagFuture.get()); 922 // snoozed interface still has high quota so background data is 923 // still restricted. 924 verifyRemoveInterfaceQuota(TEST_IFACE); 925 verifySetInterfaceQuota(TEST_IFACE, Long.MAX_VALUE); 926 verifyPolicyDataEnable(TYPE_WIFI, true); 927 } 928 } 929 930 @Test 931 public void testMeteredNetworkWithoutLimit() throws Exception { 932 NetworkState[] state = null; 933 NetworkStats stats = null; 934 935 final long TIME_FEB_15 = 1171497600000L; 936 final long TIME_MAR_10 = 1173484800000L; 937 final int CYCLE_DAY = 15; 938 939 setCurrentTimeMillis(TIME_MAR_10); 940 941 // bring up wifi network with metered policy 942 state = new NetworkState[] { buildWifi() }; 943 stats = new NetworkStats(getElapsedRealtime(), 1) 944 .addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L); 945 946 { 947 expectCurrentTime(); 948 when(mConnManager.getAllNetworkState()).thenReturn(state); 949 when(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15, 950 currentTimeMillis())).thenReturn(stats.getTotalBytes()); 951 952 mPolicyListener.expect().onMeteredIfacesChanged(any()); 953 setNetworkPolicies(new NetworkPolicy( 954 sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, WARNING_DISABLED, LIMIT_DISABLED, 955 true)); 956 mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE})); 957 958 verifyPolicyDataEnable(TYPE_WIFI, true); 959 verifyRemoveInterfaceQuota(TEST_IFACE); 960 verifySetInterfaceQuota(TEST_IFACE, Long.MAX_VALUE); 961 } 962 } 963 964 private static long parseTime(String time) { 965 final Time result = new Time(); 966 result.parse3339(time); 967 return result.toMillis(true); 968 } 969 970 private void setNetworkPolicies(NetworkPolicy... policies) { 971 mService.setNetworkPolicies(policies); 972 } 973 974 private static NetworkState buildWifi() { 975 final NetworkInfo info = new NetworkInfo(TYPE_WIFI, 0, null, null); 976 info.setDetailedState(DetailedState.CONNECTED, null, null); 977 final LinkProperties prop = new LinkProperties(); 978 prop.setInterfaceName(TEST_IFACE); 979 final NetworkCapabilities networkCapabilities = new NetworkCapabilities(); 980 return new NetworkState(info, prop, networkCapabilities, null, null, TEST_SSID); 981 } 982 983 private void expectCurrentTime() throws Exception { 984 when(mTime.forceRefresh()).thenReturn(false); 985 when(mTime.hasCache()).thenReturn(true); 986 when(mTime.currentTimeMillis()).thenReturn(currentTimeMillis()); 987 when(mTime.getCacheAge()).thenReturn(0L); 988 when(mTime.getCacheCertainty()).thenReturn(0L); 989 } 990 991 private Future<String> expectEnqueueNotification() throws Exception { 992 final FutureAnswer<String> futureAnswer = new FutureAnswer<String>(2); 993 doAnswer(futureAnswer).when(mNotifManager).enqueueNotificationWithTag( 994 anyString(), anyString(), anyString() /* capture here (index 2)*/, 995 anyInt(), isA(Notification.class), isA(int[].class), anyInt()); 996 return futureAnswer; 997 } 998 999 private void expectHasInternetPermission(int uid, boolean hasIt) throws Exception { 1000 when(mIpm.checkUidPermission(Manifest.permission.INTERNET, uid)).thenReturn( 1001 hasIt ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED); 1002 } 1003 1004 private void verifySetInterfaceQuota(String iface, long quotaBytes) throws Exception { 1005 verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(iface, quotaBytes); 1006 } 1007 1008 private void verifyRemoveInterfaceQuota(String iface) throws Exception { 1009 verify(mNetworkManager, atLeastOnce()).removeInterfaceQuota(iface); 1010 } 1011 1012 private Future<Void> verifyPolicyDataEnable(int type, boolean enabled) throws Exception { 1013 // TODO: bring back this test 1014 return null; 1015 } 1016 1017 private void verifyAdvisePersistThreshold() throws Exception { 1018 verify(mStatsService).advisePersistThreshold(anyLong()); 1019 } 1020 1021 private static class TestAbstractFuture<T> extends AbstractFuture<T> { 1022 @Override 1023 public T get() throws InterruptedException, ExecutionException { 1024 try { 1025 return get(5, TimeUnit.SECONDS); 1026 } catch (TimeoutException e) { 1027 throw new RuntimeException(e); 1028 } 1029 } 1030 } 1031 1032 private static class FutureAnswer<T> extends TestAbstractFuture<T> implements Answer<Void> { 1033 private final int index; 1034 1035 FutureAnswer(int index) { 1036 this.index = index; 1037 } 1038 @Override 1039 public Void answer(InvocationOnMock invocation) throws Throwable { 1040 @SuppressWarnings("unchecked") 1041 T captured = (T) invocation.getArguments()[index]; 1042 set(captured); 1043 return null; 1044 } 1045 } 1046 1047 private static void assertTimeEquals(long expected, long actual) { 1048 if (expected != actual) { 1049 fail("expected " + formatTime(expected) + " but was actually " + formatTime(actual)); 1050 } 1051 } 1052 1053 private static String formatTime(long millis) { 1054 final Time time = new Time(Time.TIMEZONE_UTC); 1055 time.set(millis); 1056 return time.format3339(false); 1057 } 1058 1059 private static void assertEqualsFuzzy(long expected, long actual, long fuzzy) { 1060 final long low = expected - fuzzy; 1061 final long high = expected + fuzzy; 1062 if (actual < low || actual > high) { 1063 fail("value " + actual + " is outside [" + low + "," + high + "]"); 1064 } 1065 } 1066 1067 private static void assertUnique(LinkedHashSet<Long> seen, Long value) { 1068 if (!seen.add(value)) { 1069 fail("found duplicate time " + value + " in series " + seen.toString()); 1070 } 1071 } 1072 1073 private static void assertNotificationType(int expected, String actualTag) { 1074 assertEquals("notification type mismatch for '" + actualTag +"'", 1075 Integer.toString(expected), actualTag.substring(actualTag.lastIndexOf(':') + 1)); 1076 } 1077 1078 private void assertUidPolicy(int uid, int expected) { 1079 final int actual = mService.getUidPolicy(uid); 1080 if (expected != actual) { 1081 fail("Wrong policy for UID " + uid + ": expected " + uidPoliciesToString(expected) 1082 + ", actual " + uidPoliciesToString(actual)); 1083 } 1084 } 1085 1086 private void assertWhitelistUids(int... uids) { 1087 assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_ALLOW_METERED_BACKGROUND), uids); 1088 } 1089 1090 private void assertRestrictBackgroundOn() throws Exception { 1091 assertTrue("restrictBackground should be set", mService.getRestrictBackground()); 1092 } 1093 1094 private void assertRestrictBackgroundOff() throws Exception { 1095 assertFalse("restrictBackground should not be set", mService.getRestrictBackground()); 1096 } 1097 1098 private FutureIntent newRestrictBackgroundChangedFuture() { 1099 return mServiceContext 1100 .nextBroadcastIntent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED); 1101 } 1102 1103 private void assertRestrictBackgroundChangedReceived(Future<Intent> future, 1104 String expectedPackage) throws Exception { 1105 final String action = ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED; 1106 final Intent intent = future.get(5, TimeUnit.SECONDS); 1107 assertNotNull("Didn't get a " + action + "intent in 5 seconds"); 1108 assertEquals("Wrong package on " + action + " intent", expectedPackage, intent.getPackage()); 1109 } 1110 1111 // TODO: replace by Truth, Hamcrest, or a similar tool. 1112 private void assertContainsInAnyOrder(int[] actual, int...expected) { 1113 final StringBuilder errors = new StringBuilder(); 1114 if (actual.length != expected.length) { 1115 errors.append("\tsize does not match\n"); 1116 } 1117 final List<Integer> actualList = 1118 Arrays.stream(actual).boxed().collect(Collectors.<Integer>toList()); 1119 final List<Integer> expectedList = 1120 Arrays.stream(expected).boxed().collect(Collectors.<Integer>toList()); 1121 if (!actualList.containsAll(expectedList)) { 1122 errors.append("\tmissing elements on actual list\n"); 1123 } 1124 if (!expectedList.containsAll(actualList)) { 1125 errors.append("\tmissing elements on expected list\n"); 1126 } 1127 if (errors.length() > 0) { 1128 fail("assertContainsInAnyOrder(expected=" + Arrays.toString(expected) 1129 + ", actual=" + Arrays.toString(actual) +") failed: \n" + errors); 1130 } 1131 } 1132 1133 private long getElapsedRealtime() { 1134 return mElapsedRealtime; 1135 } 1136 1137 private void setCurrentTimeMillis(long currentTimeMillis) { 1138 mStartTime = currentTimeMillis; 1139 mElapsedRealtime = 0L; 1140 } 1141 1142 private long currentTimeMillis() { 1143 return mStartTime + mElapsedRealtime; 1144 } 1145 1146 private void incrementCurrentTime(long duration) { 1147 mElapsedRealtime += duration; 1148 } 1149 1150 private FutureIntent mRestrictBackgroundChanged; 1151 1152 private void setRestrictBackground(boolean flag) throws Exception { 1153 // Must set expectation, otherwise NMPS will reset value to previous one. 1154 when(mNetworkManager.setDataSaverModeEnabled(flag)).thenReturn(true); 1155 mService.setRestrictBackground(flag); 1156 // Sanity check. 1157 assertEquals("restrictBackground not set", flag, mService.getRestrictBackground()); 1158 } 1159 1160 /** 1161 * Creates a mock and registers it to {@link LocalServices}. 1162 */ 1163 private static <T> T addLocalServiceMock(Class<T> clazz) { 1164 final T mock = mock(clazz); 1165 LocalServices.addService(clazz, mock); 1166 return mock; 1167 } 1168 1169 /** 1170 * Custom Mockito answer used to verify async {@link INetworkPolicyListener} calls. 1171 * 1172 * <p>Typical usage: 1173 * <pre><code> 1174 * mPolicyListener.expect().someCallback(any()); 1175 * // do something on objects under test 1176 * mPolicyListener.waitAndVerify().someCallback(eq(expectedValue)); 1177 * </code></pre> 1178 */ 1179 final class NetworkPolicyListenerAnswer implements Answer<Void> { 1180 private CountDownLatch latch; 1181 private final INetworkPolicyListener listener; 1182 1183 NetworkPolicyListenerAnswer(NetworkPolicyManagerService service) { 1184 this.listener = mock(INetworkPolicyListener.class); 1185 // RemoteCallbackList needs a binder to use as key 1186 when(listener.asBinder()).thenReturn(new Binder()); 1187 service.registerListener(listener); 1188 } 1189 1190 @Override 1191 public Void answer(InvocationOnMock invocation) throws Throwable { 1192 Log.d(TAG,"counting down on answer: " + invocation); 1193 latch.countDown(); 1194 return null; 1195 } 1196 1197 INetworkPolicyListener expect() { 1198 assertNull("expect() called before waitAndVerify()", latch); 1199 latch = new CountDownLatch(1); 1200 return doAnswer(this).when(listener); 1201 } 1202 1203 INetworkPolicyListener waitAndVerify() { 1204 assertNotNull("waitAndVerify() called before expect()", latch); 1205 try { 1206 assertTrue("callback not called in 5 seconds", latch.await(5, TimeUnit.SECONDS)); 1207 } catch (InterruptedException e) { 1208 fail("Thread interrupted before callback called"); 1209 } finally { 1210 latch = null; 1211 } 1212 return verify(listener, atLeastOnce()); 1213 } 1214 1215 INetworkPolicyListener verifyNotCalled() { 1216 return verify(listener, never()); 1217 } 1218 1219 } 1220 1221 private void setNetpolicyXml(Context context) throws Exception { 1222 mPolicyDir = context.getFilesDir(); 1223 if (mPolicyDir.exists()) { 1224 IoUtils.deleteContents(mPolicyDir); 1225 } 1226 if (!TextUtils.isEmpty(mNetpolicyXml)) { 1227 final String assetPath = NETPOLICY_DIR + "/" + mNetpolicyXml; 1228 final File netConfigFile = new File(mPolicyDir, "netpolicy.xml"); 1229 Log.d(TAG, "Creating " + netConfigFile + " from asset " + assetPath); 1230 try (final InputStream in = context.getResources().getAssets().open(assetPath); 1231 final OutputStream out = new FileOutputStream(netConfigFile)) { 1232 Streams.copy(in, out); 1233 } 1234 } 1235 } 1236 1237 /** 1238 * Annotation used to define the relative path of the {@code netpolicy.xml} file. 1239 */ 1240 @Retention(RetentionPolicy.RUNTIME) 1241 @Target(ElementType.METHOD) 1242 public @interface NetPolicyXml { 1243 1244 public String value() default ""; 1245 1246 } 1247 1248 /** 1249 * Rule used to set {@code mNetPolicyXml} according to the {@link NetPolicyXml} annotation. 1250 */ 1251 public static class NetPolicyMethodRule implements MethodRule { 1252 1253 @Override 1254 public Statement apply(Statement base, FrameworkMethod method, Object target) { 1255 for (Annotation annotation : method.getAnnotations()) { 1256 if ((annotation instanceof NetPolicyXml)) { 1257 final String path = ((NetPolicyXml) annotation).value(); 1258 if (!path.isEmpty()) { 1259 ((NetworkPolicyManagerServiceTest) target).mNetpolicyXml = path; 1260 break; 1261 } 1262 } 1263 } 1264 return base; 1265 } 1266 } 1267} 1268