FileDocCategorySizeDatePackage
BandwidthTest.javaAPI DocAndroid 5.1 API13952Thu Mar 12 22:22:12 GMT 2015com.android.bandwidthtest

BandwidthTest

public class BandwidthTest extends android.test.InstrumentationTestCase
Test that downloads files from a test server and reports the bandwidth metrics collected.

Fields Summary
private static final String
LOG_TAG
private static final String
PROF_LABEL
private static final String
PROC_LABEL
private static final int
INSTRUMENTATION_IN_PROGRESS
private static final String
BASE_DIR
private static final String
TMP_FILENAME
private final int
FILE_SIZE
private android.content.Context
mContext
private com.android.bandwidthtest.util.ConnectionUtil
mConnectionUtil
private android.telephony.TelephonyManager
mTManager
private int
mUid
private String
mSsid
private String
mTestServer
private String
mDeviceId
private BandwidthTestRunner
mRunner
Constructors Summary
Methods Summary
public voidaddStatsToResults(java.lang.String label, android.net.NetworkStats stats, android.os.Bundle results, int uid)
Output the {@link NetworkStats} to Instrumentation out.

param
label to attach to this given stats.
param
stats {@link NetworkStats} to add.
param
results {@link Bundle} to be added to.
param
uid for which to report the results.

        if (results == null || results.isEmpty()) {
            Log.e(LOG_TAG, "Empty bundle provided.");
            return;
        }
        Entry totalStats = null;
        for (int i = 0; i < stats.size(); ++i) {
            Entry statsEntry = stats.getValues(i, null);
            // We are only interested in the all inclusive stats.
            if (statsEntry.tag != 0) {
                continue;
            }
            // skip stats for other uids
            if (statsEntry.uid != uid) {
                continue;
            }
            if (totalStats == null || statsEntry.set == NetworkStats.SET_ALL) {
                totalStats = statsEntry;
            } else {
                totalStats.rxBytes += statsEntry.rxBytes;
                totalStats.txBytes += statsEntry.txBytes;
            }
        }
        // Output merged stats to bundle.
        results.putInt(label + "uid", totalStats.uid);
        results.putLong(label + "tx", totalStats.txBytes);
        results.putLong(label + "rx", totalStats.rxBytes);
    
private booleancleanUpFile(java.io.File file)
Remove file if it exists.

param
file {@link File} to delete.
return
true if successfully deleted the file.

        if (file.exists()) {
            return file.delete();
        }
        return true;
    
protected voiddownloadFile()
Helper method that downloads a file using http connection from a test server and reports the data usage stats to instrumentation out.

        NetworkStats pre_test_stats = fetchDataFromProc(mUid);
        String ts = Long.toString(System.currentTimeMillis());

        String targetUrl = BandwidthTestUtil.buildDownloadUrl(
                mTestServer, FILE_SIZE, mDeviceId, ts);
        TrafficStats.startDataProfiling(mContext);
        File tmpSaveFile = new File(BASE_DIR + File.separator + TMP_FILENAME);
        assertTrue(BandwidthTestUtil.DownloadFromUrl(targetUrl, tmpSaveFile));
        NetworkStats prof_stats = TrafficStats.stopDataProfiling(mContext);
        Log.d(LOG_TAG, prof_stats.toString());

        NetworkStats post_test_stats = fetchDataFromProc(mUid);
        NetworkStats proc_stats = post_test_stats.subtract(pre_test_stats);

        // Output measurements to instrumentation out, so that it can be compared to that of
        // the server.
        Bundle results = new Bundle();
        results.putString("device_id", mDeviceId);
        results.putString("timestamp", ts);
        results.putInt("size", FILE_SIZE);
        addStatsToResults(PROF_LABEL, prof_stats, results, mUid);
        addStatsToResults(PROC_LABEL, proc_stats, results, mUid);
        getInstrumentation().sendStatus(INSTRUMENTATION_IN_PROGRESS, results);

        // Clean up.
        assertTrue(cleanUpFile(tmpSaveFile));
    
