blob: be740d3ec529f79ab0bbc75b781bbde83e151f83 [file] [log] [blame]
Tsu Chiang Chuang33f86992011-07-27 15:51:49 -07001/*
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.bandwidthtest;
18
19import android.content.Context;
20import android.net.ConnectivityManager;
21import android.net.NetworkInfo.State;
22import android.net.NetworkStats;
Tsu Chiang Chuang6951b1b2011-08-17 16:21:58 -070023import android.net.NetworkStats.Entry;
Tsu Chiang Chuang33f86992011-07-27 15:51:49 -070024import android.net.TrafficStats;
25import android.net.wifi.WifiManager;
26import android.os.Bundle;
27import android.os.Environment;
28import android.os.Process;
29import android.os.SystemClock;
30import android.telephony.TelephonyManager;
31import android.test.InstrumentationTestCase;
32import android.test.suitebuilder.annotation.LargeTest;
33import android.util.Log;
34
35import com.android.bandwidthtest.util.BandwidthTestUtil;
36import com.android.bandwidthtest.util.ConnectionUtil;
37
38import java.io.File;
Tsu Chiang Chuang6951b1b2011-08-17 16:21:58 -070039import java.util.HashMap;
40import java.util.Map;
Tsu Chiang Chuang33f86992011-07-27 15:51:49 -070041
42/**
43 * Test that downloads files from a test server and reports the bandwidth metrics collected.
44 */
45public class BandwidthTest extends InstrumentationTestCase {
46
47 private static final String LOG_TAG = "BandwidthTest";
48 private final static String PROF_LABEL = "PROF_";
49 private final static String PROC_LABEL = "PROC_";
50 private final static int INSTRUMENTATION_IN_PROGRESS = 2;
51
52 private final static String BASE_DIR =
53 Environment.getExternalStorageDirectory().getAbsolutePath();
54 private final static String TMP_FILENAME = "tmp.dat";
55 // Download 10.486 * 106 bytes (+ headers) from app engine test server.
56 private final int FILE_SIZE = 10485613;
57 private Context mContext;
58 private ConnectionUtil mConnectionUtil;
59 private TelephonyManager mTManager;
60 private int mUid;
61 private String mSsid;
62 private String mTestServer;
63 private String mDeviceId;
64 private BandwidthTestRunner mRunner;
65
66
67 @Override
68 protected void setUp() throws Exception {
69 super.setUp();
70 mRunner = (BandwidthTestRunner) getInstrumentation();
71 mSsid = mRunner.mSsid;
72 mTestServer = mRunner.mTestServer;
73 mContext = mRunner.getTargetContext();
74 mConnectionUtil = new ConnectionUtil(mContext);
75 mConnectionUtil.initialize();
76 Log.v(LOG_TAG, "Initialized mConnectionUtil");
77 mUid = Process.myUid();
78 mTManager = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE);
79 mDeviceId = mTManager.getDeviceId();
80 }
81
82 @Override
83 protected void tearDown() throws Exception {
84 mConnectionUtil.cleanUp();
85 super.tearDown();
86 }
87
88 /**
89 * Ensure that downloading on wifi reports reasonable stats.
90 */
91 @LargeTest
92 public void testWifiDownload() {
93 assertTrue(setDeviceWifiAndAirplaneMode(mSsid));
94 NetworkStats pre_test_stats = fetchDataFromProc(mUid);
95 String ts = Long.toString(System.currentTimeMillis());
96
97 String targetUrl = BandwidthTestUtil.buildDownloadUrl(
98 mTestServer, FILE_SIZE, mDeviceId, ts);
99 TrafficStats.startDataProfiling(mContext);
100 File tmpSaveFile = new File(BASE_DIR + File.separator + TMP_FILENAME);
101 assertTrue(BandwidthTestUtil.DownloadFromUrl(targetUrl, tmpSaveFile));
102 NetworkStats prof_stats = TrafficStats.stopDataProfiling(mContext);
Tsu Chiang Chuang6951b1b2011-08-17 16:21:58 -0700103 Log.d(LOG_TAG, prof_stats.toString());
Tsu Chiang Chuang33f86992011-07-27 15:51:49 -0700104
105 NetworkStats post_test_stats = fetchDataFromProc(mUid);
106 NetworkStats proc_stats = post_test_stats.subtract(pre_test_stats);
107
108 // Output measurements to instrumentation out, so that it can be compared to that of
109 // the server.
110 Bundle results = new Bundle();
111 results.putString("device_id", mDeviceId);
112 results.putString("timestamp", ts);
113 results.putInt("size", FILE_SIZE);
114 AddStatsToResults(PROF_LABEL, prof_stats, results);
115 AddStatsToResults(PROC_LABEL, proc_stats, results);
116 getInstrumentation().sendStatus(INSTRUMENTATION_IN_PROGRESS, results);
117
118 // Clean up.
119 assertTrue(cleanUpFile(tmpSaveFile));
120 }
121
122 /**
123 * We want to make sure that if we use the Download Manager to download stuff,
124 * accounting still goes to the app making the call and that the numbers still make sense.
125 */
126 @LargeTest
127 public void testWifiDownloadWithDownloadManager() {
128 assertTrue(setDeviceWifiAndAirplaneMode(mSsid));
129 // If we are using the download manager, then the data that is written to /proc/uid_stat/
130 // is accounted against download manager's uid, since it uses pre-ICS API.
131 int downloadManagerUid = mConnectionUtil.downloadManagerUid();
132 assertTrue(downloadManagerUid >= 0);
133 NetworkStats pre_test_stats = fetchDataFromProc(downloadManagerUid);
134 // start profiling
135 TrafficStats.startDataProfiling(mContext);
136 String ts = Long.toString(System.currentTimeMillis());
137 String targetUrl = BandwidthTestUtil.buildDownloadUrl(
138 mTestServer, FILE_SIZE, mDeviceId, ts);
139 Log.v(LOG_TAG, "Download url: " + targetUrl);
140 File tmpSaveFile = new File(BASE_DIR + File.separator + TMP_FILENAME);
141 assertTrue(mConnectionUtil.startDownloadAndWait(targetUrl, 500000));
142 NetworkStats prof_stats = TrafficStats.stopDataProfiling(mContext);
143 NetworkStats post_test_stats = fetchDataFromProc(downloadManagerUid);
144 NetworkStats proc_stats = post_test_stats.subtract(pre_test_stats);
Tsu Chiang Chuang6951b1b2011-08-17 16:21:58 -0700145 Log.d(LOG_TAG, prof_stats.toString());
Tsu Chiang Chuang33f86992011-07-27 15:51:49 -0700146 // Output measurements to instrumentation out, so that it can be compared to that of
147 // the server.
148 Bundle results = new Bundle();
149 results.putString("device_id", mDeviceId);
150 results.putString("timestamp", ts);
151 results.putInt("size", FILE_SIZE);
152 AddStatsToResults(PROF_LABEL, prof_stats, results);
153 AddStatsToResults(PROC_LABEL, proc_stats, results);
154 getInstrumentation().sendStatus(INSTRUMENTATION_IN_PROGRESS, results);
155
156 // Clean up.
157 assertTrue(cleanUpFile(tmpSaveFile));
158 }
159
160 /**
161 * Fetch network data from /proc/uid_stat/uid
162 * @return populated {@link NetworkStats}
163 */
164 public NetworkStats fetchDataFromProc(int uid) {
165 String root_filepath = "/proc/uid_stat/" + uid + "/";
166 File rcv_stat = new File (root_filepath + "tcp_rcv");
167 int rx = BandwidthTestUtil.parseIntValueFromFile(rcv_stat);
168 File snd_stat = new File (root_filepath + "tcp_snd");
169 int tx = BandwidthTestUtil.parseIntValueFromFile(snd_stat);
170 NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700171 stats.addValues(NetworkStats.IFACE_ALL, uid, NetworkStats.SET_DEFAULT,
172 NetworkStats.TAG_NONE, rx, 0, tx, 0, 0);
Tsu Chiang Chuang33f86992011-07-27 15:51:49 -0700173 return stats;
174 }
175
176 /**
177 * Turn on Airplane mode and connect to the wifi
178 * @param ssid of the wifi to connect to
179 * @return true if we successfully connected to a given network.
180 */
181 public boolean setDeviceWifiAndAirplaneMode(String ssid) {
182 mConnectionUtil.setAirplaneMode(mContext, true);
183 assertTrue(mConnectionUtil.connectToWifi(ssid));
184 assertTrue(mConnectionUtil.waitForWifiState(WifiManager.WIFI_STATE_ENABLED,
185 ConnectionUtil.LONG_TIMEOUT));
186 return mConnectionUtil.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED,
187 ConnectionUtil.LONG_TIMEOUT);
188 }
189
190 /**
191 * Output the {@link NetworkStats} to Instrumentation out.
192 * @param label to attach to this given stats.
193 * @param stats {@link NetworkStats} to add.
194 * @param results {@link Bundle} to be added to.
195 */
196 public void AddStatsToResults(String label, NetworkStats stats, Bundle results){
197 if (results == null || results.isEmpty()) {
198 Log.e(LOG_TAG, "Empty bundle provided.");
199 return;
200 }
Tsu Chiang Chuang6951b1b2011-08-17 16:21:58 -0700201 // Merge stats across all sets.
202 Map<Integer, Entry> totalStats = new HashMap<Integer, Entry>();
Tsu Chiang Chuang33f86992011-07-27 15:51:49 -0700203 for (int i = 0; i < stats.size(); ++i) {
Tsu Chiang Chuang6951b1b2011-08-17 16:21:58 -0700204 Entry statsEntry = stats.getValues(i, null);
205 // We are only interested in the all inclusive stats.
206 if (statsEntry.tag != 0) {
207 continue;
208 }
209 Entry mapEntry = null;
210 if (totalStats.containsKey(statsEntry.uid)) {
211 mapEntry = totalStats.get(statsEntry.uid);
212 switch (statsEntry.set) {
213 case NetworkStats.SET_ALL:
214 mapEntry.rxBytes = statsEntry.rxBytes;
215 mapEntry.txBytes = statsEntry.txBytes;
216 break;
217 case NetworkStats.SET_DEFAULT:
218 case NetworkStats.SET_FOREGROUND:
219 mapEntry.rxBytes += statsEntry.rxBytes;
220 mapEntry.txBytes += statsEntry.txBytes;
221 break;
222 default:
223 Log.w(LOG_TAG, "Invalid state found in NetworkStats.");
224 }
225 } else {
226 totalStats.put(statsEntry.uid, statsEntry);
227 }
228 }
229 // Ouput merged stats to bundle.
230 for (Entry entry : totalStats.values()) {
Tsu Chiang Chuang33f86992011-07-27 15:51:49 -0700231 results.putInt(label + "uid", entry.uid);
Tsu Chiang Chuang33f86992011-07-27 15:51:49 -0700232 results.putLong(label + "tx", entry.txBytes);
233 results.putLong(label + "rx", entry.rxBytes);
234 }
235 }
236
237 /**
238 * Remove file if it exists.
239 * @param file {@link File} to delete.
240 * @return true if successfully deleted the file.
241 */
242 private boolean cleanUpFile(File file) {
243 if (file.exists()) {
244 return file.delete();
245 }
246 return true;
247 }
248}