Migrate to shared MockWebServer.
[android/platform/packages/providers/DownloadProvider.git] / tests / src / com / android / providers / downloads / AbstractPublicApiTest.java
1 /*
2  * Copyright (C) 2010 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.providers.downloads;
18
19 import android.app.DownloadManager;
20 import android.database.Cursor;
21 import android.net.Uri;
22 import android.os.ParcelFileDescriptor;
23 import android.provider.Downloads;
24 import android.util.Log;
25
26 import java.io.FileInputStream;
27 import java.io.InputStream;
28 import java.net.MalformedURLException;
29 import java.net.UnknownHostException;
30
31 /**
32  * Code common to tests that use the download manager public API.
33  */
34 public abstract class AbstractPublicApiTest extends AbstractDownloadProviderFunctionalTest {
35
36     class Download {
37         final long mId;
38
39         private Download(long downloadId) {
40             this.mId = downloadId;
41         }
42
43         public int getStatus() {
44             return (int) getLongField(DownloadManager.COLUMN_STATUS);
45         }
46
47         public int getStatusIfExists() {
48             Cursor cursor = mManager.query(new DownloadManager.Query().setFilterById(mId));
49             try {
50                 if (cursor.getCount() > 0) {
51                     cursor.moveToFirst();
52                     return (int) cursor.getLong(cursor.getColumnIndexOrThrow(
53                             DownloadManager.COLUMN_STATUS));
54                 } else {
55                     // the row doesn't exist
56                     return -1;
57                 }
58             } finally {
59                 cursor.close();
60             }
61         }
62
63         String getStringField(String field) {
64             Cursor cursor = mManager.query(new DownloadManager.Query().setFilterById(mId));
65             try {
66                 assertEquals(1, cursor.getCount());
67                 cursor.moveToFirst();
68                 return cursor.getString(cursor.getColumnIndexOrThrow(field));
69             } finally {
70                 cursor.close();
71             }
72         }
73
74         long getLongField(String field) {
75             Cursor cursor = mManager.query(new DownloadManager.Query().setFilterById(mId));
76             try {
77                 assertEquals(1, cursor.getCount());
78                 cursor.moveToFirst();
79                 return cursor.getLong(cursor.getColumnIndexOrThrow(field));
80             } finally {
81                 cursor.close();
82             }
83         }
84
85         String getContents() throws Exception {
86             ParcelFileDescriptor downloadedFile = mManager.openDownloadedFile(mId);
87             assertTrue("Invalid file descriptor: " + downloadedFile,
88                        downloadedFile.getFileDescriptor().valid());
89             InputStream stream = new FileInputStream(downloadedFile.getFileDescriptor());
90             try {
91                 return readStream(stream);
92             } finally {
93                 stream.close();
94             }
95         }
96
97         void runUntilStatus(int status) throws Exception {
98             runService();
99             assertEquals(status, getStatus());
100         }
101
102         // max time to wait before giving up on the current download operation.
103         private static final int MAX_TIME_TO_WAIT_FOR_OPERATION = 5;
104         // while waiting for the above time period, sleep this long to yield to the
105         // download thread
106         private static final int TIME_TO_SLEEP = 1000;
107
108         int runUntilDone() throws InterruptedException {
109             int sleepCounter = MAX_TIME_TO_WAIT_FOR_OPERATION * 1000 / TIME_TO_SLEEP;
110             for (int i = 0; i < sleepCounter; i++) {
111                 int status = getStatusIfExists();
112                 if (status == -1 || Downloads.Impl.isStatusCompleted(getStatus())) {
113                     // row doesn't exist or the download is done
114                     return status;
115                 }
116                 // download not done yet. sleep a while and try again
117                 Thread.sleep(TIME_TO_SLEEP);
118             }
119             return 0; // failed
120         }
121
122         // waits until progress_so_far is >= (progress)%
123         boolean runUntilProgress(int progress) throws InterruptedException {
124             int sleepCounter = MAX_TIME_TO_WAIT_FOR_OPERATION * 1000 / TIME_TO_SLEEP;
125             int numBytesReceivedSoFar = 0;
126             int totalBytes = 0;
127             for (int i = 0; i < sleepCounter; i++) {
128                 Cursor cursor = mManager.query(new DownloadManager.Query().setFilterById(mId));
129                 try {
130                     assertEquals(1, cursor.getCount());
131                     cursor.moveToFirst();
132                     numBytesReceivedSoFar = cursor.getInt(
133                             cursor.getColumnIndexOrThrow(
134                                     DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
135                     totalBytes = cursor.getInt(
136                             cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
137                 } finally {
138                     cursor.close();
139                 }
140                 Log.i(LOG_TAG, "in runUntilProgress, numBytesReceivedSoFar: " +
141                         numBytesReceivedSoFar + ", totalBytes: " + totalBytes);
142                 if (totalBytes == 0) {
143                     fail("total_bytes should not be zero");
144                     return false;
145                 } else {
146                     if (numBytesReceivedSoFar * 100 / totalBytes >= progress) {
147                         // progress_so_far is >= progress%. we are done
148                         return true;
149                     }
150                 }
151                 // download not done yet. sleep a while and try again
152                 Thread.sleep(TIME_TO_SLEEP);
153             }
154             Log.i(LOG_TAG, "FAILED in runUntilProgress, numBytesReceivedSoFar: " +
155                     numBytesReceivedSoFar + ", totalBytes: " + totalBytes);
156             return false; // failed
157         }
158     }
159
160     protected static final String PACKAGE_NAME = "my.package.name";
161     protected static final String REQUEST_PATH = "/path";
162
163     protected DownloadManager mManager;
164
165     public AbstractPublicApiTest(FakeSystemFacade systemFacade) {
166         super(systemFacade);
167     }
168
169     @Override
170     protected void setUp() throws Exception {
171         super.setUp();
172         mManager = new DownloadManager(mResolver, PACKAGE_NAME);
173     }
174
175     protected DownloadManager.Request getRequest()
176             throws MalformedURLException, UnknownHostException {
177         return getRequest(getServerUri(REQUEST_PATH));
178     }
179
180     protected DownloadManager.Request getRequest(String path) {
181         return new DownloadManager.Request(Uri.parse(path));
182     }
183
184     protected Download enqueueRequest(DownloadManager.Request request) {
185         return new Download(mManager.enqueue(request));
186     }
187 }