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