summaryrefslogtreecommitdiffstats
path: root/comm/mail/test/browser/attachment/browser_attachmentSize.js
blob: f4980c46ad97a3142f355c096df50404f94bf76a (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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

var folder;
var messenger;
var epsilon;

var {
  create_body_part,
  create_deleted_attachment,
  create_detached_attachment,
} = ChromeUtils.import(
  "resource://testing-common/mozmill/AttachmentHelpers.jsm"
);
var {
  add_message_to_folder,
  be_in_folder,
  create_folder,
  create_message,
  get_about_message,
  mc,
  msgGen,
  select_click_row,
} = ChromeUtils.import(
  "resource://testing-common/mozmill/FolderDisplayHelpers.jsm"
);

var { SyntheticPartLeaf, SyntheticPartMultiMixed } = ChromeUtils.import(
  "resource://testing-common/mailnews/MessageGenerator.jsm"
);

var textAttachment =
  "Can't make the frug contest, Helen; stomach's upset. I'll fix you, " +
  "Ubik! Ubik drops you back in the thick of things fast. Taken as " +
  "directed, Ubik speeds relief to head and stomach. Remember: Ubik is " +
  "only seconds away. Avoid prolonged use.";

var binaryAttachment = textAttachment;

var imageAttachment =
  "iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAYAAABWdVznAAAABHNCSVQICAgIfAhkiAAAAAlwS" +
  "FlzAAAN1wAADdcBQiibeAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAA" +
  "A5SURBVCiRY/z//z8DKYCJJNXkaGBgYGD4D8NQ5zUgiTVAxeBqSLaBkVRPM0KtIhrQ3km0jwe" +
  "SNQAAlmAY+71EgFoAAAAASUVORK5CYII=";
var imageSize = 188;

var vcardAttachment =
  "YmVnaW46dmNhcmQNCmZuOkppbSBCb2INCm46Qm9iO0ppbQ0KZW1haWw7aW50ZXJuZXQ6Zm9v" +
  "QGJhci5jb20NCnZlcnNpb246Mi4xDQplbmQ6dmNhcmQNCg0K";
var vcardSize = 90;

var detachedName = "./attachment.txt";
var missingName = "./nonexistent.txt";
var deletedName = "deleted.txt";

// create some messages that have various types of attachments
var messages = [
  {
    name: "text_attachment",
    attachments: [{ body: textAttachment, filename: "ubik.txt", format: "" }],
    attachmentSizes: [textAttachment.length],
    attachmentTotalSize: { size: textAttachment.length, exact: true },
  },
  {
    name: "binary_attachment",
    attachments: [
      {
        body: binaryAttachment,
        contentType: "application/x-ubik",
        filename: "ubik",
        format: "",
      },
    ],
    attachmentSizes: [binaryAttachment.length],
    attachmentTotalSize: { size: binaryAttachment.length, exact: true },
  },
  {
    name: "image_attachment",
    attachments: [
      {
        body: imageAttachment,
        contentType: "image/png",
        filename: "lines.png",
        encoding: "base64",
        format: "",
      },
    ],
    attachmentSizes: [imageSize],
    attachmentTotalSize: { size: imageSize, exact: true },
  },
  {
    name: "detached_attachment",
    bodyPart: null,
    // Sizes filled in on message creation.
    attachmentSizes: [null],
    attachmentTotalSize: { size: 0, exact: true },
  },
  {
    name: "detached_attachment_with_missing_file",
    bodyPart: null,
    attachmentSizes: [-1],
    attachmentTotalSize: { size: 0, exact: false },
  },
  {
    name: "deleted_attachment",
    bodyPart: null,
    attachmentSizes: [-1],
    attachmentTotalSize: { size: 0, exact: true },
  },
  {
    name: "multiple_attachments",
    attachments: [
      { body: textAttachment, filename: "ubik.txt", format: "" },
      {
        body: binaryAttachment,
        contentType: "application/x-ubik",
        filename: "ubik",
        format: "",
      },
    ],
    attachmentSizes: [textAttachment.length, binaryAttachment.length],
    attachmentTotalSize: {
      size: textAttachment.length + binaryAttachment.length,
      exact: true,
    },
  },
  // vCards should be included in the attachment list.
  {
    name: "multiple_attachments_one_vcard",
    attachments: [
      { body: textAttachment, filename: "ubik.txt", format: "" },
      {
        body: vcardAttachment,
        contentType: "text/vcard",
        filename: "ubik.vcf",
        encoding: "base64",
        format: "",
      },
    ],
    attachmentSizes: [textAttachment.length, vcardSize],
    attachmentTotalSize: {
      size: textAttachment.length + vcardSize,
      exact: true,
    },
  },
  {
    name: "multiple_attachments_one_detached",
    bodyPart: null,
    attachments: [{ body: textAttachment, filename: "ubik.txt", format: "" }],
    attachmentSizes: [null, textAttachment.length],
    attachmentTotalSize: { size: textAttachment.length, exact: true },
  },
  {
    name: "multiple_attachments_one_detached_with_missing_file",
    bodyPart: null,
    attachments: [{ body: textAttachment, filename: "ubik.txt", format: "" }],
    attachmentSizes: [-1, textAttachment.length],
    attachmentTotalSize: { size: textAttachment.length, exact: false },
  },
  {
    name: "multiple_attachments_one_deleted",
    bodyPart: null,
    attachments: [{ body: textAttachment, filename: "ubik.txt", format: "" }],
    attachmentSizes: [-1, textAttachment.length],
    attachmentTotalSize: { size: textAttachment.length, exact: true },
  },
  // this is an attached message that itself has an attachment
  {
    name: "attached_message_with_attachment",
    bodyPart: null,
    attachmentSizes: [-1, textAttachment.length],
    attachmentTotalSize: { size: 0, exact: true },
  },
];

add_setup(async function () {
  messenger = Cc["@mozilla.org/messenger;1"].createInstance(Ci.nsIMessenger);

  /* Today's gory details (thanks to Jonathan Protzenko): libmime somehow
   * counts the trailing newline for an attachment MIME part. Most of the time,
   * assuming attachment has N bytes (no matter what's inside, newlines or
   * not), libmime will return N + 1 bytes. On Linux and Mac, this always
   * holds. However, on Windows, if the attachment is not encoded (that is, is
   * inline text), libmime will return N + 2 bytes.
   */
  epsilon = "@mozilla.org/windows-registry-key;1" in Cc ? 4 : 2;

  // set up our detached/deleted attachments
  var detachedFile = new FileUtils.File(
    getTestFilePath(`data/${detachedName}`)
  );
  var detached = create_body_part("Here is a file", [
    create_detached_attachment(detachedFile, "text/plain"),
  ]);

  var missingFile = new FileUtils.File(getTestFilePath(`data/${missingName}`));
  var missing = create_body_part(
    "Here is a file (but you deleted the external file, you silly oaf!)",
    [create_detached_attachment(missingFile, "text/plain")]
  );

  var deleted = create_body_part("Here is a file that you deleted", [
    create_deleted_attachment(deletedName, "text/plain"),
  ]);

  var attachedMessage = msgGen.makeMessage({
    body: { body: textAttachment },
    attachments: [{ body: textAttachment, filename: "ubik.txt", format: "" }],
  });

  /* Much like the above comment, libmime counts bytes differently on Windows,
   * where it counts newlines (\r\n) as 2 bytes. Mac and Linux treats them as
   * 1 byte.
   */
  var attachedMessageLength;
  if (epsilon == 4) {
    // Windows
    attachedMessageLength = attachedMessage.toMessageString().length;
  } else {
    // Mac/Linux
    attachedMessageLength = attachedMessage
      .toMessageString()
      .replace(/\r\n/g, "\n").length;
  }

  folder = await create_folder("AttachmentSizeA");
  for (let i = 0; i < messages.length; i++) {
    // First, add any missing info to the message object.
    switch (messages[i].name) {
      case "detached_attachment":
      case "multiple_attachments_one_detached":
        messages[i].bodyPart = detached;
        messages[i].attachmentSizes[0] = detachedFile.fileSize;
        messages[i].attachmentTotalSize.size += detachedFile.fileSize;
        break;
      case "detached_attachment_with_missing_file":
      case "multiple_attachments_one_detached_with_missing_file":
        messages[i].bodyPart = missing;
        break;
      case "deleted_attachment":
      case "multiple_attachments_one_deleted":
        messages[i].bodyPart = deleted;
        break;
      case "attached_message_with_attachment":
        messages[i].bodyPart = new SyntheticPartMultiMixed([
          new SyntheticPartLeaf("I am text!", { contentType: "text/plain" }),
          attachedMessage,
        ]);
        messages[i].attachmentSizes[0] = attachedMessageLength;
        messages[i].attachmentTotalSize.size += attachedMessageLength;
        break;
    }

    await add_message_to_folder([folder], create_message(messages[i]));
  }
});

/**
 * Make sure that the attachment's size is what we expect
 *
 * @param index the attachment's index, starting at 0
 * @param expectedSize the expected size of the attachment, in bytes
 */
function check_attachment_size(index, expectedSize) {
  let win = get_about_message();
  let list = win.document.getElementById("attachmentList");
  let node = list.querySelectorAll("richlistitem.attachmentItem")[index];

  // First, let's check that the attachment size is correct
  let size = node.attachment.size;
  Assert.ok(
    Math.abs(size - expectedSize) <= epsilon,
    `Attachment "${node.attachment.name}" size should be within ${epsilon} ` +
      `of ${expectedSize} (actual: ${size})`
  );

  // Next, make sure that the formatted size in the label is correct
  Assert.equal(
    node.getAttribute("size"),
    messenger.formatFileSize(size),
    `Attachment "${node.attachment.name}" displayed size should match`
  );
}

/**
 * Make sure that the attachment's size is not displayed
 *
 * @param index the attachment's index, starting at 0
 */
function check_no_attachment_size(index) {
  let win = get_about_message();
  let list = win.document.getElementById("attachmentList");
  let node = list.querySelectorAll("richlistitem.attachmentItem")[index];

  Assert.equal(
    node.attachment.size,
    -1,
    `Attachment "${node.attachment.name}" should have a size of -1`
  );

  // If there's no size, the size attribute is the zero-width space.
  let nodeSize = node.getAttribute("size");
  Assert.equal(
    nodeSize,
    "",
    `Attachment "${node.attachment.name}" size should not be displayed`
  );
}

/**
 * Make sure that the total size of all attachments is what we expect.
 *
 * @param count the expected number of attachments
 * @param expectedSize the expected size in bytes of all the attachments
 * @param exact true if the size of all attachments is known, false otherwise
 */
function check_total_attachment_size(count, expectedSize, exact) {
  let win = get_about_message();
  let list = win.document.getElementById("attachmentList");
  let nodes = list.querySelectorAll("richlistitem.attachmentItem");
  let sizeNode = win.document.getElementById("attachmentSize");

  Assert.equal(
    nodes.length,
    count,
    "Should have the expected number of attachments"
  );

  let lastPartID;
  let size = 0;
  for (let i = 0; i < nodes.length; i++) {
    let attachment = nodes[i].attachment;
    if (!lastPartID || attachment.partID.indexOf(lastPartID) != 0) {
      lastPartID = attachment.partID;
      let currSize = attachment.size;
      if (currSize > 0 && !isNaN(currSize)) {
        size += Number(currSize);
      }
    }
  }

  Assert.ok(
    Math.abs(size - expectedSize) <= epsilon * count,
    `Total attachments size should be within ${epsilon * count} ` +
      `of ${expectedSize} (actual: ${size})`
  );

  // Next, make sure that the formatted size in the label is correct
  let formattedSize = sizeNode.getAttribute("value");
  let expectedFormattedSize = messenger.formatFileSize(size);
  let messengerBundle = mc.window.document.getElementById("bundle_messenger");

  if (!exact) {
    if (size == 0) {
      expectedFormattedSize = messengerBundle.getString(
        "attachmentSizeUnknown"
      );
    } else {
      expectedFormattedSize = messengerBundle.getFormattedString(
        "attachmentSizeAtLeast",
        [expectedFormattedSize]
      );
    }
  }
  Assert.equal(
    formattedSize,
    expectedFormattedSize,
    "Displayed attachments total size should match"
  );
}

/**
 * Make sure that the individual and total attachment sizes for this message
 * are as expected
 *
 * @param index the index of the message to check in the thread pane
 */
async function help_test_attachment_size(index) {
  await be_in_folder(folder);
  select_click_row(index);
  info(`Testing message ${index}: ${messages[index].name}`);
  let expectedSizes = messages[index].attachmentSizes;

  let aboutMessage = get_about_message();
  aboutMessage.toggleAttachmentList(true);

  let attachmentList = aboutMessage.document.getElementById("attachmentList");
  await TestUtils.waitForCondition(
    () => !attachmentList.collapsed,
    "Attachment list is shown"
  );

  for (let i = 0; i < expectedSizes.length; i++) {
    if (expectedSizes[i] == -1) {
      check_no_attachment_size(i);
    } else {
      check_attachment_size(i, expectedSizes[i]);
    }
  }

  let totalSize = messages[index].attachmentTotalSize;
  check_total_attachment_size(
    expectedSizes.length,
    totalSize.size,
    totalSize.exact
  );
}

add_task(async function test_attachment_sizes() {
  for (let i = 0; i < messages.length; i++) {
    await help_test_attachment_size(i);
  }
});

registerCleanupFunction(() => {
  // Remove created folders.
  folder.deleteSelf(null);
});