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 17package com.android.providers.downloads; 18 19import static java.net.HttpURLConnection.HTTP_OK; 20 21import android.app.DownloadManager; 22import android.test.suitebuilder.annotation.LargeTest; 23import android.util.Pair; 24 25import com.google.android.collect.Lists; 26import com.google.android.collect.Sets; 27import com.google.mockwebserver.MockResponse; 28import com.google.mockwebserver.SocketPolicy; 29 30import java.util.HashSet; 31import java.util.List; 32import java.util.Set; 33 34/** 35 * Download manager tests that require multithreading. 36 */ 37@LargeTest 38public class ThreadingTest extends AbstractPublicApiTest { 39 public ThreadingTest() { 40 super(new FakeSystemFacade()); 41 } 42 43 @Override 44 protected void tearDown() throws Exception { 45 Thread.sleep(50); // give threads a chance to finish 46 super.tearDown(); 47 } 48 49 public void testFilenameRace() throws Exception { 50 final List<Pair<Download, String>> downloads = Lists.newArrayList(); 51 final HashSet<String> expectedBodies = Sets.newHashSet(); 52 53 // Request dozen files at once with same name 54 for (int i = 0; i < 32; i++) { 55 final String body = "DOWNLOAD " + i + " CONTENTS"; 56 enqueueResponse(new MockResponse().setResponseCode(HTTP_OK).setBody(body) 57 .setHeader("Content-type", "text/plain") 58 .setSocketPolicy(SocketPolicy.DISCONNECT_AT_END)); 59 60 final Download d = enqueueRequest(getRequest()); 61 downloads.add(Pair.create(d, body)); 62 expectedBodies.add(body); 63 startDownload(d.mId); 64 } 65 66 final long startMillis = mSystemFacade.currentTimeMillis(); 67 for (Pair<Download,String> d : downloads) { 68 d.first.waitForStatus(DownloadManager.STATUS_SUCCESSFUL, startMillis); 69 } 70 71 // Ensure that contents are clean and filenames unique 72 final Set<String> seenFiles = Sets.newHashSet(); 73 final HashSet<String> actualBodies = Sets.newHashSet(); 74 75 for (Pair<Download, String> d : downloads) { 76 final String file = d.first.getStringField(DownloadManager.COLUMN_LOCAL_FILENAME); 77 if (!seenFiles.add(file)) { 78 fail("Another download already claimed " + file); 79 } 80 81 final String expected = d.second; 82 final String actual = d.first.getContents(); 83 84 actualBodies.add(actual); 85 } 86 87 assertEquals(expectedBodies, actualBodies); 88 } 89} 90