2 * Copyright (C) 2010 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.providers.downloads;
19 import static org.mockito.Mockito.mock;
21 import android.app.NotificationManager;
22 import android.content.ComponentName;
23 import android.content.ContentResolver;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.database.ContentObserver;
27 import android.database.Cursor;
28 import android.net.Uri;
29 import android.provider.Downloads;
30 import android.test.MoreAsserts;
31 import android.test.RenamingDelegatingContext;
32 import android.test.ServiceTestCase;
33 import android.test.mock.MockContentResolver;
34 import android.util.Log;
36 import com.google.mockwebserver.MockResponse;
37 import com.google.mockwebserver.MockWebServer;
38 import com.google.mockwebserver.RecordedRequest;
39 import com.google.mockwebserver.SocketPolicy;
41 import java.io.BufferedReader;
43 import java.io.IOException;
44 import java.io.InputStream;
45 import java.io.InputStreamReader;
46 import java.net.MalformedURLException;
47 import java.net.UnknownHostException;
49 public abstract class AbstractDownloadProviderFunctionalTest extends
50 ServiceTestCase<DownloadService> {
52 protected static final String LOG_TAG = "DownloadProviderFunctionalTest";
53 private static final String PROVIDER_AUTHORITY = "downloads";
54 protected static final long RETRY_DELAY_MILLIS = 61 * 1000;
56 protected static final String
57 FILE_CONTENT = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
59 private final MockitoHelper mMockitoHelper = new MockitoHelper();
61 protected MockWebServer mServer;
62 protected MockContentResolverWithNotify mResolver;
63 protected TestContext mTestContext;
64 protected FakeSystemFacade mSystemFacade;
65 protected static String STRING_1K;
67 StringBuilder buff = new StringBuilder();
68 for (int i = 0; i < 1024; i++) {
69 buff.append("a" + i % 26);
71 STRING_1K = buff.toString();
74 static class MockContentResolverWithNotify extends MockContentResolver {
75 public boolean mNotifyWasCalled = false;
77 public synchronized void resetNotified() {
78 mNotifyWasCalled = false;
82 public synchronized void notifyChange(Uri uri, ContentObserver observer,
83 boolean syncToNetwork) {
84 mNotifyWasCalled = true;
90 * Context passed to the provider and the service. Allows most methods to pass through to the
91 * real Context (this is a LargeTest), with a few exceptions, including renaming file operations
92 * to avoid file and DB conflicts (via RenamingDelegatingContext).
94 static class TestContext extends RenamingDelegatingContext {
95 private static final String FILENAME_PREFIX = "test.";
97 private ContentResolver mResolver;
98 private final NotificationManager mNotifManager;
100 boolean mHasServiceBeenStarted = false;
102 public TestContext(Context realContext) {
103 super(realContext, FILENAME_PREFIX);
104 mNotifManager = mock(NotificationManager.class);
107 public void setResolver(ContentResolver resolver) {
108 mResolver = resolver;
112 * Direct DownloadService to our test instance of DownloadProvider.
115 public ContentResolver getContentResolver() {
120 * Stub some system services, allow access to others, and block the rest.
123 public Object getSystemService(String name) {
124 if (Context.NOTIFICATION_SERVICE.equals(name)) {
125 return mNotifManager;
128 return super.getSystemService(name);
132 * Record when DownloadProvider starts DownloadService.
135 public ComponentName startService(Intent service) {
136 if (service.getComponent().getClassName().equals(DownloadService.class.getName())) {
137 mHasServiceBeenStarted = true;
138 return service.getComponent();
140 throw new UnsupportedOperationException("Unexpected service: " + service);
144 public AbstractDownloadProviderFunctionalTest(FakeSystemFacade systemFacade) {
145 super(DownloadService.class);
146 mSystemFacade = systemFacade;
150 protected void setUp() throws Exception {
152 mMockitoHelper.setUp(getClass());
154 // Since we're testing a system app, AppDataDirGuesser doesn't find our
155 // cache dir, so set it explicitly.
156 System.setProperty("dexmaker.dexcache", getContext().getCacheDir().toString());
158 final Context realContext = getContext();
159 mTestContext = new TestContext(realContext);
160 setupProviderAndResolver();
161 mTestContext.setResolver(mResolver);
162 setContext(mTestContext);
164 getService().mSystemFacade = mSystemFacade;
165 mSystemFacade.setUp();
166 assertTrue(isDatabaseEmpty()); // ensure we're not messing with real data
167 mServer = new MockWebServer();
172 protected void tearDown() throws Exception {
175 mMockitoHelper.tearDown();
179 private boolean isDatabaseEmpty() {
180 Cursor cursor = mResolver.query(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI,
181 null, null, null, null);
183 return cursor.getCount() == 0;
189 void setupProviderAndResolver() {
190 DownloadProvider provider = new DownloadProvider();
191 provider.mSystemFacade = mSystemFacade;
192 provider.attachInfo(mTestContext, null);
193 mResolver = new MockContentResolverWithNotify();
194 mResolver.addProvider(PROVIDER_AUTHORITY, provider);
198 * Remove any downloaded files and delete any lingering downloads.
200 void cleanUpDownloads() {
201 if (mResolver == null) {
204 String[] columns = new String[] {Downloads.Impl._DATA};
205 Cursor cursor = mResolver.query(Downloads.Impl.CONTENT_URI, columns, null, null, null);
207 for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
208 String filePath = cursor.getString(0);
209 if (filePath == null) continue;
210 Log.d(LOG_TAG, "Deleting " + filePath);
211 new File(filePath).delete();
216 mResolver.delete(Downloads.Impl.CONTENT_URI, null, null);
219 void enqueueResponse(MockResponse resp) {
220 mServer.enqueue(resp);
223 MockResponse buildResponse(int status, String body) {
224 return new MockResponse().setResponseCode(status).setBody(body)
225 .setHeader("Content-type", "text/plain")
226 .setSocketPolicy(SocketPolicy.DISCONNECT_AT_END);
229 MockResponse buildResponse(int status, byte[] body) {
230 return new MockResponse().setResponseCode(status).setBody(body)
231 .setHeader("Content-type", "text/plain")
232 .setSocketPolicy(SocketPolicy.DISCONNECT_AT_END);
235 MockResponse buildEmptyResponse(int status) {
236 return buildResponse(status, "");
240 * Fetch the last request received by the MockWebServer.
242 protected RecordedRequest takeRequest() throws InterruptedException {
243 RecordedRequest request = mServer.takeRequest();
244 assertNotNull("Expected request was not made", request);
248 String getServerUri(String path) throws MalformedURLException, UnknownHostException {
249 return mServer.getUrl(path).toString();
252 protected String readStream(InputStream inputStream) throws IOException {
253 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
255 char[] buffer = new char[1024];
256 int length = reader.read(buffer);
257 assertTrue("Failed to read anything from input stream", length > -1);
258 return String.valueOf(buffer, 0, length);
264 protected void assertStartsWith(String expectedPrefix, String actual) {
265 String regex = "^" + expectedPrefix + ".*";
266 MoreAsserts.assertMatchesRegex(regex, actual);