summaryrefslogtreecommitdiffstats
path: root/tests/src/com/android/providers/downloads/DownloadProviderFunctionalTest.java
blob: dbab203c3cece74ac7312fdfc57e543a3d42bdf6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.providers.downloads;

import static android.text.format.DateUtils.SECOND_IN_MILLIS;
import static java.net.HttpURLConnection.HTTP_OK;

import android.content.ContentValues;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.Downloads;
import android.test.suitebuilder.annotation.LargeTest;

import com.google.mockwebserver.MockWebServer;
import com.google.mockwebserver.RecordedRequest;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;

/**
 * This test exercises the entire download manager working together -- it requests downloads through
 * the {@link DownloadProvider}, just like a normal client would, and runs the
 * {@link DownloadService} with start intents.  It sets up a {@link MockWebServer} running on the
 * device to serve downloads.
 */
@LargeTest
public class DownloadProviderFunctionalTest extends AbstractDownloadProviderFunctionalTest {
    private static final String TAG = "DownloadManagerFunctionalTest";

    public DownloadProviderFunctionalTest() {
        super(new FakeSystemFacade());
    }

    public void testDownloadTextFile() throws Exception {
        enqueueResponse(buildResponse(HTTP_OK, FILE_CONTENT));

        String path = "/download_manager_test_path";
        Uri downloadUri = requestDownload(path);
        assertEquals(Downloads.Impl.STATUS_PENDING, getDownloadStatus(downloadUri));
        assertTrue(mTestContext.mHasServiceBeenStarted);

        runUntilStatus(downloadUri, Downloads.Impl.STATUS_SUCCESS);
        RecordedRequest request = takeRequest();
        assertEquals("GET", request.getMethod());
        assertEquals(path, request.getPath());
        assertEquals(FILE_CONTENT, getDownloadContents(downloadUri));
        assertStartsWith(Environment.getExternalStorageDirectory().getPath(),
                         getDownloadFilename(downloadUri));
    }

    public void testDownloadToCache() throws Exception {
        enqueueResponse(buildResponse(HTTP_OK, FILE_CONTENT));

        Uri downloadUri = requestDownload("/path");
        updateDownload(downloadUri, Downloads.Impl.COLUMN_DESTINATION,
                       Integer.toString(Downloads.Impl.DESTINATION_CACHE_PARTITION));
        runUntilStatus(downloadUri, Downloads.Impl.STATUS_SUCCESS);
        assertEquals(FILE_CONTENT, getDownloadContents(downloadUri));
        assertStartsWith(getContext().getCacheDir().getAbsolutePath(),
                         getDownloadFilename(downloadUri));
    }

    public void testRoaming() throws Exception {
        enqueueResponse(buildResponse(HTTP_OK, FILE_CONTENT));
        enqueueResponse(buildResponse(HTTP_OK, FILE_CONTENT));

        mSystemFacade.mActiveNetworkType = ConnectivityManager.TYPE_MOBILE;
        mSystemFacade.mIsRoaming = true;

        // for a normal download, roaming is fine
        Uri downloadUri = requestDownload("/path");
        runUntilStatus(downloadUri, Downloads.Impl.STATUS_SUCCESS);

        // when roaming is disallowed, the download should pause...
        downloadUri = requestDownload("/path");
        updateDownload(downloadUri, Downloads.Impl.COLUMN_DESTINATION,
                       Integer.toString(Downloads.Impl.DESTINATION_CACHE_PARTITION_NOROAMING));
        runUntilStatus(downloadUri, Downloads.Impl.STATUS_WAITING_FOR_NETWORK);

        // ...and pick up when we're off roaming
        mSystemFacade.mIsRoaming = false;
        runUntilStatus(downloadUri, Downloads.Impl.STATUS_SUCCESS);
    }

    /**
     * Read a downloaded file from disk.
     */
    private String getDownloadContents(Uri downloadUri) throws Exception {
        InputStream inputStream = mResolver.openInputStream(downloadUri);
        try {
            return readStream(inputStream);
        } finally {
            inputStream.close();
        }
    }

    private void runUntilStatus(Uri downloadUri, int expected) throws Exception {
        startService(null);
        
        int actual = -1;

        final long timeout = SystemClock.elapsedRealtime() + (15 * SECOND_IN_MILLIS);
        while (SystemClock.elapsedRealtime() < timeout) {
            actual = getDownloadStatus(downloadUri);
            if (expected == actual) {
                return;
            }

            SystemClock.sleep(100);
        }

        throw new TimeoutException("Expected status " + expected + "; only reached " + actual);
    }

    protected int getDownloadStatus(Uri downloadUri) {
        return Integer.valueOf(getDownloadField(downloadUri, Downloads.Impl.COLUMN_STATUS));
    }

    private String getDownloadFilename(Uri downloadUri) {
        return getDownloadField(downloadUri, Downloads.Impl._DATA);
    }

    private String getDownloadField(Uri downloadUri, String column) {
        final String[] columns = new String[] {column};
        Cursor cursor = mResolver.query(downloadUri, columns, null, null, null);
        try {
            assertEquals(1, cursor.getCount());
            cursor.moveToFirst();
            return cursor.getString(0);
        } finally {
            cursor.close();
        }
    }

    /**
     * Request a download from the Download Manager.
     */
    private Uri requestDownload(String path) throws MalformedURLException, UnknownHostException {
        ContentValues values = new ContentValues();
        values.put(Downloads.Impl.COLUMN_URI, getServerUri(path));
        values.put(Downloads.Impl.COLUMN_DESTINATION, Downloads.Impl.DESTINATION_EXTERNAL);
        return mResolver.insert(Downloads.Impl.CONTENT_URI, values);
    }

    /**
     * Update one field of a download in the provider.
     */
    private void updateDownload(Uri downloadUri, String column, String value) {
        ContentValues values = new ContentValues();
        values.put(column, value);
        int numChanged = mResolver.update(downloadUri, values, null, null);
        assertEquals(1, numChanged);
    }
}