NetworkPolicyManagerServiceTest.java revision 3d3308d3e476f62664a9c3c31e6bc95bc879e49e
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        assertWhitelistUids(); // Sanity check.
343        final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
344        mPolicyListener.expect().onRestrictBackgroundWhitelistChanged(anyInt(), anyBoolean());
345
346        mService.addRestrictBackgroundWhitelistedUid(UID_A);
347
348        assertWhitelistUids(UID_A);
349        mPolicyListener.waitAndVerify().onRestrictBackgroundWhitelistChanged(APP_ID_A, true);
350        mPolicyListener.verifyNotCalled().onRestrictBackgroundBlacklistChanged(APP_ID_A, true);
351        if (expectIntent) {
352            assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
353        } else {
354            futureIntent.assertNotReceived();
355        }
356    }
357
358    /**
359     * Removes whitelist when restrict background is on - app should receive an intent.
360     */
361    @Test
362    @NetPolicyXml("uidA-whitelisted-restrict-background-on.xml")
363    public void testRemoveRestrictBackgroundWhitelist_restrictBackgroundOn() throws Exception {
364        assertRestrictBackgroundOn(); // Sanity check.
365        removeRestrictBackgroundWhitelist(true);
366    }
367
368    /**
369     * Removes whitelist when restrict background is off - app should not receive an intent.
370     */
371    @Test
372    @NetPolicyXml("uidA-whitelisted-restrict-background-off.xml")
373    public void testRemoveRestrictBackgroundWhitelist_restrictBackgroundOff() throws Exception {
374        assertRestrictBackgroundOff(); // Sanity check.
375        removeRestrictBackgroundWhitelist(false);
376    }
377
378    private void removeRestrictBackgroundWhitelist(boolean expectIntent) throws Exception {
379        assertWhitelistUids(UID_A); // Sanity check.
380        final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
381        mPolicyListener.expect().onRestrictBackgroundWhitelistChanged(anyInt(), anyBoolean());
382
383        mService.removeRestrictBackgroundWhitelistedUid(UID_A);
384
385        assertWhitelistUids();
386        mPolicyListener.waitAndVerify().onRestrictBackgroundWhitelistChanged(APP_ID_A, false);
387        mPolicyListener.verifyNotCalled().onRestrictBackgroundBlacklistChanged(APP_ID_A, false);
388        if (expectIntent) {
389            assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
390        } else {
391            futureIntent.assertNotReceived();
392        }
393    }
394
395    /**
396     * Adds blacklist when restrict background is on - app should receive an intent.
397     */
398    @Test
399    @NetPolicyXml("restrict-background-on.xml")
400    public void testAddRestrictBackgroundBlacklist_restrictBackgroundOn() throws Exception {
401        assertRestrictBackgroundOn(); // Sanity check.
402        addRestrictBackgroundBlacklist(true);
403    }
404
405    /**
406     * Adds blacklist when restrict background is off - app should receive an intent.
407     */
408    @Test
409    public void testAddRestrictBackgroundBlacklist_restrictBackgroundOff() throws Exception {
410        assertRestrictBackgroundOff(); // Sanity check.
411        addRestrictBackgroundBlacklist(true);
412    }
413
414    private void addRestrictBackgroundBlacklist(boolean expectIntent) throws Exception {
415        assertUidPolicy(UID_A, POLICY_NONE); // Sanity check.
416        final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
417        mPolicyListener.expect().onRestrictBackgroundBlacklistChanged(anyInt(), anyBoolean());
418
419        mService.setUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
420
421        assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
422        mPolicyListener.waitAndVerify().onRestrictBackgroundBlacklistChanged(APP_ID_A, true);
423        mPolicyListener.verifyNotCalled().onRestrictBackgroundWhitelistChanged(APP_ID_A, true);
424        if (expectIntent) {
425            assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
426        } else {
427            futureIntent.assertNotReceived();
428        }
429    }
430
431    /**
432     * Removes blacklist when restrict background is on - app should receive an intent.
433     */
434    @Test
435    @NetPolicyXml("uidA-blacklisted-restrict-background-on.xml")
436    public void testRemoveRestrictBackgroundBlacklist_restrictBackgroundOn() throws Exception {
437        assertRestrictBackgroundOn(); // Sanity check.
438        removeRestrictBackgroundBlacklist(true);
439    }
440
441    /**
442     * Removes blacklist when restrict background is off - app should receive an intent.
443     */
444    @Test
445    @NetPolicyXml("uidA-blacklisted-restrict-background-off.xml")
446    public void testRemoveRestrictBackgroundBlacklist_restrictBackgroundOff() throws Exception {
447        assertRestrictBackgroundOff(); // Sanity check.
448        removeRestrictBackgroundBlacklist(true);
449    }
450
451    private void removeRestrictBackgroundBlacklist(boolean expectIntent) throws Exception {
452        assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND); // Sanity check.
453        final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
454        mPolicyListener.expect().onRestrictBackgroundBlacklistChanged(anyInt(), anyBoolean());
455
456        mService.setUidPolicy(UID_A, POLICY_NONE);
457
458        assertUidPolicy(UID_A, POLICY_NONE);
459        mPolicyListener.waitAndVerify().onRestrictBackgroundBlacklistChanged(APP_ID_A, false);
460        mPolicyListener.verifyNotCalled().onRestrictBackgroundWhitelistChanged(APP_ID_A, false);
461        if (expectIntent) {
462            assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
463        } else {
464            futureIntent.assertNotReceived();
465        }
466    }
467
468    @NetPolicyXml("uidA-blacklisted-restrict-background-off.xml")
469    public void testBlacklistedAppIsNotNotifiedWhenRestrictBackgroundIsOn() throws Exception {
470        // Sanity checks.
471        assertRestrictBackgroundOn();
472        assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
473
474        final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
475        setRestrictBackground(true);
476        futureIntent.assertNotReceived();
477    }
478
479    @NetPolicyXml("uidA-whitelisted-restrict-background-off.xml")
480    public void testWhitelistedAppIsNotNotifiedWhenRestrictBackgroundIsOn() throws Exception {
481        // Sanity checks.
482        assertRestrictBackgroundOff();
483        assertWhitelistUids(UID_A);
484
485        final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
486        setRestrictBackground(true);
487        futureIntent.assertNotReceived();
488    }
489
490    @Test
491    @NetPolicyXml("restrict-background-lists-whitelist-format.xml")
492    public void testRestrictBackgroundLists_whitelistFormat() throws Exception {
493        restrictBackgroundListsTest();
494    }
495
496    @Test
497    @NetPolicyXml("restrict-background-lists-uid-policy-format.xml")
498    public void testRestrictBackgroundLists_uidPolicyFormat() throws Exception {
499        restrictBackgroundListsTest();
500    }
501
502    private void restrictBackgroundListsTest() throws Exception {
503        // UIds that are whitelisted.
504        assertWhitelistUids(UID_A, UID_B, UID_C);
505        assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
506        assertUidPolicy(UID_B, POLICY_ALLOW_METERED_BACKGROUND);
507        assertUidPolicy(UID_C, POLICY_ALLOW_METERED_BACKGROUND);
508
509        // UIDs that are blacklisted.
510        assertUidPolicy(UID_D, POLICY_NONE);
511        assertUidPolicy(UID_E, POLICY_REJECT_METERED_BACKGROUND);
512
513        // UIDS that have legacy policies.
514        assertUidPolicy(UID_F, 2); // POLICY_ALLOW_BACKGROUND_BATTERY_SAVE
515
516        // Remove whitelist.
517        mService.removeRestrictBackgroundWhitelistedUid(UID_A);
518        assertUidPolicy(UID_A, POLICY_NONE);
519        assertWhitelistUids(UID_B, UID_C);
520
521        // Add whitelist when blacklisted.
522        mService.addRestrictBackgroundWhitelistedUid(UID_E);
523        assertUidPolicy(UID_E, POLICY_ALLOW_METERED_BACKGROUND);
524        assertWhitelistUids(UID_B, UID_C, UID_E);
525
526        // Add blacklist when whitelisted.
527        mService.setUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND);
528        assertUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND);
529        assertWhitelistUids(UID_C, UID_E);
530    }
531
532    /**
533     * Tests scenario where an UID had {@code restrict-background} and {@code uid-policy} tags.
534     */
535    @Test
536    @NetPolicyXml("restrict-background-lists-mixed-format.xml")
537    public void testRestrictBackgroundLists_mixedFormat() throws Exception {
538        assertWhitelistUids(UID_A, UID_C, UID_D);
539        assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
540        assertUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND);
541        assertUidPolicy(UID_C, (POLICY_ALLOW_METERED_BACKGROUND | 2));
542        assertUidPolicy(UID_D, POLICY_ALLOW_METERED_BACKGROUND);
543    }
544
545    @Test
546    @NetPolicyXml("uids-with-mixed-policies.xml")
547    public void testGetUidsWithPolicy() throws Exception {
548        assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_NONE),
549                UID_A);
550        assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND),
551                UID_B, UID_D);
552        assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_ALLOW_METERED_BACKGROUND),
553                UID_E, UID_F);
554        // Legacy (POLICY_ALLOW_BACKGROUND_BATTERY_SAVE)
555        assertContainsInAnyOrder(mService.getUidsWithPolicy(2),
556                UID_C, UID_D, UID_F);
557    }
558
559    // NOTE: testPolicyChangeTriggersListener() and testUidForeground() are too superficial, they
560    // don't check for side-effects (like calls to NetworkManagementService) neither cover all
561    // different modes (Data Saver, Battery Saver, Doze, App idle, etc...).
562    // These scenarios are extensively tested on CTS' HostsideRestrictBackgroundNetworkTests.
563
564    @Test
565    public void testPolicyChangeTriggersListener() throws Exception {
566        mPolicyListener.expect().onRestrictBackgroundBlacklistChanged(anyInt(), anyBoolean());
567
568        mService.setUidPolicy(APP_ID_A, POLICY_NONE);
569        mService.setUidPolicy(APP_ID_A, POLICY_REJECT_METERED_BACKGROUND);
570
571        mPolicyListener.waitAndVerify().onRestrictBackgroundBlacklistChanged(APP_ID_A, true);
572    }
573
574    @Test
575    public void testUidForeground() throws Exception {
576        // push all uids into background
577        mUidObserver.onUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE);
578        mUidObserver.onUidStateChanged(UID_B, ActivityManager.PROCESS_STATE_SERVICE);
579        assertFalse(mService.isUidForeground(UID_A));
580        assertFalse(mService.isUidForeground(UID_B));
581
582        // push one of the uids into foreground
583        mUidObserver.onUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_TOP);
584        assertTrue(mService.isUidForeground(UID_A));
585        assertFalse(mService.isUidForeground(UID_B));
586
587        // and swap another uid into foreground
588        mUidObserver.onUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE);
589        mUidObserver.onUidStateChanged(UID_B, ActivityManager.PROCESS_STATE_TOP);
590        assertFalse(mService.isUidForeground(UID_A));
591        assertTrue(mService.isUidForeground(UID_B));
592    }
593
594    @Test
595    public void testLastCycleBoundaryThisMonth() throws Exception {
596        // assume cycle day of "5th", which should be in same month
597        final long currentTime = parseTime("2007-11-14T00:00:00.000Z");
598        final long expectedCycle = parseTime("2007-11-05T00:00:00.000Z");
599
600        final NetworkPolicy policy = new NetworkPolicy(
601                sTemplateWifi, 5, TIMEZONE_UTC, 1024L, 1024L, false);
602        final long actualCycle = computeLastCycleBoundary(currentTime, policy);
603        assertTimeEquals(expectedCycle, actualCycle);
604    }
605
606    @Test
607    public void testLastCycleBoundaryLastMonth() throws Exception {
608        // assume cycle day of "20th", which should be in last month
609        final long currentTime = parseTime("2007-11-14T00:00:00.000Z");
610        final long expectedCycle = parseTime("2007-10-20T00:00:00.000Z");
611
612        final NetworkPolicy policy = new NetworkPolicy(
613                sTemplateWifi, 20, TIMEZONE_UTC, 1024L, 1024L, false);
614        final long actualCycle = computeLastCycleBoundary(currentTime, policy);
615        assertTimeEquals(expectedCycle, actualCycle);
616    }
617
618    @Test
619    public void testLastCycleBoundaryThisMonthFebruary() throws Exception {
620        // assume cycle day of "30th" in february; should go to january
621        final long currentTime = parseTime("2007-02-14T00:00:00.000Z");
622        final long expectedCycle = parseTime("2007-01-30T00:00:00.000Z");
623
624        final NetworkPolicy policy = new NetworkPolicy(
625                sTemplateWifi, 30, TIMEZONE_UTC, 1024L, 1024L, false);
626        final long actualCycle = computeLastCycleBoundary(currentTime, policy);
627        assertTimeEquals(expectedCycle, actualCycle);
628    }
629
630    @Test
631    public void testLastCycleBoundaryLastMonthFebruary() throws Exception {
632        // assume cycle day of "30th" in february, which should clamp
633        final long currentTime = parseTime("2007-03-14T00:00:00.000Z");
634        final long expectedCycle = parseTime("2007-02-28T23:59:59.000Z");
635
636        final NetworkPolicy policy = new NetworkPolicy(
637                sTemplateWifi, 30, TIMEZONE_UTC, 1024L, 1024L, false);
638        final long actualCycle = computeLastCycleBoundary(currentTime, policy);
639        assertTimeEquals(expectedCycle, actualCycle);
640    }
641
642    @Test
643    public void testCycleBoundaryLeapYear() throws Exception {
644        final NetworkPolicy policy = new NetworkPolicy(
645                sTemplateWifi, 29, TIMEZONE_UTC, 1024L, 1024L, false);
646
647        assertTimeEquals(parseTime("2012-01-29T00:00:00.000Z"),
648                computeNextCycleBoundary(parseTime("2012-01-14T00:00:00.000Z"), policy));
649        assertTimeEquals(parseTime("2012-02-29T00:00:00.000Z"),
650                computeNextCycleBoundary(parseTime("2012-02-14T00:00:00.000Z"), policy));
651        assertTimeEquals(parseTime("2012-02-29T00:00:00.000Z"),
652                computeLastCycleBoundary(parseTime("2012-03-14T00:00:00.000Z"), policy));
653        assertTimeEquals(parseTime("2012-03-29T00:00:00.000Z"),
654                computeNextCycleBoundary(parseTime("2012-03-14T00:00:00.000Z"), policy));
655
656        assertTimeEquals(parseTime("2007-01-29T00:00:00.000Z"),
657                computeNextCycleBoundary(parseTime("2007-01-14T00:00:00.000Z"), policy));
658        assertTimeEquals(parseTime("2007-02-28T23:59:59.000Z"),
659                computeNextCycleBoundary(parseTime("2007-02-14T00:00:00.000Z"), policy));
660        assertTimeEquals(parseTime("2007-02-28T23:59:59.000Z"),
661                computeLastCycleBoundary(parseTime("2007-03-14T00:00:00.000Z"), policy));
662        assertTimeEquals(parseTime("2007-03-29T00:00:00.000Z"),
663                computeNextCycleBoundary(parseTime("2007-03-14T00:00:00.000Z"), policy));
664    }
665
666    @Test
667    public void testNextCycleTimezoneAfterUtc() throws Exception {
668        // US/Central is UTC-6
669        final NetworkPolicy policy = new NetworkPolicy(
670                sTemplateWifi, 10, "US/Central", 1024L, 1024L, false);
671        assertTimeEquals(parseTime("2012-01-10T06:00:00.000Z"),
672                computeNextCycleBoundary(parseTime("2012-01-05T00:00:00.000Z"), policy));
673    }
674
675    @Test
676    public void testNextCycleTimezoneBeforeUtc() throws Exception {
677        // Israel is UTC+2
678        final NetworkPolicy policy = new NetworkPolicy(
679                sTemplateWifi, 10, "Israel", 1024L, 1024L, false);
680        assertTimeEquals(parseTime("2012-01-09T22:00:00.000Z"),
681                computeNextCycleBoundary(parseTime("2012-01-05T00:00:00.000Z"), policy));
682    }
683
684    @Test
685    public void testNextCycleSane() throws Exception {
686        final NetworkPolicy policy = new NetworkPolicy(
687                sTemplateWifi, 31, TIMEZONE_UTC, WARNING_DISABLED, LIMIT_DISABLED, false);
688        final LinkedHashSet<Long> seen = new LinkedHashSet<Long>();
689
690        // walk forwards, ensuring that cycle boundaries don't get stuck
691        long currentCycle = computeNextCycleBoundary(parseTime("2011-08-01T00:00:00.000Z"), policy);
692        for (int i = 0; i < 128; i++) {
693            long nextCycle = computeNextCycleBoundary(currentCycle, policy);
694            assertEqualsFuzzy(DAY_IN_MILLIS * 30, nextCycle - currentCycle, DAY_IN_MILLIS * 3);
695            assertUnique(seen, nextCycle);
696            currentCycle = nextCycle;
697        }
698    }
699
700    @Test
701    public void testLastCycleSane() throws Exception {
702        final NetworkPolicy policy = new NetworkPolicy(
703                sTemplateWifi, 31, TIMEZONE_UTC, WARNING_DISABLED, LIMIT_DISABLED, false);
704        final LinkedHashSet<Long> seen = new LinkedHashSet<Long>();
705
706        // walk backwards, ensuring that cycle boundaries look sane
707        long currentCycle = computeLastCycleBoundary(parseTime("2011-08-04T00:00:00.000Z"), policy);
708        for (int i = 0; i < 128; i++) {
709            long lastCycle = computeLastCycleBoundary(currentCycle, policy);
710            assertEqualsFuzzy(DAY_IN_MILLIS * 30, currentCycle - lastCycle, DAY_IN_MILLIS * 3);
711            assertUnique(seen, lastCycle);
712            currentCycle = lastCycle;
713        }
714    }
715
716    @Test
717    public void testCycleTodayJanuary() throws Exception {
718        final NetworkPolicy policy = new NetworkPolicy(
719                sTemplateWifi, 14, "US/Pacific", 1024L, 1024L, false);
720
721        assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
722                computeNextCycleBoundary(parseTime("2013-01-13T23:59:59.000-08:00"), policy));
723        assertTimeEquals(parseTime("2013-02-14T00:00:00.000-08:00"),
724                computeNextCycleBoundary(parseTime("2013-01-14T00:00:01.000-08:00"), policy));
725        assertTimeEquals(parseTime("2013-02-14T00:00:00.000-08:00"),
726                computeNextCycleBoundary(parseTime("2013-01-14T15:11:00.000-08:00"), policy));
727
728        assertTimeEquals(parseTime("2012-12-14T00:00:00.000-08:00"),
729                computeLastCycleBoundary(parseTime("2013-01-13T23:59:59.000-08:00"), policy));
730        assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
731                computeLastCycleBoundary(parseTime("2013-01-14T00:00:01.000-08:00"), policy));
732        assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
733                computeLastCycleBoundary(parseTime("2013-01-14T15:11:00.000-08:00"), policy));
734    }
735
736    @Test
737    public void testLastCycleBoundaryDST() throws Exception {
738        final long currentTime = parseTime("1989-01-02T07:30:00.000");
739        final long expectedCycle = parseTime("1988-12-03T02:00:00.000Z");
740
741        final NetworkPolicy policy = new NetworkPolicy(
742                sTemplateWifi, 3, "America/Argentina/Buenos_Aires", 1024L, 1024L, false);
743        final long actualCycle = computeLastCycleBoundary(currentTime, policy);
744        assertTimeEquals(expectedCycle, actualCycle);
745    }
746
747    @Test
748    public void testNetworkPolicyAppliedCycleLastMonth() throws Exception {
749        NetworkState[] state = null;
750        NetworkStats stats = null;
751
752        final long TIME_FEB_15 = 1171497600000L;
753        final long TIME_MAR_10 = 1173484800000L;
754        final int CYCLE_DAY = 15;
755
756        setCurrentTimeMillis(TIME_MAR_10);
757
758        // first, pretend that wifi network comes online. no policy active,
759        // which means we shouldn't push limit to interface.
760        state = new NetworkState[] { buildWifi() };
761        when(mConnManager.getAllNetworkState()).thenReturn(state);
762        expectCurrentTime();
763
764        mPolicyListener.expect().onMeteredIfacesChanged(any());
765        mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION));
766        mPolicyListener.waitAndVerify().onMeteredIfacesChanged(any());
767
768        // now change cycle to be on 15th, and test in early march, to verify we
769        // pick cycle day in previous month.
770        when(mConnManager.getAllNetworkState()).thenReturn(state);
771        expectCurrentTime();
772
773        // pretend that 512 bytes total have happened
774        stats = new NetworkStats(getElapsedRealtime(), 1)
775                .addIfaceValues(TEST_IFACE, 256L, 2L, 256L, 2L);
776        when(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15, TIME_MAR_10))
777                .thenReturn(stats.getTotalBytes());
778
779        mPolicyListener.expect().onMeteredIfacesChanged(any());
780        setNetworkPolicies(new NetworkPolicy(
781                sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, 1 * MB_IN_BYTES, 2 * MB_IN_BYTES, false));
782        mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
783
784        // TODO: consider making strongly ordered mock
785        verifyPolicyDataEnable(TYPE_WIFI, true);
786        verifyRemoveInterfaceQuota(TEST_IFACE);
787        verifySetInterfaceQuota(TEST_IFACE, (2 * MB_IN_BYTES) - 512);
788    }
789
790    @Test
791    public void testOverWarningLimitNotification() throws Exception {
792        NetworkState[] state = null;
793        NetworkStats stats = null;
794        Future<String> tagFuture = null;
795
796        final long TIME_FEB_15 = 1171497600000L;
797        final long TIME_MAR_10 = 1173484800000L;
798        final int CYCLE_DAY = 15;
799
800        setCurrentTimeMillis(TIME_MAR_10);
801
802        // assign wifi policy
803        state = new NetworkState[] {};
804        stats = new NetworkStats(getElapsedRealtime(), 1)
805                .addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L);
806
807        {
808            expectCurrentTime();
809            when(mConnManager.getAllNetworkState()).thenReturn(state);
810            when(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15,
811                    currentTimeMillis())).thenReturn(stats.getTotalBytes());
812
813            mPolicyListener.expect().onMeteredIfacesChanged(any());
814            setNetworkPolicies(new NetworkPolicy(sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, 1
815                    * MB_IN_BYTES, 2 * MB_IN_BYTES, false));
816            mPolicyListener.waitAndVerify().onMeteredIfacesChanged(any());
817            verifyPolicyDataEnable(TYPE_WIFI, true);
818        }
819
820        // bring up wifi network
821        incrementCurrentTime(MINUTE_IN_MILLIS);
822        state = new NetworkState[] { buildWifi() };
823        stats = new NetworkStats(getElapsedRealtime(), 1)
824                .addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L);
825
826        {
827            expectCurrentTime();
828            when(mConnManager.getAllNetworkState()).thenReturn(state);
829            when(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15,
830                    currentTimeMillis())).thenReturn(stats.getTotalBytes());
831
832            mPolicyListener.expect().onMeteredIfacesChanged(any());
833            mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION));
834            mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
835
836            verifyPolicyDataEnable(TYPE_WIFI, true);
837            verifyRemoveInterfaceQuota(TEST_IFACE);
838            verifySetInterfaceQuota(TEST_IFACE, 2 * MB_IN_BYTES);
839        }
840
841        // go over warning, which should kick notification
842        incrementCurrentTime(MINUTE_IN_MILLIS);
843        stats = new NetworkStats(getElapsedRealtime(), 1)
844                .addIfaceValues(TEST_IFACE, 1536 * KB_IN_BYTES, 15L, 0L, 0L);
845
846        {
847            expectCurrentTime();
848            when(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15,
849                    currentTimeMillis())).thenReturn(stats.getTotalBytes());
850            tagFuture = expectEnqueueNotification();
851
852            mNetworkObserver.limitReached(null, TEST_IFACE);
853
854            assertNotificationType(TYPE_WARNING, tagFuture.get());
855            verifyPolicyDataEnable(TYPE_WIFI, true);
856
857        }
858
859        // go over limit, which should kick notification and dialog
860        incrementCurrentTime(MINUTE_IN_MILLIS);
861        stats = new NetworkStats(getElapsedRealtime(), 1)
862                .addIfaceValues(TEST_IFACE, 5 * MB_IN_BYTES, 512L, 0L, 0L);
863
864        {
865            expectCurrentTime();
866            when(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15,
867                    currentTimeMillis())).thenReturn(stats.getTotalBytes());
868            tagFuture = expectEnqueueNotification();
869
870            mNetworkObserver.limitReached(null, TEST_IFACE);
871
872            assertNotificationType(TYPE_LIMIT, tagFuture.get());
873            verifyPolicyDataEnable(TYPE_WIFI, false);
874        }
875
876        // now snooze policy, which should remove quota
877        incrementCurrentTime(MINUTE_IN_MILLIS);
878
879        {
880            expectCurrentTime();
881            when(mConnManager.getAllNetworkState()).thenReturn(state);
882            when(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15,
883                    currentTimeMillis())).thenReturn(stats.getTotalBytes());
884            tagFuture = expectEnqueueNotification();
885
886            mPolicyListener.expect().onMeteredIfacesChanged(any());
887            mService.snoozeLimit(sTemplateWifi);
888            mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
889
890            assertNotificationType(TYPE_LIMIT_SNOOZED, tagFuture.get());
891            // snoozed interface still has high quota so background data is
892            // still restricted.
893            verifyRemoveInterfaceQuota(TEST_IFACE);
894            verifySetInterfaceQuota(TEST_IFACE, Long.MAX_VALUE);
895            verifyPolicyDataEnable(TYPE_WIFI, true);
896        }
897    }
898
899    @Test
900    public void testMeteredNetworkWithoutLimit() throws Exception {
901        NetworkState[] state = null;
902        NetworkStats stats = null;
903
904        final long TIME_FEB_15 = 1171497600000L;
905        final long TIME_MAR_10 = 1173484800000L;
906        final int CYCLE_DAY = 15;
907
908        setCurrentTimeMillis(TIME_MAR_10);
909
910        // bring up wifi network with metered policy
911        state = new NetworkState[] { buildWifi() };
912        stats = new NetworkStats(getElapsedRealtime(), 1)
913                .addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L);
914
915        {
916            expectCurrentTime();
917            when(mConnManager.getAllNetworkState()).thenReturn(state);
918            when(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15,
919                    currentTimeMillis())).thenReturn(stats.getTotalBytes());
920
921            mPolicyListener.expect().onMeteredIfacesChanged(any());
922            setNetworkPolicies(new NetworkPolicy(
923                    sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, WARNING_DISABLED, LIMIT_DISABLED,
924                    true));
925            mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
926
927            verifyPolicyDataEnable(TYPE_WIFI, true);
928            verifyRemoveInterfaceQuota(TEST_IFACE);
929            verifySetInterfaceQuota(TEST_IFACE, Long.MAX_VALUE);
930        }
931    }
932
933    private static long parseTime(String time) {
934        final Time result = new Time();
935        result.parse3339(time);
936        return result.toMillis(true);
937    }
938
939    private void setNetworkPolicies(NetworkPolicy... policies) {
940        mService.setNetworkPolicies(policies);
941    }
942
943    private static NetworkState buildWifi() {
944        final NetworkInfo info = new NetworkInfo(TYPE_WIFI, 0, null, null);
945        info.setDetailedState(DetailedState.CONNECTED, null, null);
946        final LinkProperties prop = new LinkProperties();
947        prop.setInterfaceName(TEST_IFACE);
948        return new NetworkState(info, prop, null, null, null, TEST_SSID);
949    }
950
951    private void expectCurrentTime() throws Exception {
952        when(mTime.forceRefresh()).thenReturn(false);
953        when(mTime.hasCache()).thenReturn(true);
954        when(mTime.currentTimeMillis()).thenReturn(currentTimeMillis());
955        when(mTime.getCacheAge()).thenReturn(0L);
956        when(mTime.getCacheCertainty()).thenReturn(0L);
957    }
958
959    private Future<String> expectEnqueueNotification() throws Exception {
960        final FutureAnswer<String> futureAnswer = new FutureAnswer<String>(2);
961        doAnswer(futureAnswer).when(mNotifManager).enqueueNotificationWithTag(
962                anyString(), anyString(), anyString() /* capture here (index 2)*/,
963                anyInt(), isA(Notification.class), isA(int[].class), anyInt());
964        return futureAnswer;
965    }
966
967    private void expectHasInternetPermission(int uid, boolean hasIt) throws Exception {
968        when(mIpm.checkUidPermission(Manifest.permission.INTERNET, uid)).thenReturn(
969                hasIt ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED);
970    }
971
972    private void verifySetInterfaceQuota(String iface, long quotaBytes) throws Exception {
973        verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(iface, quotaBytes);
974    }
975
976    private void verifyRemoveInterfaceQuota(String iface) throws Exception {
977        verify(mNetworkManager, atLeastOnce()).removeInterfaceQuota(iface);
978    }
979
980    private Future<Void> verifyPolicyDataEnable(int type, boolean enabled) throws Exception {
981        // TODO: bring back this test
982        return null;
983    }
984
985    private void verifyAdvisePersistThreshold() throws Exception {
986        verify(mStatsService).advisePersistThreshold(anyLong());
987    }
988
989    private static class TestAbstractFuture<T> extends AbstractFuture<T> {
990        @Override
991        public T get() throws InterruptedException, ExecutionException {
992            try {
993                return get(5, TimeUnit.SECONDS);
994            } catch (TimeoutException e) {
995                throw new RuntimeException(e);
996            }
997        }
998    }
999
1000    private static class FutureAnswer<T> extends TestAbstractFuture<T> implements Answer<Void> {
1001        private final int index;
1002
1003        FutureAnswer(int index) {
1004            this.index = index;
1005        }
1006        @Override
1007        public Void answer(InvocationOnMock invocation) throws Throwable {
1008            @SuppressWarnings("unchecked")
1009            T captured = (T) invocation.getArguments()[index];
1010            set(captured);
1011            return null;
1012        }
1013    }
1014
1015    private static void assertTimeEquals(long expected, long actual) {
1016        if (expected != actual) {
1017            fail("expected " + formatTime(expected) + " but was actually " + formatTime(actual));
1018        }
1019    }
1020
1021    private static String formatTime(long millis) {
1022        final Time time = new Time(Time.TIMEZONE_UTC);
1023        time.set(millis);
1024        return time.format3339(false);
1025    }
1026
1027    private static void assertEqualsFuzzy(long expected, long actual, long fuzzy) {
1028        final long low = expected - fuzzy;
1029        final long high = expected + fuzzy;
1030        if (actual < low || actual > high) {
1031            fail("value " + actual + " is outside [" + low + "," + high + "]");
1032        }
1033    }
1034
1035    private static void assertUnique(LinkedHashSet<Long> seen, Long value) {
1036        if (!seen.add(value)) {
1037            fail("found duplicate time " + value + " in series " + seen.toString());
1038        }
1039    }
1040
1041    private static void assertNotificationType(int expected, String actualTag) {
1042        assertEquals("notification type mismatch for '" + actualTag +"'",
1043                Integer.toString(expected), actualTag.substring(actualTag.lastIndexOf(':') + 1));
1044    }
1045
1046    private void assertUidPolicy(int uid, int expected) {
1047        final int actual = mService.getUidPolicy(uid);
1048        if (expected != actual) {
1049            fail("Wrong policy for UID " + uid + ": expected " + uidPoliciesToString(expected)
1050                    + ", actual " + uidPoliciesToString(actual));
1051        }
1052    }
1053
1054    private void assertWhitelistUids(int... uids) {
1055        assertContainsInAnyOrder(mService.getRestrictBackgroundWhitelistedUids(), uids);
1056    }
1057
1058    private void assertRestrictBackgroundOn() throws Exception {
1059        assertTrue("restrictBackground should be set", mService.getRestrictBackground());
1060    }
1061
1062    private void assertRestrictBackgroundOff() throws Exception {
1063        assertFalse("restrictBackground should not be set", mService.getRestrictBackground());
1064    }
1065
1066    private FutureIntent newRestrictBackgroundChangedFuture() {
1067        return mServiceContext
1068                .nextBroadcastIntent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
1069    }
1070
1071    private void assertRestrictBackgroundChangedReceived(Future<Intent> future,
1072            String expectedPackage) throws Exception {
1073        final String action = ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED;
1074        final Intent intent = future.get(5, TimeUnit.SECONDS);
1075        assertNotNull("Didn't get a " + action + "intent in 5 seconds");
1076        assertEquals("Wrong package on " + action + " intent", expectedPackage, intent.getPackage());
1077    }
1078
1079    // TODO: replace by Truth, Hamcrest, or a similar tool.
1080    private void assertContainsInAnyOrder(int[] actual, int...expected) {
1081        final StringBuilder errors = new StringBuilder();
1082        if (actual.length != expected.length) {
1083            errors.append("\tsize does not match\n");
1084        }
1085        final List<Integer> actualList =
1086                Arrays.stream(actual).boxed().collect(Collectors.<Integer>toList());
1087        final List<Integer> expectedList =
1088                Arrays.stream(expected).boxed().collect(Collectors.<Integer>toList());
1089        if (!actualList.containsAll(expectedList)) {
1090            errors.append("\tmissing elements on actual list\n");
1091        }
1092        if (!expectedList.containsAll(actualList)) {
1093            errors.append("\tmissing elements on expected list\n");
1094        }
1095        if (errors.length() > 0) {
1096            fail("assertContainsInAnyOrder(expected=" + Arrays.toString(expected)
1097                    + ", actual=" + Arrays.toString(actual) +") failed: \n" + errors);
1098        }
1099    }
1100
1101    private long getElapsedRealtime() {
1102        return mElapsedRealtime;
1103    }
1104
1105    private void setCurrentTimeMillis(long currentTimeMillis) {
1106        mStartTime = currentTimeMillis;
1107        mElapsedRealtime = 0L;
1108    }
1109
1110    private long currentTimeMillis() {
1111        return mStartTime + mElapsedRealtime;
1112    }
1113
1114    private void incrementCurrentTime(long duration) {
1115        mElapsedRealtime += duration;
1116    }
1117
1118    private FutureIntent mRestrictBackgroundChanged;
1119
1120    private void setRestrictBackground(boolean flag) throws Exception {
1121        // Must set expectation, otherwise NMPS will reset value to previous one.
1122        when(mNetworkManager.setDataSaverModeEnabled(flag)).thenReturn(true);
1123        mService.setRestrictBackground(flag);
1124        // Sanity check.
1125        assertEquals("restrictBackground not set", flag, mService.getRestrictBackground());
1126    }
1127
1128    /**
1129     * Creates a mock and registers it to {@link LocalServices}.
1130     */
1131    private static <T> T addLocalServiceMock(Class<T> clazz) {
1132        final T mock = mock(clazz);
1133        LocalServices.addService(clazz, mock);
1134        return mock;
1135    }
1136
1137    /**
1138     * Custom Mockito answer used to verify async {@link INetworkPolicyListener} calls.
1139     *
1140     * <p>Typical usage:
1141     * <pre><code>
1142     *    mPolicyListener.expect().someCallback(any());
1143     *    // do something on objects under test
1144     *    mPolicyListener.waitAndVerify().someCallback(eq(expectedValue));
1145     * </code></pre>
1146     */
1147    final class NetworkPolicyListenerAnswer implements Answer<Void> {
1148        private CountDownLatch latch;
1149        private final INetworkPolicyListener listener;
1150
1151        NetworkPolicyListenerAnswer(NetworkPolicyManagerService service) {
1152            this.listener = mock(INetworkPolicyListener.class);
1153            // RemoteCallbackList needs a binder to use as key
1154            when(listener.asBinder()).thenReturn(new Binder());
1155            service.registerListener(listener);
1156        }
1157
1158        @Override
1159        public Void answer(InvocationOnMock invocation) throws Throwable {
1160            Log.d(TAG,"counting down on answer: " + invocation);
1161            latch.countDown();
1162            return null;
1163        }
1164
1165        INetworkPolicyListener expect() {
1166            assertNull("expect() called before waitAndVerify()", latch);
1167            latch = new CountDownLatch(1);
1168            return doAnswer(this).when(listener);
1169        }
1170
1171        INetworkPolicyListener waitAndVerify() {
1172            assertNotNull("waitAndVerify() called before expect()", latch);
1173            try {
1174                assertTrue("callback not called in 5 seconds", latch.await(5, TimeUnit.SECONDS));
1175            } catch (InterruptedException e) {
1176                fail("Thread interrupted before callback called");
1177            } finally {
1178                latch = null;
1179            }
1180            return verify(listener, atLeastOnce());
1181        }
1182
1183        INetworkPolicyListener verifyNotCalled() {
1184            return verify(listener, never());
1185        }
1186
1187    }
1188
1189    private void setNetpolicyXml(Context context) throws Exception {
1190        mPolicyDir = context.getFilesDir();
1191        if (mPolicyDir.exists()) {
1192            IoUtils.deleteContents(mPolicyDir);
1193        }
1194        if (!TextUtils.isEmpty(mNetpolicyXml)) {
1195            final String assetPath = NETPOLICY_DIR + "/" + mNetpolicyXml;
1196            final File netConfigFile = new File(mPolicyDir, "netpolicy.xml");
1197            Log.d(TAG, "Creating " + netConfigFile + " from asset " + assetPath);
1198            try (final InputStream in = context.getResources().getAssets().open(assetPath);
1199                    final OutputStream out = new FileOutputStream(netConfigFile)) {
1200                Streams.copy(in, out);
1201            }
1202        }
1203    }
1204
1205    /**
1206     * Annotation used to define the relative path of the {@code netpolicy.xml} file.
1207     */
1208    @Retention(RetentionPolicy.RUNTIME)
1209    @Target(ElementType.METHOD)
1210    public @interface NetPolicyXml {
1211
1212        public String value() default "";
1213
1214    }
1215
1216    /**
1217     * Rule used to set {@code mNetPolicyXml} according to the {@link NetPolicyXml} annotation.
1218     */
1219    public static class NetPolicyMethodRule implements MethodRule {
1220
1221        @Override
1222        public Statement apply(Statement base, FrameworkMethod method, Object target) {
1223            for (Annotation annotation : method.getAnnotations()) {
1224                if ((annotation instanceof NetPolicyXml)) {
1225                    final String path = ((NetPolicyXml) annotation).value();
1226                    if (!path.isEmpty()) {
1227                        ((NetworkPolicyManagerServiceTest) target).mNetpolicyXml = path;
1228                        break;
1229                    }
1230                }
1231            }
1232            return base;
1233        }
1234    }
1235}
1236