toolkit/components/downloads/test/unit/head_download_manager.js

changeset 0
6474c204b198
equal deleted inserted replaced
-1:000000000000 0:d951ceedc270
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 // This file tests the download manager backend
6
7 const Cc = Components.classes;
8 const Ci = Components.interfaces;
9 const Cu = Components.utils;
10 const Cr = Components.results;
11
12 do_get_profile();
13
14 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
15 Cu.import("resource://gre/modules/Services.jsm");
16 Cu.import("resource://testing-common/httpd.js");
17 Cu.import("resource://gre/modules/PlacesUtils.jsm");
18 XPCOMUtils.defineLazyModuleGetter(this, "Promise",
19 "resource://gre/modules/Promise.jsm");
20
21 var downloadUtils = { };
22 XPCOMUtils.defineLazyServiceGetter(downloadUtils,
23 "downloadManager",
24 "@mozilla.org/download-manager;1",
25 Ci.nsIDownloadManager);
26
27 function createURI(aObj)
28 {
29 var ios = Cc["@mozilla.org/network/io-service;1"].
30 getService(Ci.nsIIOService);
31 return (aObj instanceof Ci.nsIFile) ? ios.newFileURI(aObj) :
32 ios.newURI(aObj, null, null);
33 }
34
35 var dirSvc = Cc["@mozilla.org/file/directory_service;1"].
36 getService(Ci.nsIProperties);
37
38 var provider = {
39 getFile: function(prop, persistent) {
40 persistent.value = true;
41 if (prop == "DLoads") {
42 var file = dirSvc.get("ProfD", Ci.nsILocalFile);
43 file.append("downloads.rdf");
44 return file;
45 }
46 print("*** Throwing trying to get " + prop);
47 throw Cr.NS_ERROR_FAILURE;
48 },
49 QueryInterface: function(iid) {
50 if (iid.equals(Ci.nsIDirectoryServiceProvider) ||
51 iid.equals(Ci.nsISupports)) {
52 return this;
53 }
54 throw Cr.NS_ERROR_NO_INTERFACE;
55 }
56 };
57 dirSvc.QueryInterface(Ci.nsIDirectoryService).registerProvider(provider);
58
59 var gDownloadCount = 0;
60 /**
61 * Adds a download to the DM, and starts it.
62 * @param server: a HttpServer used to serve the sourceURI
63 * @param aParams (optional): an optional object which contains the function
64 * parameters:
65 * resultFileName: leaf node for the target file
66 * targetFile: nsIFile for the target (overrides resultFileName)
67 * sourceURI: the download source URI
68 * downloadName: the display name of the download
69 * runBeforeStart: a function to run before starting the download
70 * isPrivate: whether the download is private or not
71 */
72 function addDownload(server, aParams)
73 {
74 if (!server)
75 do_throw("Must provide a valid server.");
76 const PORT = server.identity.primaryPort;
77 if (!aParams)
78 aParams = {};
79 if (!("resultFileName" in aParams))
80 aParams.resultFileName = "download.result";
81 if (!("targetFile" in aParams)) {
82 aParams.targetFile = dirSvc.get("ProfD", Ci.nsIFile);
83 aParams.targetFile.append(aParams.resultFileName);
84 }
85 if (!("sourceURI" in aParams))
86 aParams.sourceURI = "http://localhost:" + PORT + "/head_download_manager.js";
87 if (!("downloadName" in aParams))
88 aParams.downloadName = null;
89 if (!("runBeforeStart" in aParams))
90 aParams.runBeforeStart = function () {};
91
92 const nsIWBP = Ci.nsIWebBrowserPersist;
93 var persist = Cc["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
94 .createInstance(Ci.nsIWebBrowserPersist);
95 persist.persistFlags = nsIWBP.PERSIST_FLAGS_REPLACE_EXISTING_FILES |
96 nsIWBP.PERSIST_FLAGS_BYPASS_CACHE |
97 nsIWBP.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION;
98
99 // it is part of the active downloads the moment addDownload is called
100 gDownloadCount++;
101
102 let dm = downloadUtils.downloadManager;
103 var dl = dm.addDownload(Ci.nsIDownloadManager.DOWNLOAD_TYPE_DOWNLOAD,
104 createURI(aParams.sourceURI),
105 createURI(aParams.targetFile), aParams.downloadName, null,
106 Math.round(Date.now() * 1000), null, persist, aParams.isPrivate);
107
108 // This will throw if it isn't found, and that would mean test failure, so no
109 // try catch block
110 if (!aParams.isPrivate)
111 var test = dm.getDownload(dl.id);
112
113 aParams.runBeforeStart.call(undefined, dl);
114
115 persist.progressListener = dl.QueryInterface(Ci.nsIWebProgressListener);
116 persist.savePrivacyAwareURI(dl.source, null, null, null, null, dl.targetFile,
117 aParams.isPrivate);
118
119 return dl;
120 }
121
122 function getDownloadListener()
123 {
124 return {
125 onDownloadStateChange: function(aState, aDownload)
126 {
127 if (aDownload.state == Ci.nsIDownloadManager.DOWNLOAD_QUEUED)
128 do_test_pending();
129
130 if (aDownload.state == Ci.nsIDownloadManager.DOWNLOAD_FINISHED ||
131 aDownload.state == Ci.nsIDownloadManager.DOWNLOAD_CANCELED ||
132 aDownload.state == Ci.nsIDownloadManager.DOWNLOAD_FAILED) {
133 gDownloadCount--;
134 do_test_finished();
135 }
136
137 if (gDownloadCount == 0 && typeof httpserv != "undefined" && httpserv)
138 {
139 do_test_pending();
140 httpserv.stop(do_test_finished);
141 }
142 },
143 onStateChange: function(a, b, c, d, e) { },
144 onProgressChange: function(a, b, c, d, e, f, g) { },
145 onSecurityChange: function(a, b, c, d) { }
146 };
147 }
148
149 /**
150 * Asynchronously adds visits to a page.
151 *
152 * @param aPlaceInfo
153 * Can be an nsIURI, in such a case a single LINK visit will be added.
154 * Otherwise can be an object describing the visit to add, or an array
155 * of these objects:
156 * { uri: nsIURI of the page,
157 * transition: one of the TRANSITION_* from nsINavHistoryService,
158 * [optional] title: title of the page,
159 * [optional] visitDate: visit date in microseconds from the epoch
160 * [optional] referrer: nsIURI of the referrer for this visit
161 * }
162 *
163 * @return {Promise}
164 * @resolves When all visits have been added successfully.
165 * @rejects JavaScript exception.
166 */
167 function promiseAddVisits(aPlaceInfo)
168 {
169 let deferred = Promise.defer();
170 let places = [];
171 if (aPlaceInfo instanceof Ci.nsIURI) {
172 places.push({ uri: aPlaceInfo });
173 }
174 else if (Array.isArray(aPlaceInfo)) {
175 places = places.concat(aPlaceInfo);
176 } else {
177 places.push(aPlaceInfo)
178 }
179
180 // Create mozIVisitInfo for each entry.
181 let now = Date.now();
182 for (let i = 0; i < places.length; i++) {
183 if (!places[i].title) {
184 places[i].title = "test visit for " + places[i].uri.spec;
185 }
186 places[i].visits = [{
187 transitionType: places[i].transition === undefined ? Ci.nsINavHistoryService.TRANSITION_LINK
188 : places[i].transition,
189 visitDate: places[i].visitDate || (now++) * 1000,
190 referrerURI: places[i].referrer
191 }];
192 }
193
194 PlacesUtils.asyncHistory.updatePlaces(
195 places,
196 {
197 handleError: function handleError(aResultCode, aPlaceInfo) {
198 let ex = new Components.Exception("Unexpected error in adding visits.",
199 aResultCode);
200 deferred.reject(ex);
201 },
202 handleResult: function () {},
203 handleCompletion: function handleCompletion() {
204 deferred.resolve();
205 }
206 }
207 );
208
209 return deferred.promise;
210 }
211
212
213 XPCOMUtils.defineLazyGetter(this, "Services", function() {
214 Cu.import("resource://gre/modules/Services.jsm");
215 return Services;
216 });
217
218 // Disable alert service notifications
219 Services.prefs.setBoolPref("browser.download.manager.showAlertOnComplete", false);
220
221 do_register_cleanup(function() {
222 Services.obs.notifyObservers(null, "quit-application", null);
223 });
224
225 function oldDownloadManagerDisabled() {
226 try {
227 // This method throws an exception if the old Download Manager is disabled.
228 Services.downloads.activeDownloadCount;
229 } catch (ex) {
230 return true;
231 }
232 return false;
233 }

mercurial