summaryrefslogtreecommitdiffstats
path: root/toolkit/components/downloads/test/unit/test_DownloadCore.js
blob: 41aeaac33b8f90122a30e3b518d3bb33737f02e8 (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
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

/**
 * Tests the main download interfaces using DownloadCopySaver.
 */

"use strict";

ChromeUtils.defineESModuleGetters(this, {
  DownloadError: "resource://gre/modules/DownloadCore.sys.mjs",
});

// Execution of common tests

// This is used in common_test_Download.js
// eslint-disable-next-line no-unused-vars
var gUseLegacySaver = false;

var scriptFile = do_get_file("common_test_Download.js");
Services.scriptloader.loadSubScript(NetUtil.newURI(scriptFile).spec);

// Tests

/**
 * The download should fail early if the source and the target are the same.
 */
add_task(async function test_error_target_downloadingToSameFile() {
  let targetFile = getTempFile(TEST_TARGET_FILE_NAME);
  targetFile.create(Ci.nsIFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE);

  let download = await Downloads.createDownload({
    source: NetUtil.newURI(targetFile),
    target: targetFile,
  });
  await Assert.rejects(
    download.start(),
    ex => ex instanceof Downloads.Error && ex.becauseTargetFailed
  );

  Assert.ok(
    await IOUtils.exists(download.target.path),
    "The file should not have been deleted."
  );
});

/**
 * Tests allowHttpStatus allowing requests
 */
add_task(async function test_error_notfound() {
  const targetFile = getTempFile(TEST_TARGET_FILE_NAME);
  let called = false;
  const download = await Downloads.createDownload({
    source: {
      url: httpUrl("notfound.gone"),
      allowHttpStatus(aDownload, aStatusCode) {
        Assert.strictEqual(download, aDownload, "Check Download objects");
        Assert.strictEqual(aStatusCode, 404, "The status should be correct");
        called = true;
        return true;
      },
    },
    target: targetFile,
  });
  await download.start();
  Assert.ok(called, "allowHttpStatus should have been called");
});

/**
 * Tests allowHttpStatus rejecting requests
 */
add_task(async function test_error_notfound_reject() {
  const targetFile = getTempFile(TEST_TARGET_FILE_NAME);
  let called = false;
  const download = await Downloads.createDownload({
    source: {
      url: httpUrl("notfound.gone"),
      allowHttpStatus(aDownload, aStatusCode) {
        Assert.strictEqual(download, aDownload, "Check Download objects");
        Assert.strictEqual(aStatusCode, 404, "The status should be correct");
        called = true;
        return false;
      },
    },
    target: targetFile,
  });
  await Assert.rejects(
    download.start(),
    ex => ex instanceof Downloads.Error && ex.becauseSourceFailed,
    "Download should have been rejected"
  );
  Assert.ok(called, "allowHttpStatus should have been called");
});

/**
 * Tests allowHttpStatus rejecting requests other than 404
 */
add_task(async function test_error_busy_reject() {
  const targetFile = getTempFile(TEST_TARGET_FILE_NAME);
  let called = false;
  const download = await Downloads.createDownload({
    source: {
      url: httpUrl("busy.txt"),
      allowHttpStatus(aDownload, aStatusCode) {
        Assert.strictEqual(download, aDownload, "Check Download objects");
        Assert.strictEqual(aStatusCode, 504, "The status should be correct");
        called = true;
        return false;
      },
    },
    target: targetFile,
  });
  await Assert.rejects(
    download.start(),
    ex => ex instanceof Downloads.Error && ex.becauseSourceFailed,
    "Download should have been rejected"
  );
  Assert.ok(called, "allowHttpStatus should have been called");
});

/**
 * Tests redirects are followed correctly, and the meta data corresponds
 * to the correct, final response
 */
add_task(async function test_redirects() {
  const targetFile = getTempFile(TEST_TARGET_FILE_NAME);
  let called = false;
  const download = await Downloads.createDownload({
    source: {
      url: httpUrl("redirect"),
      allowHttpStatus(aDownload, aStatusCode) {
        Assert.strictEqual(download, aDownload, "Check Download objects");
        Assert.strictEqual(
          aStatusCode,
          504,
          "The status should be correct after a redirect"
        );
        called = true;
        return true;
      },
    },
    target: targetFile,
  });
  await download.start();
  Assert.equal(
    download.contentType,
    "text/plain",
    "Content-Type is correct after redirect"
  );
  Assert.equal(
    download.totalBytes,
    TEST_DATA_SHORT.length,
    "Content-Length is correct after redirect"
  );
  Assert.equal(download.target.size, TEST_DATA_SHORT.length);
  Assert.ok(called, "allowHttpStatus should have been called");
});

/**
 * Tests the DownloadError object.
 */
add_task(function test_DownloadError() {
  let error = new DownloadError({
    result: Cr.NS_ERROR_NOT_RESUMABLE,
    message: "Not resumable.",
  });
  Assert.equal(error.result, Cr.NS_ERROR_NOT_RESUMABLE);
  Assert.equal(error.message, "Not resumable.");
  Assert.ok(!error.becauseSourceFailed);
  Assert.ok(!error.becauseTargetFailed);
  Assert.ok(!error.becauseBlocked);
  Assert.ok(!error.becauseBlockedByParentalControls);

  error = new DownloadError({ message: "Unknown error." });
  Assert.equal(error.result, Cr.NS_ERROR_FAILURE);
  Assert.equal(error.message, "Unknown error.");

  error = new DownloadError({ result: Cr.NS_ERROR_NOT_RESUMABLE });
  Assert.equal(error.result, Cr.NS_ERROR_NOT_RESUMABLE);
  Assert.ok(error.message.indexOf("Exception") > 0);

  // becauseSourceFailed will be set, but not the unknown property.
  error = new DownloadError({
    message: "Unknown error.",
    becauseSourceFailed: true,
    becauseUnknown: true,
  });
  Assert.ok(error.becauseSourceFailed);
  Assert.equal(false, "becauseUnknown" in error);

  error = new DownloadError({
    result: Cr.NS_ERROR_MALFORMED_URI,
    inferCause: true,
  });
  Assert.equal(error.result, Cr.NS_ERROR_MALFORMED_URI);
  Assert.ok(error.becauseSourceFailed);
  Assert.ok(!error.becauseTargetFailed);
  Assert.ok(!error.becauseBlocked);
  Assert.ok(!error.becauseBlockedByParentalControls);

  // This test does not set inferCause, so becauseSourceFailed will not be set.
  error = new DownloadError({ result: Cr.NS_ERROR_MALFORMED_URI });
  Assert.equal(error.result, Cr.NS_ERROR_MALFORMED_URI);
  Assert.ok(!error.becauseSourceFailed);

  error = new DownloadError({
    result: Cr.NS_ERROR_FILE_INVALID_PATH,
    inferCause: true,
  });
  Assert.equal(error.result, Cr.NS_ERROR_FILE_INVALID_PATH);
  Assert.ok(!error.becauseSourceFailed);
  Assert.ok(error.becauseTargetFailed);
  Assert.ok(!error.becauseBlocked);
  Assert.ok(!error.becauseBlockedByParentalControls);

  error = new DownloadError({ becauseBlocked: true });
  Assert.equal(error.message, "Download blocked.");
  Assert.ok(!error.becauseSourceFailed);
  Assert.ok(!error.becauseTargetFailed);
  Assert.ok(error.becauseBlocked);
  Assert.ok(!error.becauseBlockedByParentalControls);

  error = new DownloadError({ becauseBlockedByParentalControls: true });
  Assert.equal(error.message, "Download blocked.");
  Assert.ok(!error.becauseSourceFailed);
  Assert.ok(!error.becauseTargetFailed);
  Assert.ok(error.becauseBlocked);
  Assert.ok(error.becauseBlockedByParentalControls);
});

add_task(async function test_cancel_interrupted_download() {
  let targetFile = getTempFile(TEST_TARGET_FILE_NAME);

  let download = await Downloads.createDownload({
    source: httpUrl("interruptible_resumable.txt"),
    target: targetFile,
  });

  async function createAndCancelDownload() {
    info("Create an interruptible download and cancel it midway");
    mustInterruptResponses();
    const promiseDownloaded = download.start();
    await promiseDownloadMidway(download);
    await download.cancel();

    info("Unblock the interruptible download and wait for its annotation");
    continueResponses();
    await waitForAnnotation(
      httpUrl("interruptible_resumable.txt"),
      "downloads/destinationFileURI"
    );

    await Assert.rejects(
      promiseDownloaded,
      /DownloadError: Download canceled/,
      "Got a download error as expected"
    );
  }

  await new Promise(resolve => {
    const DONE = "=== download xpcshell test console listener done ===";
    const logDone = () => Services.console.logStringMessage(DONE);
    const consoleListener = msg => {
      if (msg == DONE) {
        Services.console.unregisterListener(consoleListener);
        resolve();
      }
    };
    Services.console.reset();
    Services.console.registerListener(consoleListener);

    createAndCancelDownload().then(logDone);
  });

  info(
    "Assert that nsIStreamListener.onDataAvailable has not been called after download.cancel"
  );
  let found = Services.console
    .getMessageArray()
    .map(m => m.message)
    .filter(message => {
      return message.includes("nsIStreamListener.onDataAvailable");
    });
  Assert.deepEqual(
    found,
    [],
    "Expect no nsIStreamListener.onDataAvaialable error"
  );
});