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