protected voiddownloadFileUsingDownloadManager()
Helper method that downloads a file from a test server using the download manager and reports the stats to instrumentation out.

        // If we are using the download manager, then the data that is written to /proc/uid_stat/
        // is accounted against download manager's uid, since it uses pre-ICS API.
        int downloadManagerUid = mConnectionUtil.downloadManagerUid();
        assertTrue(downloadManagerUid >= 0);
        NetworkStats pre_test_stats = fetchDataFromProc(downloadManagerUid);
        // start profiling
        TrafficStats.startDataProfiling(mContext);
        String ts = Long.toString(System.currentTimeMillis());
        String targetUrl = BandwidthTestUtil.buildDownloadUrl(
                mTestServer, FILE_SIZE, mDeviceId, ts);
        Log.v(LOG_TAG, "Download url: " + targetUrl);
        File tmpSaveFile = new File(BASE_DIR + File.separator + TMP_FILENAME);
        assertTrue(mConnectionUtil.startDownloadAndWait(targetUrl, 500000));
        NetworkStats prof_stats = TrafficStats.stopDataProfiling(mContext);
        NetworkStats post_test_stats = fetchDataFromProc(downloadManagerUid);
        NetworkStats proc_stats = post_test_stats.subtract(pre_test_stats);
        Log.d(LOG_TAG, prof_stats.toString());
        // Output measurements to instrumentation out, so that it can be compared to that of
        // the server.
        Bundle results = new Bundle();
        results.putString("device_id", mDeviceId);
        results.putString("timestamp", ts);
        results.putInt("size", FILE_SIZE);
        addStatsToResults(PROF_LABEL, prof_stats, results, mUid);
        // remember to use download manager uid for proc stats
        addStatsToResults(PROC_LABEL, proc_stats, results, downloadManagerUid);
        getInstrumentation().sendStatus(INSTRUMENTATION_IN_PROGRESS, results);

        // Clean up.
        assertTrue(cleanUpFile(tmpSaveFile));
    
public android.net.NetworkStatsfetchDataFromProc(int uid)
Fetch network data from /proc/uid_stat/uid

return
populated {@link NetworkStats}

        String root_filepath = "/proc/uid_stat/" + uid + "/";
        File rcv_stat = new File (root_filepath + "tcp_rcv");
        int rx = BandwidthTestUtil.parseIntValueFromFile(rcv_stat);
        File snd_stat = new File (root_filepath + "tcp_snd");
        int tx = BandwidthTestUtil.parseIntValueFromFile(snd_stat);
        NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
        stats.addValues(NetworkStats.IFACE_ALL, uid, NetworkStats.SET_DEFAULT,
                NetworkStats.TAG_NONE, rx, 0, tx, 0, 0);
        return stats;
    
public booleanhasMobileData()
Helper method to make sure we are connected to mobile data.

return
true if we successfully connect to mobile data.

        assertTrue(mConnectionUtil.waitForNetworkState(ConnectivityManager.TYPE_MOBILE,
                State.CONNECTED, ConnectionUtil.LONG_TIMEOUT));
        assertTrue("Not connected to mobile", mConnectionUtil.isConnectedToMobile());
        assertFalse("Still connected to wifi.", mConnectionUtil.isConnectedToWifi());
        return mConnectionUtil.hasData();
    
public booleansetDeviceWifiAndAirplaneMode(java.lang.String ssid)
Turn on Airplane mode and connect to the wifi.

param
ssid of the wifi to connect to
return
true if we successfully connected to a given network.

        mConnectionUtil.setAirplaneMode(mContext, true);
        assertTrue(mConnectionUtil.connectToWifi(ssid));
        assertTrue(mConnectionUtil.waitForWifiState(WifiManager.WIFI_STATE_ENABLED,
                ConnectionUtil.LONG_TIMEOUT));
        assertTrue(mConnectionUtil.waitForNetworkState(ConnectivityManager.TYPE_WIFI,
                State.CONNECTED, ConnectionUtil.LONG_TIMEOUT));
        return mConnectionUtil.hasData();
    
