summaryrefslogtreecommitdiffstats
path: root/chrome/android/javatests/src/org/chromium/chrome/browser/download/DownloadManagerServiceTest.java
blob: c32a7af3a5da1855f75f29b88deb415eeff58f42 (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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.download;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.preference.PreferenceManager;
import android.test.InstrumentationTestCase;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.util.Log;
import android.util.Pair;

import org.chromium.base.test.util.AdvancedMockContext;
import org.chromium.base.test.util.Feature;
import org.chromium.base.test.util.UrlUtils;
import org.chromium.chrome.browser.download.DownloadManagerServiceTest.MockDownloadNotifier.MethodID;
import org.chromium.content.browser.DownloadInfo;
import org.chromium.content.browser.DownloadInfo.Builder;
import org.chromium.content.browser.test.util.Criteria;
import org.chromium.content.browser.test.util.CriteriaHelper;
import org.chromium.net.ConnectionType;
import org.chromium.net.test.EmbeddedTestServer;

import java.util.Collections;
import java.util.HashSet;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Test for DownloadManagerService.
 */
public class DownloadManagerServiceTest extends InstrumentationTestCase {
    private static final int UPDATE_DELAY_FOR_TEST = 1;
    private static final int DELAY_BETWEEN_CALLS = 10;
    private static final int LONG_UPDATE_DELAY_FOR_TEST = 500;
    private static final String INSTALL_NOTIFY_URI = "http://test/test";
    private final Random mRandom = new Random();

    /**
     * The MockDownloadNotifier. Currently there is no support for creating mock objects this is a
     * simple mock object that provides testing support for checking a sequence of calls.
     */
    static class MockDownloadNotifier
            implements org.chromium.chrome.browser.download.DownloadNotifier {
        /**
         * The Ids of different methods in this mock object.
         */
        static enum MethodID {
            DOWNLOAD_SUCCESSFUL,
            DOWNLOAD_FAILED,
            DOWNLOAD_PROGRESS,
            DOWNLOAD_PAUSED,
            CANCEL_DOWNLOAD_ID,
            CLEAR_PENDING_DOWNLOADS
        }

        private final Queue<Pair<MethodID, Object>> mExpectedCalls =
                new ConcurrentLinkedQueue<Pair<MethodID, Object>>();

        public MockDownloadNotifier() {
            expect(MethodID.CLEAR_PENDING_DOWNLOADS, null);
        }

        public MockDownloadNotifier expect(MethodID method, Object param) {
            mExpectedCalls.clear();
            mExpectedCalls.add(getMethodSignature(method, param));
            return this;
        }

        public void waitTillExpectedCallsComplete() {
            try {
                CriteriaHelper.pollInstrumentationThread(
                        new Criteria("Failed while waiting for all calls to complete.") {
                            @Override
                            public boolean isSatisfied() {
                                return mExpectedCalls.isEmpty();
                            }
                        });
            } catch (InterruptedException e) {
                fail("Failed while waiting for all calls to complete." + e);
            }
        }

        public MockDownloadNotifier andThen(MethodID method, Object param) {
            mExpectedCalls.add(getMethodSignature(method, param));
            return this;
        }

        static Pair<MethodID, Object> getMethodSignature(MethodID methodId, Object param) {
            return new Pair<MethodID, Object>(methodId, param);
        }

        void assertCorrectExpectedCall(MethodID methodId, Object param) {
            Log.w("MockDownloadNotifier", "Called: " + methodId);
            assertFalse("Unexpected call:, no call expected, but got: " + methodId,
                    mExpectedCalls.isEmpty());
            Pair<MethodID, Object> actual = getMethodSignature(methodId, param);
            Pair<MethodID, Object> expected = mExpectedCalls.poll();
            assertEquals("Unexpected call", expected.first, actual.first);
            assertTrue("Incorrect arguments", MatchHelper.macthes(expected.second, actual.second));
        }

        @Override
        public void notifyDownloadSuccessful(DownloadInfo downloadInfo, Intent intent) {
            assertCorrectExpectedCall(MethodID.DOWNLOAD_SUCCESSFUL, downloadInfo);
        }

        @Override
        public void notifyDownloadFailed(DownloadInfo downloadInfo) {
            assertCorrectExpectedCall(MethodID.DOWNLOAD_FAILED, downloadInfo);

        }

        @Override
        public void notifyDownloadProgress(DownloadInfo downloadInfo, long startTime) {
            assertCorrectExpectedCall(MethodID.DOWNLOAD_PROGRESS, downloadInfo);
        }

        @Override
        public void notifyDownloadPaused(DownloadInfo downloadInfo, boolean isAutoResumable) {
            assertCorrectExpectedCall(MethodID.DOWNLOAD_PAUSED, downloadInfo);
        }

        @Override
        public void cancelNotification(int downloadId) {
            assertCorrectExpectedCall(MethodID.CANCEL_DOWNLOAD_ID, downloadId);
        }

        @Override
        public void clearPendingDownloads() {
            assertCorrectExpectedCall(MethodID.CLEAR_PENDING_DOWNLOADS, null);
        }
    }

    /**
     * Mock implementation of the DownloadSnackbarController.
     */
    static class MockDownloadSnackbarController extends DownloadSnackbarController {
        private boolean mSucceeded;
        private boolean mFailed;

        public MockDownloadSnackbarController() {
            super(null);
        }

        public void waitForSnackbarControllerToFinish(final boolean success) {
            try {
                CriteriaHelper.pollInstrumentationThread(
                        new Criteria("Failed while waiting for all calls to complete.") {
                            @Override
                            public boolean isSatisfied() {
                                return success ? mSucceeded : mFailed;
                            }
                        });
            } catch (InterruptedException e) {
                fail("Failed while waiting for all calls to complete." + e);
            }
        }

        @Override
        public void onDownloadSucceeded(
                DownloadInfo downloadInfo, final long downloadId, boolean canBeResolved) {
            mSucceeded = true;
        }

        @Override
        public void onDownloadFailed(String errorMessage, boolean showAllDownloads) {
            mFailed = true;
        }
    }

    /**
     * A set that each object can be matched ^only^ once. Once matched, the object
     * will be removed from the set. This is useful to write expectations
     * for a sequence of calls where order of calls is not defined. Client can
     * do the following. OneTimeMatchSet matchSet = new OneTimeMatchSet(possibleValue1,
     * possibleValue2, possibleValue3); mockObject.expect(method1, matchSet).andThen(method1,
     * matchSet).andThen(method3, matchSet); .... Some work.
     * mockObject.waitTillExpectedCallsComplete(); assertTrue(matchSet.mMatches.empty());
     */
    private static class OneTimeMatchSet {
        private final HashSet<Object> mMatches;

        OneTimeMatchSet(Object... params) {
            mMatches = new HashSet<Object>();
            Collections.addAll(mMatches, params);
        }

        public boolean matches(Object obj) {
            if (obj == null) return false;
            if (this == obj) return true;
            if (!mMatches.contains(obj)) return false;

            // Remove the object since it has been matched.
            mMatches.remove(obj);
            return true;
        }
    }

    /**
     * Class that helps matching 2 objects with either of them may be a OneTimeMatchSet object.
     */
    private static class MatchHelper {
        public static boolean macthes(Object obj1, Object obj2) {
            if (obj1 == null) return obj2 == null;
            if (obj1.equals(obj2)) return true;
            if (obj1 instanceof OneTimeMatchSet) {
                return ((OneTimeMatchSet) obj1).matches(obj2);
            } else if (obj2 instanceof OneTimeMatchSet) {
                return ((OneTimeMatchSet) obj2).matches(obj1);
            }
            return false;
        }
    }

    static class MockOMADownloadHandler extends OMADownloadHandler {
        protected boolean mSuccess;
        protected String mNofityURI;
        protected DownloadInfo mDownloadInfo;
        protected long mDownloadId;

        MockOMADownloadHandler(Context context) {
            super(context);
        }

        protected void setDownloadId(long downloadId) {
            mDownloadId = downloadId;
        }

        @Override
        public void onDownloadCompleted(DownloadInfo downloadInfo, String notifyURI) {
            mSuccess = true;
            mNofityURI = notifyURI;
        }

        @Override
        public boolean isPendingOMADownload(long downloadId) {
            return mDownloadId == downloadId;
        }

        @Override
        public DownloadInfo updateDownloadInfo(DownloadInfo downloadInfo, long newDownloadId) {
            mDownloadInfo = downloadInfo;
            mDownloadId = newDownloadId;
            mDownloadInfo = DownloadInfo.Builder.fromDownloadInfo(downloadInfo)
                      .setDownloadId((int) newDownloadId)
                      .build();
            return mDownloadInfo;
        }

        @Override
        public String getInstallNotifyInfo(long downloadId) {
            return INSTALL_NOTIFY_URI;
        }
    }

    private static class DownloadManagerServiceForTest extends DownloadManagerService {
        boolean mResumed;
        boolean mIsActiveNetworkMetered;

        public DownloadManagerServiceForTest(Context context, MockDownloadNotifier mockNotifier,
                long updateDelayInMillis) {
            super(context, mockNotifier, getTestHandler(), updateDelayInMillis);
        }

        @Override
        protected long addCompletedDownload(DownloadInfo downloadInfo) {
            return 1L;
        }

        @Override
        protected boolean isActiveNetworkMetered() {
            return mIsActiveNetworkMetered;
        }

        @Override
        protected void init() {}

        @Override
        protected void resumeDownload(int downloadId, String fileName, boolean hasUserGesture) {
            mResumed = true;
        }
    }

    private static Handler getTestHandler() {
        HandlerThread handlerThread = new HandlerThread("handlerThread");
        handlerThread.start();
        return new Handler(handlerThread.getLooper());
    }

    private DownloadInfo getDownloadInfo() {
        return new Builder().setContentLength(100)
                .setDownloadId(mRandom.nextInt(1000))
                .setHasDownloadId(true)
                .build();
    }

    private Context getTestContext() {
        return new AdvancedMockContext(getInstrumentation().getTargetContext());
    }

    @MediumTest
    @Feature({"Download"})
    public void testDownloadProgressIsCalled() throws InterruptedException {
        MockDownloadNotifier notifier = new MockDownloadNotifier();
        DownloadManagerServiceForTest dService = new DownloadManagerServiceForTest(
                getTestContext(), notifier, UPDATE_DELAY_FOR_TEST);
        DownloadInfo downloadInfo = getDownloadInfo();

        notifier.expect(MethodID.DOWNLOAD_PROGRESS, downloadInfo);
        dService.onDownloadUpdated(downloadInfo);
        notifier.waitTillExpectedCallsComplete();

        // Now post multiple download updated calls and make sure all are received.
        DownloadInfo update1 = Builder.fromDownloadInfo(downloadInfo)
                .setPercentCompleted(10).build();
        DownloadInfo update2 = Builder.fromDownloadInfo(downloadInfo)
                .setPercentCompleted(30).build();
        DownloadInfo update3 = Builder.fromDownloadInfo(downloadInfo)
                .setPercentCompleted(30).build();
        notifier.expect(MethodID.DOWNLOAD_PROGRESS, update1)
                .andThen(MethodID.DOWNLOAD_PROGRESS, update2)
                .andThen(MethodID.DOWNLOAD_PROGRESS, update3);

        dService.onDownloadUpdated(update1);
        Thread.sleep(DELAY_BETWEEN_CALLS);
        dService.onDownloadUpdated(update2);
        Thread.sleep(DELAY_BETWEEN_CALLS);
        dService.onDownloadUpdated(update3);
        notifier.waitTillExpectedCallsComplete();
    }

    @MediumTest
    @Feature({"Download"})
    public void testOnlyOneProgressForFastUpdates() throws InterruptedException {
        MockDownloadNotifier notifier = new MockDownloadNotifier();
        DownloadManagerServiceForTest dService = new DownloadManagerServiceForTest(
                getTestContext(), notifier, LONG_UPDATE_DELAY_FOR_TEST);
        DownloadInfo downloadInfo = getDownloadInfo();
        DownloadInfo update1 = Builder.fromDownloadInfo(downloadInfo)
                .setPercentCompleted(10).build();
        DownloadInfo update2 = Builder.fromDownloadInfo(downloadInfo)
                .setPercentCompleted(30).build();
        DownloadInfo update3 = Builder.fromDownloadInfo(downloadInfo)
                .setPercentCompleted(30).build();

        // Should only get one update call, the last update.
        notifier.expect(MethodID.DOWNLOAD_PROGRESS, update3);
        dService.onDownloadUpdated(update1);
        Thread.sleep(DELAY_BETWEEN_CALLS);
        dService.onDownloadUpdated(update2);
        Thread.sleep(DELAY_BETWEEN_CALLS);
        dService.onDownloadUpdated(update3);
        Thread.sleep(DELAY_BETWEEN_CALLS);
        notifier.waitTillExpectedCallsComplete();
    }

    @MediumTest
    @Feature({"Download"})
    public void testDownloadCompletedIsCalled() throws InterruptedException {
        MockDownloadNotifier notifier = new MockDownloadNotifier();
        MockDownloadSnackbarController snackbarController = new MockDownloadSnackbarController();
        DownloadManagerServiceForTest dService = new DownloadManagerServiceForTest(
                getTestContext(), notifier, UPDATE_DELAY_FOR_TEST);
        dService.setDownloadSnackbarController(snackbarController);
        // Try calling download completed directly.
        DownloadInfo successful = getDownloadInfo();

        notifier.expect(MethodID.DOWNLOAD_SUCCESSFUL, successful);

        dService.onDownloadCompleted(successful);
        notifier.waitTillExpectedCallsComplete();
        snackbarController.waitForSnackbarControllerToFinish(true);

        // Now check that a successful notification appears after a download progress.
        DownloadInfo progress = getDownloadInfo();
        notifier.expect(MethodID.DOWNLOAD_PROGRESS, progress)
                .andThen(MethodID.DOWNLOAD_SUCCESSFUL, progress);
        dService.onDownloadUpdated(progress);
        Thread.sleep(DELAY_BETWEEN_CALLS);
        dService.onDownloadCompleted(progress);
        notifier.waitTillExpectedCallsComplete();
        snackbarController.waitForSnackbarControllerToFinish(true);
    }

    @MediumTest
    @Feature({"Download"})
    public void testDownloadFailedIsCalled() throws InterruptedException {
        MockDownloadNotifier notifier = new MockDownloadNotifier();
        DownloadManagerServiceForTest dService = new DownloadManagerServiceForTest(
                getTestContext(), notifier, UPDATE_DELAY_FOR_TEST);
        // Check that if an interrupted download cannot be resumed, it will trigger a download
        // failure.
        DownloadInfo failure =
                Builder.fromDownloadInfo(getDownloadInfo()).setIsResumable(false).build();
        notifier.expect(MethodID.DOWNLOAD_FAILED, failure);
        dService.onDownloadInterrupted(failure, false);
        notifier.waitTillExpectedCallsComplete();
    }

    @MediumTest
    @Feature({"Download"})
    public void testDownloadPausedIsCalled() throws InterruptedException {
        MockDownloadNotifier notifier = new MockDownloadNotifier();
        DownloadManagerServiceForTest dService = new DownloadManagerServiceForTest(
                getTestContext(), notifier, UPDATE_DELAY_FOR_TEST);
        dService.disableNetworkChangeNotifierForTest();
        DownloadInfo paused =
                Builder.fromDownloadInfo(getDownloadInfo()).setIsResumable(true).build();
        notifier.expect(MethodID.DOWNLOAD_PAUSED, paused);
        dService.onDownloadInterrupted(paused, true);
        notifier.waitTillExpectedCallsComplete();
    }

    @MediumTest
    @Feature({"Download"})
    public void testMultipleDownloadProgress() {
        MockDownloadNotifier notifier = new MockDownloadNotifier();
        DownloadManagerServiceForTest dService = new DownloadManagerServiceForTest(
                getTestContext(), notifier, UPDATE_DELAY_FOR_TEST);

        DownloadInfo download1 = getDownloadInfo();
        DownloadInfo download2 = getDownloadInfo();
        DownloadInfo download3 = getDownloadInfo();
        OneTimeMatchSet matchSet = new OneTimeMatchSet(download1, download2, download3);
        notifier.expect(MethodID.DOWNLOAD_PROGRESS, matchSet)
                .andThen(MethodID.DOWNLOAD_PROGRESS, matchSet)
                .andThen(MethodID.DOWNLOAD_PROGRESS, matchSet);
        dService.onDownloadUpdated(download1);
        dService.onDownloadUpdated(download2);
        dService.onDownloadUpdated(download3);

        notifier.waitTillExpectedCallsComplete();
        assertTrue("All downloads should be updated.", matchSet.mMatches.isEmpty());
    }

    @MediumTest
    @Feature({"Download"})
    public void testInterruptedDownloadAreAutoResumed() throws InterruptedException {
        MockDownloadNotifier notifier = new MockDownloadNotifier();
        final DownloadManagerServiceForTest dService = new DownloadManagerServiceForTest(
                getTestContext(), notifier, UPDATE_DELAY_FOR_TEST);
        dService.disableNetworkChangeNotifierForTest();
        DownloadInfo paused =
                Builder.fromDownloadInfo(getDownloadInfo()).setIsResumable(true).build();
        notifier.expect(MethodID.DOWNLOAD_PROGRESS, paused)
                .andThen(MethodID.DOWNLOAD_PAUSED, paused);
        dService.onDownloadUpdated(paused);
        Thread.sleep(DELAY_BETWEEN_CALLS);
        dService.onDownloadInterrupted(paused, true);
        notifier.waitTillExpectedCallsComplete();
        int resumableIdCount = dService.mAutoResumableDownloadIds.size();
        dService.onConnectionTypeChanged(ConnectionType.CONNECTION_WIFI);
        assertEquals(resumableIdCount - 1, dService.mAutoResumableDownloadIds.size());
        CriteriaHelper.pollUiThread(new Criteria() {
            @Override
            public boolean isSatisfied() {
                return dService.mResumed;
            }
        });
    }

    @MediumTest
    @Feature({"Download"})
    public void testInterruptedUnmeteredDownloadCannotAutoResumeOnMeteredNetwork() throws
            InterruptedException {
        MockDownloadNotifier notifier = new MockDownloadNotifier();
        final DownloadManagerServiceForTest dService = new DownloadManagerServiceForTest(
                getTestContext(), notifier, UPDATE_DELAY_FOR_TEST);
        dService.disableNetworkChangeNotifierForTest();
        DownloadInfo paused =
                Builder.fromDownloadInfo(getDownloadInfo()).setIsResumable(true).build();
        notifier.expect(MethodID.DOWNLOAD_PROGRESS, paused)
                .andThen(MethodID.DOWNLOAD_PAUSED, paused);
        dService.onDownloadUpdated(paused);
        Thread.sleep(DELAY_BETWEEN_CALLS);
        dService.onDownloadInterrupted(paused, true);
        notifier.waitTillExpectedCallsComplete();
        dService.mIsActiveNetworkMetered = true;
        int resumableIdCount = dService.mAutoResumableDownloadIds.size();
        dService.onConnectionTypeChanged(ConnectionType.CONNECTION_2G);
        assertEquals(resumableIdCount, dService.mAutoResumableDownloadIds.size());
    }

    /**
     * Test to make sure {@link DownloadManagerService#clearPendingDownloadNotifications}
     * will clear the OMA notifications and pass the notification URI to {@link OMADownloadHandler}.
     */
    @MediumTest
    @Feature({"Download"})
    public void testClearPendingOMADownloads() throws InterruptedException {
        DownloadManager manager =
                (DownloadManager) getTestContext().getSystemService(Context.DOWNLOAD_SERVICE);
        long downloadId = manager.addCompletedDownload(
                "test", "test", false, "text/html",
                UrlUtils.getIsolatedTestFilePath("chrome/test/data/android/download/download.txt"),
                4, true);
        MockDownloadNotifier notifier = new MockDownloadNotifier();
        DownloadManagerServiceForTest dService = new DownloadManagerServiceForTest(
                getTestContext(), notifier, UPDATE_DELAY_FOR_TEST);
        final MockOMADownloadHandler handler = new MockOMADownloadHandler(getTestContext());
        dService.setOMADownloadHandler(handler);
        dService.addOMADownloadToSharedPrefs(String.valueOf(downloadId) + "," + INSTALL_NOTIFY_URI);
        dService.clearPendingOMADownloads();
        CriteriaHelper.pollUiThread(new Criteria() {
            @Override
            public boolean isSatisfied() {
                return handler.mSuccess;
            }
        });
        assertEquals(handler.mNofityURI, "http://test/test");
        manager.remove(downloadId);
    }

    /**
     * Test that calling {@link DownloadManagerService#enqueueDownloadManagerRequest} for an
     * OMA download will enqueue a new DownloadManager request and insert an entry into the
     * SharedPrefs.
     */
    @MediumTest
    @Feature({"Download"})
    public void testEnqueueOMADownloads() throws InterruptedException {
        EmbeddedTestServer testServer = EmbeddedTestServer.createAndStartFileServer(
                getInstrumentation().getContext(), Environment.getExternalStorageDirectory());

        try {
            DownloadInfo info = new DownloadInfo.Builder()
                    .setDownloadId(0)
                    .setMimeType(OMADownloadHandler.OMA_DRM_MESSAGE_MIME)
                    .setFileName("test.gzip")
                    .setUrl(testServer.getURL("/chrome/test/data/android/download/test.gzip"))
                    .build();
            MockDownloadNotifier notifier = new MockDownloadNotifier();
            Context context = getTestContext();
            DownloadManagerServiceForTest dService = new DownloadManagerServiceForTest(
                    context, notifier, UPDATE_DELAY_FOR_TEST);
            final MockOMADownloadHandler handler = new MockOMADownloadHandler(context);
            dService.setOMADownloadHandler(handler);
            handler.setDownloadId(0);
            dService.enqueueDownloadManagerRequest(info, true);
            CriteriaHelper.pollUiThread(new Criteria() {
                @Override
                public boolean isSatisfied() {
                    return handler.mDownloadId != 0;
                }
            });
            handler.mDownloadId = handler.mDownloadInfo.getDownloadId();
            Set<String> downloads = dService.getStoredDownloadInfo(
                    PreferenceManager.getDefaultSharedPreferences(context),
                    DownloadManagerService.PENDING_OMA_DOWNLOADS);
            assertEquals(1, downloads.size());
            DownloadManagerService.OMAEntry entry = DownloadManagerService.OMAEntry.parseOMAEntry(
                    (String) (downloads.toArray()[0]));
            assertEquals(entry.mDownloadId, handler.mDownloadId);
            assertEquals(entry.mInstallNotifyURI, INSTALL_NOTIFY_URI);
            DownloadManager manager =
                    (DownloadManager) getTestContext().getSystemService(Context.DOWNLOAD_SERVICE);
            manager.remove(handler.mDownloadId);
        } finally {
            testServer.stopAndDestroyServer();
        }
    }

    /**
     * Test to make sure {@link DownloadManagerService#shouldOpenAfterDownload}
     * returns the right result for varying MIME types and Content-Dispositions.
     */
    @SmallTest
    @Feature({"Download"})
    public void testShouldOpenAfterDownload() {
        // Should not open any download type MIME types.
        assertFalse(
                DownloadManagerService.shouldOpenAfterDownload(new DownloadInfo.Builder()
                        .setMimeType("application/download")
                        .setHasUserGesture(true)
                        .build()));
        assertFalse(
                DownloadManagerService.shouldOpenAfterDownload(new DownloadInfo.Builder()
                        .setMimeType("application/x-download")
                        .setHasUserGesture(true)
                        .build()));
        assertFalse(
                DownloadManagerService.shouldOpenAfterDownload(new DownloadInfo.Builder()
                        .setMimeType("application/octet-stream")
                        .setHasUserGesture(true)
                        .build()));

        // Should open PDFs.
        assertTrue(
                DownloadManagerService.shouldOpenAfterDownload(new DownloadInfo.Builder()
                        .setMimeType("application/pdf")
                        .setHasUserGesture(true)
                        .build()));
        assertTrue(
                DownloadManagerService.shouldOpenAfterDownload(new DownloadInfo.Builder()
                        .setContentDisposition("filename=test.pdf")
                        .setMimeType("application/pdf")
                        .setHasUserGesture(true)
                        .build()));

        // Require user gesture.
        assertFalse(
                DownloadManagerService.shouldOpenAfterDownload(new DownloadInfo.Builder()
                        .setMimeType("application/pdf")
                        .setHasUserGesture(false)
                        .build()));
        assertFalse(
                DownloadManagerService.shouldOpenAfterDownload(new DownloadInfo.Builder()
                        .setContentDisposition("filename=test.pdf")
                        .setMimeType("application/pdf")
                        .setHasUserGesture(false)
                        .build()));

        // But should not open any PDFs with Content-Disposition: attachment.
        assertFalse(
                DownloadManagerService.shouldOpenAfterDownload(new DownloadInfo.Builder()
                        .setContentDisposition("attachment")
                        .setMimeType("application/pdf")
                        .setHasUserGesture(true)
                        .build()));
        assertFalse(
                DownloadManagerService.shouldOpenAfterDownload(new DownloadInfo.Builder()
                        .setContentDisposition("attachment; filename=test.pdf")
                        .setMimeType("application/pdf")
                        .setHasUserGesture(true)
                        .build()));
    }
}