Home | History | Annotate | Download | only in server
      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 
     17 package com.android.server;
     18 
     19 import static android.content.Intent.ACTION_UID_REMOVED;
     20 import static android.content.Intent.EXTRA_UID;
     21 import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
     22 import static android.net.ConnectivityManager.TYPE_MOBILE;
     23 import static android.net.ConnectivityManager.TYPE_WIFI;
     24 import static android.net.ConnectivityManager.TYPE_WIMAX;
     25 import static android.net.NetworkStats.IFACE_ALL;
     26 import static android.net.NetworkStats.SET_ALL;
     27 import static android.net.NetworkStats.SET_DEFAULT;
     28 import static android.net.NetworkStats.SET_FOREGROUND;
     29 import static android.net.NetworkStats.TAG_NONE;
     30 import static android.net.NetworkStats.UID_ALL;
     31 import static android.net.NetworkStatsHistory.FIELD_ALL;
     32 import static android.net.NetworkTemplate.buildTemplateMobileAll;
     33 import static android.net.NetworkTemplate.buildTemplateWifiWildcard;
     34 import static android.net.TrafficStats.MB_IN_BYTES;
     35 import static android.net.TrafficStats.UID_REMOVED;
     36 import static android.net.TrafficStats.UID_TETHERING;
     37 import static android.text.format.DateUtils.DAY_IN_MILLIS;
     38 import static android.text.format.DateUtils.HOUR_IN_MILLIS;
     39 import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
     40 import static android.text.format.DateUtils.WEEK_IN_MILLIS;
     41 import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_POLL;
     42 import static org.easymock.EasyMock.anyLong;
     43 import static org.easymock.EasyMock.capture;
     44 import static org.easymock.EasyMock.createMock;
     45 import static org.easymock.EasyMock.eq;
     46 import static org.easymock.EasyMock.expect;
     47 import static org.easymock.EasyMock.expectLastCall;
     48 import static org.easymock.EasyMock.isA;
     49 
     50 import android.app.AlarmManager;
     51 import android.app.IAlarmManager;
     52 import android.app.PendingIntent;
     53 import android.content.Intent;
     54 import android.net.IConnectivityManager;
     55 import android.net.INetworkManagementEventObserver;
     56 import android.net.INetworkStatsSession;
     57 import android.net.LinkProperties;
     58 import android.net.NetworkInfo;
     59 import android.net.NetworkInfo.DetailedState;
     60 import android.net.NetworkState;
     61 import android.net.NetworkStats;
     62 import android.net.NetworkStatsHistory;
     63 import android.net.NetworkTemplate;
     64 import android.os.INetworkManagementService;
     65 import android.os.WorkSource;
     66 import android.telephony.TelephonyManager;
     67 import android.test.AndroidTestCase;
     68 import android.test.suitebuilder.annotation.LargeTest;
     69 import android.test.suitebuilder.annotation.Suppress;
     70 import android.util.TrustedTime;
     71 
     72 import com.android.server.net.NetworkStatsService;
     73 import com.android.server.net.NetworkStatsService.NetworkStatsSettings;
     74 import com.android.server.net.NetworkStatsService.NetworkStatsSettings.Config;
     75 
     76 import libcore.io.IoUtils;
     77 
     78 import org.easymock.Capture;
     79 import org.easymock.EasyMock;
     80 
     81 import java.io.File;
     82 
     83 /**
     84  * Tests for {@link NetworkStatsService}.
     85  */
     86 @LargeTest
     87 public class NetworkStatsServiceTest extends AndroidTestCase {
     88     private static final String TAG = "NetworkStatsServiceTest";
     89 
     90     private static final String TEST_IFACE = "test0";
     91     private static final String TEST_IFACE2 = "test1";
     92     private static final long TEST_START = 1194220800000L;
     93 
     94     private static final String IMSI_1 = "310004";
     95     private static final String IMSI_2 = "310260";
     96     private static final String TEST_SSID = "AndroidAP";
     97 
     98     private static NetworkTemplate sTemplateWifi = buildTemplateWifiWildcard();
     99     private static NetworkTemplate sTemplateImsi1 = buildTemplateMobileAll(IMSI_1);
    100     private static NetworkTemplate sTemplateImsi2 = buildTemplateMobileAll(IMSI_2);
    101 
    102     private static final int UID_RED = 1001;
    103     private static final int UID_BLUE = 1002;
    104     private static final int UID_GREEN = 1003;
    105 
    106     private long mElapsedRealtime;
    107 
    108     private BroadcastInterceptingContext mServiceContext;
    109     private File mStatsDir;
    110 
    111     private INetworkManagementService mNetManager;
    112     private IAlarmManager mAlarmManager;
    113     private TrustedTime mTime;
    114     private NetworkStatsSettings mSettings;
    115     private IConnectivityManager mConnManager;
    116 
    117     private NetworkStatsService mService;
    118     private INetworkStatsSession mSession;
    119     private INetworkManagementEventObserver mNetworkObserver;
    120 
    121     @Override
    122     public void setUp() throws Exception {
    123         super.setUp();
    124 
    125         mServiceContext = new BroadcastInterceptingContext(getContext());
    126         mStatsDir = getContext().getFilesDir();
    127         if (mStatsDir.exists()) {
    128             IoUtils.deleteContents(mStatsDir);
    129         }
    130 
    131         mNetManager = createMock(INetworkManagementService.class);
    132         mAlarmManager = createMock(IAlarmManager.class);
    133         mTime = createMock(TrustedTime.class);
    134         mSettings = createMock(NetworkStatsSettings.class);
    135         mConnManager = createMock(IConnectivityManager.class);
    136 
    137         mService = new NetworkStatsService(
    138                 mServiceContext, mNetManager, mAlarmManager, mTime, mStatsDir, mSettings);
    139         mService.bindConnectivityManager(mConnManager);
    140 
    141         mElapsedRealtime = 0L;
    142 
    143         expectCurrentTime();
    144         expectDefaultSettings();
    145         expectNetworkStatsSummary(buildEmptyStats());
    146         expectNetworkStatsUidDetail(buildEmptyStats());
    147         expectSystemReady();
    148 
    149         // catch INetworkManagementEventObserver during systemReady()
    150         final Capture<INetworkManagementEventObserver> networkObserver = new Capture<
    151                 INetworkManagementEventObserver>();
    152         mNetManager.registerObserver(capture(networkObserver));
    153         expectLastCall().atLeastOnce();
    154 
    155         replay();
    156         mService.systemReady();
    157         mSession = mService.openSession();
    158         verifyAndReset();
    159 
    160         mNetworkObserver = networkObserver.getValue();
    161 
    162     }
    163 
    164     @Override
    165     public void tearDown() throws Exception {
    166         IoUtils.deleteContents(mStatsDir);
    167 
    168         mServiceContext = null;
    169         mStatsDir = null;
    170 
    171         mNetManager = null;
    172         mAlarmManager = null;
    173         mTime = null;
    174         mSettings = null;
    175         mConnManager = null;
    176 
    177         mSession.close();
    178         mService = null;
    179 
    180         super.tearDown();
    181     }
    182 
    183     public void testNetworkStatsWifi() throws Exception {
    184         // pretend that wifi network comes online; service should ask about full
    185         // network state, and poll any existing interfaces before updating.
    186         expectCurrentTime();
    187         expectDefaultSettings();
    188         expectNetworkState(buildWifiState());
    189         expectNetworkStatsSummary(buildEmptyStats());
    190         expectNetworkStatsUidDetail(buildEmptyStats());
    191         expectNetworkStatsPoll();
    192 
    193         replay();
    194         mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION_IMMEDIATE));
    195 
    196         // verify service has empty history for wifi
    197         assertNetworkTotal(sTemplateWifi, 0L, 0L, 0L, 0L, 0);
    198         verifyAndReset();
    199 
    200         // modify some number on wifi, and trigger poll event
    201         incrementCurrentTime(HOUR_IN_MILLIS);
    202         expectCurrentTime();
    203         expectDefaultSettings();
    204         expectNetworkStatsSummary(new NetworkStats(getElapsedRealtime(), 1)
    205                 .addIfaceValues(TEST_IFACE, 1024L, 1L, 2048L, 2L));
    206         expectNetworkStatsUidDetail(buildEmptyStats());
    207         expectNetworkStatsPoll();
    208 
    209         replay();
    210         mServiceContext.sendBroadcast(new Intent(ACTION_NETWORK_STATS_POLL));
    211 
    212         // verify service recorded history
    213         assertNetworkTotal(sTemplateWifi, 1024L, 1L, 2048L, 2L, 0);
    214         verifyAndReset();
    215 
    216         // and bump forward again, with counters going higher. this is
    217         // important, since polling should correctly subtract last snapshot.
    218         incrementCurrentTime(DAY_IN_MILLIS);
    219         expectCurrentTime();
    220         expectDefaultSettings();
    221         expectNetworkStatsSummary(new NetworkStats(getElapsedRealtime(), 1)
    222                 .addIfaceValues(TEST_IFACE, 4096L, 4L, 8192L, 8L));
    223         expectNetworkStatsUidDetail(buildEmptyStats());
    224         expectNetworkStatsPoll();
    225 
    226         replay();
    227         mServiceContext.sendBroadcast(new Intent(ACTION_NETWORK_STATS_POLL));
    228 
    229         // verify service recorded history
    230         assertNetworkTotal(sTemplateWifi, 4096L, 4L, 8192L, 8L, 0);
    231         verifyAndReset();
    232 
    233     }
    234 
    235     public void testStatsRebootPersist() throws Exception {
    236         assertStatsFilesExist(false);
    237 
    238         // pretend that wifi network comes online; service should ask about full
    239         // network state, and poll any existing interfaces before updating.
    240         expectCurrentTime();
    241         expectDefaultSettings();
    242         expectNetworkState(buildWifiState());
    243         expectNetworkStatsSummary(buildEmptyStats());
    244         expectNetworkStatsUidDetail(buildEmptyStats());
    245         expectNetworkStatsPoll();
    246 
    247         replay();
    248         mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION_IMMEDIATE));
    249 
    250         // verify service has empty history for wifi
    251         assertNetworkTotal(sTemplateWifi, 0L, 0L, 0L, 0L, 0);
    252         verifyAndReset();
    253 
    254         // modify some number on wifi, and trigger poll event
    255         incrementCurrentTime(HOUR_IN_MILLIS);
    256         expectCurrentTime();
    257         expectDefaultSettings();
    258         expectNetworkStatsSummary(new NetworkStats(getElapsedRealtime(), 1)
    259                 .addIfaceValues(TEST_IFACE, 1024L, 8L, 2048L, 16L));
    260         expectNetworkStatsUidDetail(new NetworkStats(getElapsedRealtime(), 2)
    261                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, TAG_NONE, 512L, 4L, 256L, 2L, 0L)
    262                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, 0xFAAD, 256L, 2L, 128L, 1L, 0L)
    263                 .addValues(TEST_IFACE, UID_RED, SET_FOREGROUND, TAG_NONE, 512L, 4L, 256L, 2L, 0L)
    264                 .addValues(TEST_IFACE, UID_RED, SET_FOREGROUND, 0xFAAD, 256L, 2L, 128L, 1L, 0L)
    265                 .addValues(TEST_IFACE, UID_BLUE, SET_DEFAULT, TAG_NONE, 128L, 1L, 128L, 1L, 0L));
    266         expectNetworkStatsPoll();
    267 
    268         mService.setUidForeground(UID_RED, false);
    269         mService.incrementOperationCount(UID_RED, 0xFAAD, 4);
    270         mService.setUidForeground(UID_RED, true);
    271         mService.incrementOperationCount(UID_RED, 0xFAAD, 6);
    272 
    273         replay();
    274         mServiceContext.sendBroadcast(new Intent(ACTION_NETWORK_STATS_POLL));
    275 
    276         // verify service recorded history
    277         assertNetworkTotal(sTemplateWifi, 1024L, 8L, 2048L, 16L, 0);
    278         assertUidTotal(sTemplateWifi, UID_RED, 1024L, 8L, 512L, 4L, 10);
    279         assertUidTotal(sTemplateWifi, UID_RED, SET_DEFAULT, 512L, 4L, 256L, 2L, 4);
    280         assertUidTotal(sTemplateWifi, UID_RED, SET_FOREGROUND, 512L, 4L, 256L, 2L, 6);
    281         assertUidTotal(sTemplateWifi, UID_BLUE, 128L, 1L, 128L, 1L, 0);
    282         verifyAndReset();
    283 
    284         // graceful shutdown system, which should trigger persist of stats, and
    285         // clear any values in memory.
    286         expectCurrentTime();
    287         expectDefaultSettings();
    288         replay();
    289         mServiceContext.sendBroadcast(new Intent(Intent.ACTION_SHUTDOWN));
    290         verifyAndReset();
    291 
    292         assertStatsFilesExist(true);
    293 
    294         // boot through serviceReady() again
    295         expectCurrentTime();
    296         expectDefaultSettings();
    297         expectNetworkStatsSummary(buildEmptyStats());
    298         expectNetworkStatsUidDetail(buildEmptyStats());
    299         expectSystemReady();
    300 
    301         // catch INetworkManagementEventObserver during systemReady()
    302         final Capture<INetworkManagementEventObserver> networkObserver = new Capture<
    303                 INetworkManagementEventObserver>();
    304         mNetManager.registerObserver(capture(networkObserver));
    305         expectLastCall().atLeastOnce();
    306 
    307         replay();
    308         mService.systemReady();
    309 
    310         mNetworkObserver = networkObserver.getValue();
    311 
    312         // after systemReady(), we should have historical stats loaded again
    313         assertNetworkTotal(sTemplateWifi, 1024L, 8L, 2048L, 16L, 0);
    314         assertUidTotal(sTemplateWifi, UID_RED, 1024L, 8L, 512L, 4L, 10);
    315         assertUidTotal(sTemplateWifi, UID_RED, SET_DEFAULT, 512L, 4L, 256L, 2L, 4);
    316         assertUidTotal(sTemplateWifi, UID_RED, SET_FOREGROUND, 512L, 4L, 256L, 2L, 6);
    317         assertUidTotal(sTemplateWifi, UID_BLUE, 128L, 1L, 128L, 1L, 0);
    318         verifyAndReset();
    319 
    320     }
    321 
    322     // TODO: simulate reboot to test bucket resize
    323     @Suppress
    324     public void testStatsBucketResize() throws Exception {
    325         NetworkStatsHistory history = null;
    326 
    327         assertStatsFilesExist(false);
    328 
    329         // pretend that wifi network comes online; service should ask about full
    330         // network state, and poll any existing interfaces before updating.
    331         expectCurrentTime();
    332         expectSettings(0L, HOUR_IN_MILLIS, WEEK_IN_MILLIS);
    333         expectNetworkState(buildWifiState());
    334         expectNetworkStatsSummary(buildEmptyStats());
    335         expectNetworkStatsUidDetail(buildEmptyStats());
    336         expectNetworkStatsPoll();
    337 
    338         replay();
    339         mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION_IMMEDIATE));
    340         verifyAndReset();
    341 
    342         // modify some number on wifi, and trigger poll event
    343         incrementCurrentTime(2 * HOUR_IN_MILLIS);
    344         expectCurrentTime();
    345         expectSettings(0L, HOUR_IN_MILLIS, WEEK_IN_MILLIS);
    346         expectNetworkStatsSummary(new NetworkStats(getElapsedRealtime(), 1)
    347                 .addIfaceValues(TEST_IFACE, 512L, 4L, 512L, 4L));
    348         expectNetworkStatsUidDetail(buildEmptyStats());
    349         expectNetworkStatsPoll();
    350 
    351         replay();
    352         mServiceContext.sendBroadcast(new Intent(ACTION_NETWORK_STATS_POLL));
    353 
    354         // verify service recorded history
    355         history = mSession.getHistoryForNetwork(sTemplateWifi, FIELD_ALL);
    356         assertValues(history, Long.MIN_VALUE, Long.MAX_VALUE, 512L, 4L, 512L, 4L, 0);
    357         assertEquals(HOUR_IN_MILLIS, history.getBucketDuration());
    358         assertEquals(2, history.size());
    359         verifyAndReset();
    360 
    361         // now change bucket duration setting and trigger another poll with
    362         // exact same values, which should resize existing buckets.
    363         expectCurrentTime();
    364         expectSettings(0L, 30 * MINUTE_IN_MILLIS, WEEK_IN_MILLIS);
    365         expectNetworkStatsSummary(buildEmptyStats());
    366         expectNetworkStatsUidDetail(buildEmptyStats());
    367         expectNetworkStatsPoll();
    368 
    369         replay();
    370         mServiceContext.sendBroadcast(new Intent(ACTION_NETWORK_STATS_POLL));
    371 
    372         // verify identical stats, but spread across 4 buckets now
    373         history = mSession.getHistoryForNetwork(sTemplateWifi, FIELD_ALL);
    374         assertValues(history, Long.MIN_VALUE, Long.MAX_VALUE, 512L, 4L, 512L, 4L, 0);
    375         assertEquals(30 * MINUTE_IN_MILLIS, history.getBucketDuration());
    376         assertEquals(4, history.size());
    377         verifyAndReset();
    378 
    379     }
    380 
    381     public void testUidStatsAcrossNetworks() throws Exception {
    382         // pretend first mobile network comes online
    383         expectCurrentTime();
    384         expectDefaultSettings();
    385         expectNetworkState(buildMobile3gState(IMSI_1));
    386         expectNetworkStatsSummary(buildEmptyStats());
    387         expectNetworkStatsUidDetail(buildEmptyStats());
    388         expectNetworkStatsPoll();
    389 
    390         replay();
    391         mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION_IMMEDIATE));
    392         verifyAndReset();
    393 
    394         // create some traffic on first network
    395         incrementCurrentTime(HOUR_IN_MILLIS);
    396         expectCurrentTime();
    397         expectDefaultSettings();
    398         expectNetworkStatsSummary(new NetworkStats(getElapsedRealtime(), 1)
    399                 .addIfaceValues(TEST_IFACE, 2048L, 16L, 512L, 4L));
    400         expectNetworkStatsUidDetail(new NetworkStats(getElapsedRealtime(), 3)
    401                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, TAG_NONE, 1536L, 12L, 512L, 4L, 0L)
    402                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, 0xF00D, 512L, 4L, 512L, 4L, 0L)
    403                 .addValues(TEST_IFACE, UID_BLUE, SET_DEFAULT, TAG_NONE, 512L, 4L, 0L, 0L, 0L));
    404         expectNetworkStatsPoll();
    405 
    406         mService.incrementOperationCount(UID_RED, 0xF00D, 10);
    407 
    408         replay();
    409         mServiceContext.sendBroadcast(new Intent(ACTION_NETWORK_STATS_POLL));
    410 
    411         // verify service recorded history
    412         assertNetworkTotal(sTemplateImsi1, 2048L, 16L, 512L, 4L, 0);
    413         assertNetworkTotal(sTemplateWifi, 0L, 0L, 0L, 0L, 0);
    414         assertUidTotal(sTemplateImsi1, UID_RED, 1536L, 12L, 512L, 4L, 10);
    415         assertUidTotal(sTemplateImsi1, UID_BLUE, 512L, 4L, 0L, 0L, 0);
    416         verifyAndReset();
    417 
    418         // now switch networks; this also tests that we're okay with interfaces
    419         // disappearing, to verify we don't count backwards.
    420         incrementCurrentTime(HOUR_IN_MILLIS);
    421         expectCurrentTime();
    422         expectDefaultSettings();
    423         expectNetworkState(buildMobile3gState(IMSI_2));
    424         expectNetworkStatsSummary(new NetworkStats(getElapsedRealtime(), 1)
    425                 .addIfaceValues(TEST_IFACE, 2048L, 16L, 512L, 4L));
    426         expectNetworkStatsUidDetail(new NetworkStats(getElapsedRealtime(), 3)
    427                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, TAG_NONE, 1536L, 12L, 512L, 4L, 0L)
    428                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, 0xF00D, 512L, 4L, 512L, 4L, 0L)
    429                 .addValues(TEST_IFACE, UID_BLUE, SET_DEFAULT, TAG_NONE, 512L, 4L, 0L, 0L, 0L));
    430         expectNetworkStatsPoll();
    431 
    432         replay();
    433         mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION_IMMEDIATE));
    434         mServiceContext.sendBroadcast(new Intent(ACTION_NETWORK_STATS_POLL));
    435         verifyAndReset();
    436 
    437         // create traffic on second network
    438         incrementCurrentTime(HOUR_IN_MILLIS);
    439         expectCurrentTime();
    440         expectDefaultSettings();
    441         expectNetworkStatsSummary(new NetworkStats(getElapsedRealtime(), 1)
    442                 .addIfaceValues(TEST_IFACE, 2176L, 17L, 1536L, 12L));
    443         expectNetworkStatsUidDetail(new NetworkStats(getElapsedRealtime(), 1)
    444                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, TAG_NONE, 1536L, 12L, 512L, 4L, 0L)
    445                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, 0xF00D, 512L, 4L, 512L, 4L, 0L)
    446                 .addValues(TEST_IFACE, UID_BLUE, SET_DEFAULT, TAG_NONE, 640L, 5L, 1024L, 8L, 0L)
    447                 .addValues(TEST_IFACE, UID_BLUE, SET_DEFAULT, 0xFAAD, 128L, 1L, 1024L, 8L, 0L));
    448         expectNetworkStatsPoll();
    449 
    450         mService.incrementOperationCount(UID_BLUE, 0xFAAD, 10);
    451 
    452         replay();
    453         mServiceContext.sendBroadcast(new Intent(ACTION_NETWORK_STATS_POLL));
    454 
    455         // verify original history still intact
    456         assertNetworkTotal(sTemplateImsi1, 2048L, 16L, 512L, 4L, 0);
    457         assertUidTotal(sTemplateImsi1, UID_RED, 1536L, 12L, 512L, 4L, 10);
    458         assertUidTotal(sTemplateImsi1, UID_BLUE, 512L, 4L, 0L, 0L, 0);
    459 
    460         // and verify new history also recorded under different template, which
    461         // verifies that we didn't cross the streams.
    462         assertNetworkTotal(sTemplateImsi2, 128L, 1L, 1024L, 8L, 0);
    463         assertNetworkTotal(sTemplateWifi, 0L, 0L, 0L, 0L, 0);
    464         assertUidTotal(sTemplateImsi2, UID_BLUE, 128L, 1L, 1024L, 8L, 10);
    465         verifyAndReset();
    466 
    467     }
    468 
    469     public void testUidRemovedIsMoved() throws Exception {
    470         // pretend that network comes online
    471         expectCurrentTime();
    472         expectDefaultSettings();
    473         expectNetworkState(buildWifiState());
    474         expectNetworkStatsSummary(buildEmptyStats());
    475         expectNetworkStatsUidDetail(buildEmptyStats());
    476         expectNetworkStatsPoll();
    477 
    478         replay();
    479         mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION_IMMEDIATE));
    480         verifyAndReset();
    481 
    482         // create some traffic
    483         incrementCurrentTime(HOUR_IN_MILLIS);
    484         expectCurrentTime();
    485         expectDefaultSettings();
    486         expectNetworkStatsSummary(new NetworkStats(getElapsedRealtime(), 1)
    487                 .addIfaceValues(TEST_IFACE, 4128L, 258L, 544L, 34L));
    488         expectNetworkStatsUidDetail(new NetworkStats(getElapsedRealtime(), 1)
    489                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, TAG_NONE, 16L, 1L, 16L, 1L, 0L)
    490                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, 0xFAAD, 16L, 1L, 16L, 1L, 0L)
    491                 .addValues(TEST_IFACE, UID_BLUE, SET_DEFAULT, TAG_NONE, 4096L, 258L, 512L, 32L, 0L)
    492                 .addValues(TEST_IFACE, UID_GREEN, SET_DEFAULT, TAG_NONE, 16L, 1L, 16L, 1L, 0L));
    493         expectNetworkStatsPoll();
    494 
    495         mService.incrementOperationCount(UID_RED, 0xFAAD, 10);
    496 
    497         replay();
    498         mServiceContext.sendBroadcast(new Intent(ACTION_NETWORK_STATS_POLL));
    499 
    500         // verify service recorded history
    501         assertNetworkTotal(sTemplateWifi, 4128L, 258L, 544L, 34L, 0);
    502         assertUidTotal(sTemplateWifi, UID_RED, 16L, 1L, 16L, 1L, 10);
    503         assertUidTotal(sTemplateWifi, UID_BLUE, 4096L, 258L, 512L, 32L, 0);
    504         assertUidTotal(sTemplateWifi, UID_GREEN, 16L, 1L, 16L, 1L, 0);
    505         verifyAndReset();
    506 
    507         // now pretend two UIDs are uninstalled, which should migrate stats to
    508         // special "removed" bucket.
    509         expectCurrentTime();
    510         expectDefaultSettings();
    511         expectNetworkStatsSummary(new NetworkStats(getElapsedRealtime(), 1)
    512                 .addIfaceValues(TEST_IFACE, 4128L, 258L, 544L, 34L));
    513         expectNetworkStatsUidDetail(new NetworkStats(getElapsedRealtime(), 1)
    514                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, TAG_NONE, 16L, 1L, 16L, 1L, 0L)
    515                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, 0xFAAD, 16L, 1L, 16L, 1L, 0L)
    516                 .addValues(TEST_IFACE, UID_BLUE, SET_DEFAULT, TAG_NONE, 4096L, 258L, 512L, 32L, 0L)
    517                 .addValues(TEST_IFACE, UID_GREEN, SET_DEFAULT, TAG_NONE, 16L, 1L, 16L, 1L, 0L));
    518         expectNetworkStatsPoll();
    519 
    520         replay();
    521         final Intent intent = new Intent(ACTION_UID_REMOVED);
    522         intent.putExtra(EXTRA_UID, UID_BLUE);
    523         mServiceContext.sendBroadcast(intent);
    524         intent.putExtra(EXTRA_UID, UID_RED);
    525         mServiceContext.sendBroadcast(intent);
    526 
    527         // existing uid and total should remain unchanged; but removed UID
    528         // should be gone completely.
    529         assertNetworkTotal(sTemplateWifi, 4128L, 258L, 544L, 34L, 0);
    530         assertUidTotal(sTemplateWifi, UID_RED, 0L, 0L, 0L, 0L, 0);
    531         assertUidTotal(sTemplateWifi, UID_BLUE, 0L, 0L, 0L, 0L, 0);
    532         assertUidTotal(sTemplateWifi, UID_GREEN, 16L, 1L, 16L, 1L, 0);
    533         assertUidTotal(sTemplateWifi, UID_REMOVED, 4112L, 259L, 528L, 33L, 10);
    534         verifyAndReset();
    535 
    536     }
    537 
    538     public void testUid3g4gCombinedByTemplate() throws Exception {
    539         // pretend that network comes online
    540         expectCurrentTime();
    541         expectDefaultSettings();
    542         expectNetworkState(buildMobile3gState(IMSI_1));
    543         expectNetworkStatsSummary(buildEmptyStats());
    544         expectNetworkStatsUidDetail(buildEmptyStats());
    545         expectNetworkStatsPoll();
    546 
    547         replay();
    548         mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION_IMMEDIATE));
    549         verifyAndReset();
    550 
    551         // create some traffic
    552         incrementCurrentTime(HOUR_IN_MILLIS);
    553         expectCurrentTime();
    554         expectDefaultSettings();
    555         expectNetworkStatsSummary(buildEmptyStats());
    556         expectNetworkStatsUidDetail(new NetworkStats(getElapsedRealtime(), 1)
    557                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, TAG_NONE, 1024L, 8L, 1024L, 8L, 0L)
    558                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, 0xF00D, 512L, 4L, 512L, 4L, 0L));
    559         expectNetworkStatsPoll();
    560 
    561         mService.incrementOperationCount(UID_RED, 0xF00D, 5);
    562 
    563         replay();
    564         mServiceContext.sendBroadcast(new Intent(ACTION_NETWORK_STATS_POLL));
    565 
    566         // verify service recorded history
    567         assertUidTotal(sTemplateImsi1, UID_RED, 1024L, 8L, 1024L, 8L, 5);
    568         verifyAndReset();
    569 
    570         // now switch over to 4g network
    571         incrementCurrentTime(HOUR_IN_MILLIS);
    572         expectCurrentTime();
    573         expectDefaultSettings();
    574         expectNetworkState(buildMobile4gState(TEST_IFACE2));
    575         expectNetworkStatsSummary(buildEmptyStats());
    576         expectNetworkStatsUidDetail(new NetworkStats(getElapsedRealtime(), 1)
    577                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, TAG_NONE, 1024L, 8L, 1024L, 8L, 0L)
    578                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, 0xF00D, 512L, 4L, 512L, 4L, 0L));
    579         expectNetworkStatsPoll();
    580 
    581         replay();
    582         mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION_IMMEDIATE));
    583         mServiceContext.sendBroadcast(new Intent(ACTION_NETWORK_STATS_POLL));
    584         verifyAndReset();
    585 
    586         // create traffic on second network
    587         incrementCurrentTime(HOUR_IN_MILLIS);
    588         expectCurrentTime();
    589         expectDefaultSettings();
    590         expectNetworkStatsSummary(buildEmptyStats());
    591         expectNetworkStatsUidDetail(new NetworkStats(getElapsedRealtime(), 1)
    592                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, TAG_NONE, 1024L, 8L, 1024L, 8L, 0L)
    593                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, 0xF00D, 512L, 4L, 512L, 4L, 0L)
    594                 .addValues(TEST_IFACE2, UID_RED, SET_DEFAULT, TAG_NONE, 512L, 4L, 256L, 2L, 0L)
    595                 .addValues(TEST_IFACE2, UID_RED, SET_DEFAULT, 0xFAAD, 512L, 4L, 256L, 2L, 0L));
    596         expectNetworkStatsPoll();
    597 
    598         mService.incrementOperationCount(UID_RED, 0xFAAD, 5);
    599 
    600         replay();
    601         mServiceContext.sendBroadcast(new Intent(ACTION_NETWORK_STATS_POLL));
    602 
    603         // verify that ALL_MOBILE template combines both
    604         assertUidTotal(sTemplateImsi1, UID_RED, 1536L, 12L, 1280L, 10L, 10);
    605 
    606         verifyAndReset();
    607     }
    608 
    609     public void testSummaryForAllUid() throws Exception {
    610         // pretend that network comes online
    611         expectCurrentTime();
    612         expectDefaultSettings();
    613         expectNetworkState(buildWifiState());
    614         expectNetworkStatsSummary(buildEmptyStats());
    615         expectNetworkStatsUidDetail(buildEmptyStats());
    616         expectNetworkStatsPoll();
    617 
    618         replay();
    619         mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION_IMMEDIATE));
    620         verifyAndReset();
    621 
    622         // create some traffic for two apps
    623         incrementCurrentTime(HOUR_IN_MILLIS);
    624         expectCurrentTime();
    625         expectDefaultSettings();
    626         expectNetworkStatsSummary(buildEmptyStats());
    627         expectNetworkStatsUidDetail(new NetworkStats(getElapsedRealtime(), 1)
    628                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, TAG_NONE, 50L, 5L, 50L, 5L, 0L)
    629                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, 0xF00D, 10L, 1L, 10L, 1L, 0L)
    630                 .addValues(TEST_IFACE, UID_BLUE, SET_DEFAULT, TAG_NONE, 1024L, 8L, 512L, 4L, 0L));
    631         expectNetworkStatsPoll();
    632 
    633         mService.incrementOperationCount(UID_RED, 0xF00D, 1);
    634 
    635         replay();
    636         mServiceContext.sendBroadcast(new Intent(ACTION_NETWORK_STATS_POLL));
    637 
    638         // verify service recorded history
    639         assertUidTotal(sTemplateWifi, UID_RED, 50L, 5L, 50L, 5L, 1);
    640         assertUidTotal(sTemplateWifi, UID_BLUE, 1024L, 8L, 512L, 4L, 0);
    641         verifyAndReset();
    642 
    643         // now create more traffic in next hour, but only for one app
    644         incrementCurrentTime(HOUR_IN_MILLIS);
    645         expectCurrentTime();
    646         expectDefaultSettings();
    647         expectNetworkStatsSummary(buildEmptyStats());
    648         expectNetworkStatsUidDetail(new NetworkStats(getElapsedRealtime(), 1)
    649                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, TAG_NONE, 50L, 5L, 50L, 5L, 0L)
    650                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, 0xF00D, 10L, 1L, 10L, 1L, 0L)
    651                 .addValues(TEST_IFACE, UID_BLUE, SET_DEFAULT, TAG_NONE, 2048L, 16L, 1024L, 8L, 0L));
    652         expectNetworkStatsPoll();
    653 
    654         replay();
    655         mServiceContext.sendBroadcast(new Intent(ACTION_NETWORK_STATS_POLL));
    656 
    657         // first verify entire history present
    658         NetworkStats stats = mSession.getSummaryForAllUid(
    659                 sTemplateWifi, Long.MIN_VALUE, Long.MAX_VALUE, true);
    660         assertEquals(3, stats.size());
    661         assertValues(stats, IFACE_ALL, UID_RED, SET_DEFAULT, TAG_NONE, 50L, 5L, 50L, 5L, 1);
    662         assertValues(stats, IFACE_ALL, UID_RED, SET_DEFAULT, 0xF00D, 10L, 1L, 10L, 1L, 1);
    663         assertValues(stats, IFACE_ALL, UID_BLUE, SET_DEFAULT, TAG_NONE, 2048L, 16L, 1024L, 8L, 0);
    664 
    665         // now verify that recent history only contains one uid
    666         final long currentTime = currentTimeMillis();
    667         stats = mSession.getSummaryForAllUid(
    668                 sTemplateWifi, currentTime - HOUR_IN_MILLIS, currentTime, true);
    669         assertEquals(1, stats.size());
    670         assertValues(stats, IFACE_ALL, UID_BLUE, SET_DEFAULT, TAG_NONE, 1024L, 8L, 512L, 4L, 0);
    671 
    672         verifyAndReset();
    673     }
    674 
    675     public void testForegroundBackground() throws Exception {
    676         // pretend that network comes online
    677         expectCurrentTime();
    678         expectDefaultSettings();
    679         expectNetworkState(buildWifiState());
    680         expectNetworkStatsSummary(buildEmptyStats());
    681         expectNetworkStatsUidDetail(buildEmptyStats());
    682         expectNetworkStatsPoll();
    683 
    684         replay();
    685         mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION_IMMEDIATE));
    686         verifyAndReset();
    687 
    688         // create some initial traffic
    689         incrementCurrentTime(HOUR_IN_MILLIS);
    690         expectCurrentTime();
    691         expectDefaultSettings();
    692         expectNetworkStatsSummary(buildEmptyStats());
    693         expectNetworkStatsUidDetail(new NetworkStats(getElapsedRealtime(), 1)
    694                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, TAG_NONE, 128L, 2L, 128L, 2L, 0L)
    695                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, 0xF00D, 64L, 1L, 64L, 1L, 0L));
    696         expectNetworkStatsPoll();
    697 
    698         mService.incrementOperationCount(UID_RED, 0xF00D, 1);
    699 
    700         replay();
    701         mServiceContext.sendBroadcast(new Intent(ACTION_NETWORK_STATS_POLL));
    702 
    703         // verify service recorded history
    704         assertUidTotal(sTemplateWifi, UID_RED, 128L, 2L, 128L, 2L, 1);
    705         verifyAndReset();
    706 
    707         // now switch to foreground
    708         incrementCurrentTime(HOUR_IN_MILLIS);
    709         expectCurrentTime();
    710         expectDefaultSettings();
    711         expectNetworkStatsSummary(buildEmptyStats());
    712         expectNetworkStatsUidDetail(new NetworkStats(getElapsedRealtime(), 1)
    713                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, TAG_NONE, 128L, 2L, 128L, 2L, 0L)
    714                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, 0xF00D, 64L, 1L, 64L, 1L, 0L)
    715                 .addValues(TEST_IFACE, UID_RED, SET_FOREGROUND, TAG_NONE, 32L, 2L, 32L, 2L, 0L)
    716                 .addValues(TEST_IFACE, UID_RED, SET_FOREGROUND, 0xFAAD, 1L, 1L, 1L, 1L, 0L));
    717         expectNetworkStatsPoll();
    718 
    719         mService.setUidForeground(UID_RED, true);
    720         mService.incrementOperationCount(UID_RED, 0xFAAD, 1);
    721 
    722         replay();
    723         mServiceContext.sendBroadcast(new Intent(ACTION_NETWORK_STATS_POLL));
    724 
    725         // test that we combined correctly
    726         assertUidTotal(sTemplateWifi, UID_RED, 160L, 4L, 160L, 4L, 2);
    727 
    728         // verify entire history present
    729         final NetworkStats stats = mSession.getSummaryForAllUid(
    730                 sTemplateWifi, Long.MIN_VALUE, Long.MAX_VALUE, true);
    731         assertEquals(4, stats.size());
    732         assertValues(stats, IFACE_ALL, UID_RED, SET_DEFAULT, TAG_NONE, 128L, 2L, 128L, 2L, 1);
    733         assertValues(stats, IFACE_ALL, UID_RED, SET_DEFAULT, 0xF00D, 64L, 1L, 64L, 1L, 1);
    734         assertValues(stats, IFACE_ALL, UID_RED, SET_FOREGROUND, TAG_NONE, 32L, 2L, 32L, 2L, 1);
    735         assertValues(stats, IFACE_ALL, UID_RED, SET_FOREGROUND, 0xFAAD, 1L, 1L, 1L, 1L, 1);
    736 
    737         verifyAndReset();
    738     }
    739 
    740     public void testTethering() throws Exception {
    741         // pretend first mobile network comes online
    742         expectCurrentTime();
    743         expectDefaultSettings();
    744         expectNetworkState(buildMobile3gState(IMSI_1));
    745         expectNetworkStatsSummary(buildEmptyStats());
    746         expectNetworkStatsUidDetail(buildEmptyStats());
    747         expectNetworkStatsPoll();
    748 
    749         replay();
    750         mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION_IMMEDIATE));
    751         verifyAndReset();
    752 
    753         // create some tethering traffic
    754         incrementCurrentTime(HOUR_IN_MILLIS);
    755         expectCurrentTime();
    756         expectDefaultSettings();
    757         expectNetworkStatsSummary(new NetworkStats(getElapsedRealtime(), 1)
    758                 .addIfaceValues(TEST_IFACE, 2048L, 16L, 512L, 4L));
    759 
    760         final NetworkStats uidStats = new NetworkStats(getElapsedRealtime(), 1)
    761                 .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, TAG_NONE, 128L, 2L, 128L, 2L, 0L);
    762         final String[] tetherIfacePairs = new String[] { TEST_IFACE, "wlan0" };
    763         final NetworkStats tetherStats = new NetworkStats(getElapsedRealtime(), 1)
    764                 .addValues(TEST_IFACE, UID_TETHERING, SET_DEFAULT, TAG_NONE, 1920L, 14L, 384L, 2L, 0L);
    765 
    766         expectNetworkStatsUidDetail(uidStats, tetherIfacePairs, tetherStats);
    767         expectNetworkStatsPoll();
    768 
    769         replay();
    770         mServiceContext.sendBroadcast(new Intent(ACTION_NETWORK_STATS_POLL));
    771 
    772         // verify service recorded history
    773         assertNetworkTotal(sTemplateImsi1, 2048L, 16L, 512L, 4L, 0);
    774         assertUidTotal(sTemplateImsi1, UID_RED, 128L, 2L, 128L, 2L, 0);
    775         assertUidTotal(sTemplateImsi1, UID_TETHERING, 1920L, 14L, 384L, 2L, 0);
    776         verifyAndReset();
    777 
    778     }
    779 
    780     public void testReportXtOverDev() throws Exception {
    781         // bring mobile network online
    782         expectCurrentTime();
    783         expectDefaultSettings();
    784         expectNetworkState(buildMobile3gState(IMSI_1));
    785         expectNetworkStatsSummary(buildEmptyStats());
    786         expectNetworkStatsUidDetail(buildEmptyStats());
    787         expectNetworkStatsPoll();
    788 
    789         replay();
    790         mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION_IMMEDIATE));
    791         verifyAndReset();
    792 
    793         // create some traffic, but only for DEV, and across 1.5 buckets
    794         incrementCurrentTime(90 * MINUTE_IN_MILLIS);
    795         expectCurrentTime();
    796         expectDefaultSettings();
    797         expectNetworkStatsSummaryDev(new NetworkStats(getElapsedRealtime(), 1)
    798                 .addIfaceValues(TEST_IFACE, 6000L, 60L, 3000L, 30L));
    799         expectNetworkStatsSummaryXt(buildEmptyStats());
    800         expectNetworkStatsUidDetail(buildEmptyStats());
    801         expectNetworkStatsPoll();
    802 
    803         replay();
    804         mServiceContext.sendBroadcast(new Intent(ACTION_NETWORK_STATS_POLL));
    805 
    806         // verify service recorded history:
    807         // 4000(dev) + 2000(dev)
    808         assertNetworkTotal(sTemplateImsi1, 6000L, 60L, 3000L, 30L, 0);
    809         verifyAndReset();
    810 
    811         // create traffic on both DEV and XT, across two buckets
    812         incrementCurrentTime(2 * HOUR_IN_MILLIS);
    813         expectCurrentTime();
    814         expectDefaultSettings();
    815         expectNetworkStatsSummaryDev(new NetworkStats(getElapsedRealtime(), 1)
    816                 .addIfaceValues(TEST_IFACE, 6004L, 64L, 3004L, 34L));
    817         expectNetworkStatsSummaryXt(new NetworkStats(getElapsedRealtime(), 1)
    818                 .addIfaceValues(TEST_IFACE, 10240L, 0L, 0L, 0L));
    819         expectNetworkStatsUidDetail(buildEmptyStats());
    820         expectNetworkStatsPoll();
    821 
    822         replay();
    823         mServiceContext.sendBroadcast(new Intent(ACTION_NETWORK_STATS_POLL));
    824 
    825         // verify that we switching reporting at the first atomic XT bucket,
    826         // which should give us:
    827         // 4000(dev) + 2000(dev) + 1(dev) + 5120(xt) + 2560(xt)
    828         assertNetworkTotal(sTemplateImsi1, 13681L, 61L, 3001L, 31L, 0);
    829 
    830         // also test pure-DEV and pure-XT ranges
    831         assertNetworkTotal(sTemplateImsi1, startTimeMillis(),
    832                 startTimeMillis() + 2 * HOUR_IN_MILLIS, 6001L, 61L, 3001L, 31L, 0);
    833         assertNetworkTotal(sTemplateImsi1, startTimeMillis() + 2 * HOUR_IN_MILLIS,
    834                 startTimeMillis() + 4 * HOUR_IN_MILLIS, 7680L, 0L, 0L, 0L, 0);
    835 
    836         verifyAndReset();
    837     }
    838 
    839     private void assertNetworkTotal(NetworkTemplate template, long rxBytes, long rxPackets,
    840             long txBytes, long txPackets, int operations) throws Exception {
    841         assertNetworkTotal(template, Long.MIN_VALUE, Long.MAX_VALUE, rxBytes, rxPackets, txBytes,
    842                 txPackets, operations);
    843     }
    844 
    845     private void assertNetworkTotal(NetworkTemplate template, long start, long end, long rxBytes,
    846             long rxPackets, long txBytes, long txPackets, int operations) throws Exception {
    847         // verify history API
    848         final NetworkStatsHistory history = mSession.getHistoryForNetwork(template, FIELD_ALL);
    849         assertValues(history, start, end, rxBytes, rxPackets, txBytes, txPackets, operations);
    850 
    851         // verify summary API
    852         final NetworkStats stats = mSession.getSummaryForNetwork(template, start, end);
    853         assertValues(stats, IFACE_ALL, UID_ALL, SET_DEFAULT, TAG_NONE, rxBytes, rxPackets, txBytes,
    854                 txPackets, operations);
    855     }
    856 
    857     private void assertUidTotal(NetworkTemplate template, int uid, long rxBytes, long rxPackets,
    858             long txBytes, long txPackets, int operations) throws Exception {
    859         assertUidTotal(template, uid, SET_ALL, rxBytes, rxPackets, txBytes, txPackets, operations);
    860     }
    861 
    862     private void assertUidTotal(NetworkTemplate template, int uid, int set, long rxBytes,
    863             long rxPackets, long txBytes, long txPackets, int operations) throws Exception {
    864         // verify history API
    865         final NetworkStatsHistory history = mSession.getHistoryForUid(
    866                 template, uid, set, TAG_NONE, FIELD_ALL);
    867         assertValues(history, Long.MIN_VALUE, Long.MAX_VALUE, rxBytes, rxPackets, txBytes,
    868                 txPackets, operations);
    869 
    870         // verify summary API
    871         final NetworkStats stats = mSession.getSummaryForAllUid(
    872                 template, Long.MIN_VALUE, Long.MAX_VALUE, false);
    873         assertValues(stats, IFACE_ALL, uid, set, TAG_NONE, rxBytes, rxPackets, txBytes, txPackets,
    874                 operations);
    875     }
    876 
    877     private void expectSystemReady() throws Exception {
    878         mAlarmManager.remove(isA(PendingIntent.class));
    879         expectLastCall().anyTimes();
    880 
    881         mAlarmManager.set(eq(AlarmManager.ELAPSED_REALTIME), anyLong(), anyLong(), anyLong(),
    882                 isA(PendingIntent.class), isA(WorkSource.class),
    883                 isA(AlarmManager.AlarmClockInfo.class));
    884         expectLastCall().atLeastOnce();
    885 
    886         mNetManager.setGlobalAlert(anyLong());
    887         expectLastCall().atLeastOnce();
    888 
    889         expect(mNetManager.isBandwidthControlEnabled()).andReturn(true).atLeastOnce();
    890     }
    891 
    892     private void expectNetworkState(NetworkState... state) throws Exception {
    893         expect(mConnManager.getAllNetworkState()).andReturn(state).atLeastOnce();
    894 
    895         final LinkProperties linkProp = state.length > 0 ? state[0].linkProperties : null;
    896         expect(mConnManager.getActiveLinkProperties()).andReturn(linkProp).atLeastOnce();
    897     }
    898 
    899     private void expectNetworkStatsSummary(NetworkStats summary) throws Exception {
    900         expectNetworkStatsSummaryDev(summary);
    901         expectNetworkStatsSummaryXt(summary);
    902     }
    903 
    904     private void expectNetworkStatsSummaryDev(NetworkStats summary) throws Exception {
    905         expect(mNetManager.getNetworkStatsSummaryDev()).andReturn(summary).atLeastOnce();
    906     }
    907 
    908     private void expectNetworkStatsSummaryXt(NetworkStats summary) throws Exception {
    909         expect(mNetManager.getNetworkStatsSummaryXt()).andReturn(summary).atLeastOnce();
    910     }
    911 
    912     private void expectNetworkStatsUidDetail(NetworkStats detail) throws Exception {
    913         expectNetworkStatsUidDetail(detail, new String[0], new NetworkStats(0L, 0));
    914     }
    915 
    916     private void expectNetworkStatsUidDetail(
    917             NetworkStats detail, String[] tetherIfacePairs, NetworkStats tetherStats)
    918             throws Exception {
    919         expect(mNetManager.getNetworkStatsUidDetail(eq(UID_ALL))).andReturn(detail).atLeastOnce();
    920 
    921         // also include tethering details, since they are folded into UID
    922         expect(mNetManager.getNetworkStatsTethering())
    923                 .andReturn(tetherStats).atLeastOnce();
    924     }
    925 
    926     private void expectDefaultSettings() throws Exception {
    927         expectSettings(0L, HOUR_IN_MILLIS, WEEK_IN_MILLIS);
    928     }
    929 
    930     private void expectSettings(long persistBytes, long bucketDuration, long deleteAge)
    931             throws Exception {
    932         expect(mSettings.getPollInterval()).andReturn(HOUR_IN_MILLIS).anyTimes();
    933         expect(mSettings.getTimeCacheMaxAge()).andReturn(DAY_IN_MILLIS).anyTimes();
    934         expect(mSettings.getSampleEnabled()).andReturn(true).anyTimes();
    935 
    936         final Config config = new Config(bucketDuration, deleteAge, deleteAge);
    937         expect(mSettings.getDevConfig()).andReturn(config).anyTimes();
    938         expect(mSettings.getXtConfig()).andReturn(config).anyTimes();
    939         expect(mSettings.getUidConfig()).andReturn(config).anyTimes();
    940         expect(mSettings.getUidTagConfig()).andReturn(config).anyTimes();
    941 
    942         expect(mSettings.getGlobalAlertBytes(anyLong())).andReturn(MB_IN_BYTES).anyTimes();
    943         expect(mSettings.getDevPersistBytes(anyLong())).andReturn(MB_IN_BYTES).anyTimes();
    944         expect(mSettings.getXtPersistBytes(anyLong())).andReturn(MB_IN_BYTES).anyTimes();
    945         expect(mSettings.getUidPersistBytes(anyLong())).andReturn(MB_IN_BYTES).anyTimes();
    946         expect(mSettings.getUidTagPersistBytes(anyLong())).andReturn(MB_IN_BYTES).anyTimes();
    947     }
    948 
    949     private void expectCurrentTime() throws Exception {
    950         expect(mTime.forceRefresh()).andReturn(false).anyTimes();
    951         expect(mTime.hasCache()).andReturn(true).anyTimes();
    952         expect(mTime.currentTimeMillis()).andReturn(currentTimeMillis()).anyTimes();
    953         expect(mTime.getCacheAge()).andReturn(0L).anyTimes();
    954         expect(mTime.getCacheCertainty()).andReturn(0L).anyTimes();
    955     }
    956 
    957     private void expectNetworkStatsPoll() throws Exception {
    958         mNetManager.setGlobalAlert(anyLong());
    959         expectLastCall().anyTimes();
    960     }
    961 
    962     private void assertStatsFilesExist(boolean exist) {
    963         final File basePath = new File(mStatsDir, "netstats");
    964         if (exist) {
    965             assertTrue(basePath.list().length > 0);
    966         } else {
    967             assertTrue(basePath.list().length == 0);
    968         }
    969     }
    970 
    971     private static void assertValues(NetworkStats stats, String iface, int uid, int set,
    972             int tag, long rxBytes, long rxPackets, long txBytes, long txPackets, int operations) {
    973         final NetworkStats.Entry entry = new NetworkStats.Entry();
    974         if (set == SET_DEFAULT || set == SET_ALL) {
    975             final int i = stats.findIndex(iface, uid, SET_DEFAULT, tag);
    976             if (i != -1) {
    977                 entry.add(stats.getValues(i, null));
    978             }
    979         }
    980         if (set == SET_FOREGROUND || set == SET_ALL) {
    981             final int i = stats.findIndex(iface, uid, SET_FOREGROUND, tag);
    982             if (i != -1) {
    983                 entry.add(stats.getValues(i, null));
    984             }
    985         }
    986 
    987         assertEquals("unexpected rxBytes", rxBytes, entry.rxBytes);
    988         assertEquals("unexpected rxPackets", rxPackets, entry.rxPackets);
    989         assertEquals("unexpected txBytes", txBytes, entry.txBytes);
    990         assertEquals("unexpected txPackets", txPackets, entry.txPackets);
    991         assertEquals("unexpected operations", operations, entry.operations);
    992     }
    993 
    994     private static void assertValues(NetworkStatsHistory stats, long start, long end, long rxBytes,
    995             long rxPackets, long txBytes, long txPackets, int operations) {
    996         final NetworkStatsHistory.Entry entry = stats.getValues(start, end, null);
    997         assertEquals("unexpected rxBytes", rxBytes, entry.rxBytes);
    998         assertEquals("unexpected rxPackets", rxPackets, entry.rxPackets);
    999         assertEquals("unexpected txBytes", txBytes, entry.txBytes);
   1000         assertEquals("unexpected txPackets", txPackets, entry.txPackets);
   1001         assertEquals("unexpected operations", operations, entry.operations);
   1002     }
   1003 
   1004     private static NetworkState buildWifiState() {
   1005         final NetworkInfo info = new NetworkInfo(TYPE_WIFI, 0, null, null);
   1006         info.setDetailedState(DetailedState.CONNECTED, null, null);
   1007         final LinkProperties prop = new LinkProperties();
   1008         prop.setInterfaceName(TEST_IFACE);
   1009         return new NetworkState(info, prop, null, null, null, TEST_SSID);
   1010     }
   1011 
   1012     private static NetworkState buildMobile3gState(String subscriberId) {
   1013         final NetworkInfo info = new NetworkInfo(
   1014                 TYPE_MOBILE, TelephonyManager.NETWORK_TYPE_UMTS, null, null);
   1015         info.setDetailedState(DetailedState.CONNECTED, null, null);
   1016         final LinkProperties prop = new LinkProperties();
   1017         prop.setInterfaceName(TEST_IFACE);
   1018         return new NetworkState(info, prop, null, null, subscriberId, null);
   1019     }
   1020 
   1021     private static NetworkState buildMobile4gState(String iface) {
   1022         final NetworkInfo info = new NetworkInfo(TYPE_WIMAX, 0, null, null);
   1023         info.setDetailedState(DetailedState.CONNECTED, null, null);
   1024         final LinkProperties prop = new LinkProperties();
   1025         prop.setInterfaceName(iface);
   1026         return new NetworkState(info, prop, null, null, null, null);
   1027     }
   1028 
   1029     private NetworkStats buildEmptyStats() {
   1030         return new NetworkStats(getElapsedRealtime(), 0);
   1031     }
   1032 
   1033     private long getElapsedRealtime() {
   1034         return mElapsedRealtime;
   1035     }
   1036 
   1037     private long startTimeMillis() {
   1038         return TEST_START;
   1039     }
   1040 
   1041     private long currentTimeMillis() {
   1042         return startTimeMillis() + mElapsedRealtime;
   1043     }
   1044 
   1045     private void incrementCurrentTime(long duration) {
   1046         mElapsedRealtime += duration;
   1047     }
   1048 
   1049     private void replay() {
   1050         EasyMock.replay(mNetManager, mAlarmManager, mTime, mSettings, mConnManager);
   1051     }
   1052 
   1053     private void verifyAndReset() {
   1054         EasyMock.verify(mNetManager, mAlarmManager, mTime, mSettings, mConnManager);
   1055         EasyMock.reset(mNetManager, mAlarmManager, mTime, mSettings, mConnManager);
   1056     }
   1057 }
   1058