protected voidsetUp()



    
         
        super.setUp();
        mRunner = (BandwidthTestRunner) getInstrumentation();
        mSsid = mRunner.mSsid;
        mTestServer = mRunner.mTestServer;
        mContext = mRunner.getTargetContext();
        mConnectionUtil = new ConnectionUtil(mContext);
        mConnectionUtil.initialize();
        Log.v(LOG_TAG, "Initialized mConnectionUtil");
        mUid = Process.myUid();
        mTManager = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE);
        mDeviceId = mTManager.getDeviceId();
    
protected voidtearDown()

        mConnectionUtil.cleanUp();
        super.tearDown();
    
public voidtestMobileDownload()
Ensure that downloading on mobile reports reasonable stats.

        // As part of the setup we disconnected from wifi; make sure we are connected to mobile and
        // that we have data.
        assertTrue("Do not have mobile data!", hasMobileData());
        downloadFile();
    
public voidtestMobileDownloadWithDownloadManager()
We want to make sure that if we use mobile data and the Download Manager to download stuff, accounting still goes to the app making the call and that the numbers still make sense.

        assertTrue(hasMobileData());
        downloadFileUsingDownloadManager();
    
public voidtestMobileUpload()
Ensure that uploading on wifi reports reasonable stats.

        assertTrue(hasMobileData());
        uploadFile();
    
public voidtestWifiDownload()
Ensure that downloading on wifi reports reasonable stats.

        mConnectionUtil.wifiTestInit();
        assertTrue("Could not connect to wifi!", setDeviceWifiAndAirplaneMode(mSsid));
        downloadFile();
    
public voidtestWifiDownloadWithDownloadManager()
We want to make sure that if we use wifi and the Download Manager to download stuff, accounting still goes to the app making the call and that the numbers still make sense.

        mConnectionUtil.wifiTestInit();
        assertTrue(setDeviceWifiAndAirplaneMode(mSsid));
        downloadFileUsingDownloadManager();
    
public voidtestWifiUpload()
Ensure that uploading on wifi reports reasonable stats.

        mConnectionUtil.wifiTestInit();
        assertTrue(setDeviceWifiAndAirplaneMode(mSsid));
        uploadFile();
    
protected voiduploadFile()
Helper method that downloads a test file to upload. The stats reported to instrumentation out only include upload stats.

        // Download a file from the server.
        String ts = Long.toString(System.currentTimeMillis());
        String targetUrl = BandwidthTestUtil.buildDownloadUrl(
                mTestServer, FILE_SIZE, mDeviceId, ts);
        File tmpSaveFile = new File(BASE_DIR + File.separator + TMP_FILENAME);
        assertTrue(BandwidthTestUtil.DownloadFromUrl(targetUrl, tmpSaveFile));

        ts = Long.toString(System.currentTimeMillis());
        NetworkStats pre_test_stats = fetchDataFromProc(mUid);
        TrafficStats.startDataProfiling(mContext);
        assertTrue(BandwidthTestUtil.postFileToServer(mTestServer, mDeviceId, ts, tmpSaveFile));
        NetworkStats prof_stats = TrafficStats.stopDataProfiling(mContext);
        Log.d(LOG_TAG, prof_stats.toString());
        NetworkStats post_test_stats = fetchDataFromProc(mUid);
        NetworkStats proc_stats = post_test_stats.subtract(pre_test_stats);

        // Output measurements to instrumentation out, so that it can be compared to that of
        // the server.
        Bundle results = new Bundle();
        results.putString("device_id", mDeviceId);
        results.putString("timestamp", ts);
        results.putInt("size", FILE_SIZE);
        addStatsToResults(PROF_LABEL, prof_stats, results, mUid);
        addStatsToResults(PROC_LABEL, proc_stats, results, mUid);
        getInstrumentation().sendStatus(INSTRUMENTATION_IN_PROGRESS, results);

        // Clean up.
        assertTrue(cleanUpFile(tmpSaveFile));