summaryrefslogtreecommitdiffstats
path: root/toolkit/components/places/tests/queries/test_containersQueries_sorting.js
blob: 9cdc0f2a5255eaf21f219cf67f803f0bf5009a01 (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
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et: */
/* 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/. */

/**
 * Testing behavior of bug 473157
 * "Want to sort history in container view without sorting the containers"
 * and regression bug 488783
 * Tags list no longer sorted (alphabetized).
 * This test is for global testing sorting containers queries.
 */

// Globals and Constants

var resultTypes = [
  {
    value: Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_QUERY,
    name: "RESULTS_AS_DATE_QUERY",
  },
  {
    value: Ci.nsINavHistoryQueryOptions.RESULTS_AS_SITE_QUERY,
    name: "RESULTS_AS_SITE_QUERY",
  },
  {
    value: Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_SITE_QUERY,
    name: "RESULTS_AS_DATE_SITE_QUERY",
  },
  {
    value: Ci.nsINavHistoryQueryOptions.RESULTS_AS_TAGS_ROOT,
    name: "RESULTS_AS_TAGS_ROOT",
  },
];

var sortingModes = [
  {
    value: Ci.nsINavHistoryQueryOptions.SORT_BY_TITLE_ASCENDING,
    name: "SORT_BY_TITLE_ASCENDING",
  },
  {
    value: Ci.nsINavHistoryQueryOptions.SORT_BY_TITLE_DESCENDING,
    name: "SORT_BY_TITLE_DESCENDING",
  },
  {
    value: Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_ASCENDING,
    name: "SORT_BY_DATE_ASCENDING",
  },
  {
    value: Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING,
    name: "SORT_BY_DATE_DESCENDING",
  },
  {
    value: Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_ASCENDING,
    name: "SORT_BY_DATEADDED_ASCENDING",
  },
  {
    value: Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_DESCENDING,
    name: "SORT_BY_DATEADDED_DESCENDING",
  },
];

// These pages will be added from newest to oldest and from less visited to most
// visited.
var pages = [
  "http://www.mozilla.org/c/",
  "http://www.mozilla.org/a/",
  "http://www.mozilla.org/b/",
  "http://www.mozilla.com/c/",
  "http://www.mozilla.com/a/",
  "http://www.mozilla.com/b/",
];

var tags = ["mozilla", "Development", "test"];

// Test Runner

/**
 * Enumerates all the sequences of the cartesian product of the arrays contained
 * in aSequences.  Examples:
 *
 *   cartProd([[1, 2, 3], ["a", "b"]], callback);
 *   // callback is called 3 * 2 = 6 times with the following arrays:
 *   // [1, "a"], [1, "b"], [2, "a"], [2, "b"], [3, "a"], [3, "b"]
 *
 *   cartProd([["a"], [1, 2, 3], ["X", "Y"]], callback);
 *   // callback is called 1 * 3 * 2 = 6 times with the following arrays:
 *   // ["a", 1, "X"], ["a", 1, "Y"], ["a", 2, "X"], ["a", 2, "Y"],
 *   // ["a", 3, "X"], ["a", 3, "Y"]
 *
 *   cartProd([[1], [2], [3], [4]], callback);
 *   // callback is called 1 * 1 * 1 * 1 = 1 time with the following array:
 *   // [1, 2, 3, 4]
 *
 *   cartProd([], callback);
 *   // callback is 0 times
 *
 *   cartProd([[1, 2, 3, 4]], callback);
 *   // callback is called 4 times with the following arrays:
 *   // [1], [2], [3], [4]
 *
 * @param  aSequences
 *         an array that contains an arbitrary number of arrays
 * @param  aCallback
 *         a function that is passed each sequence of the product as it's
 *         computed
 * @return the total number of sequences in the product
 */
function cartProd(aSequences, aCallback) {
  if (aSequences.length === 0) {
    return 0;
  }

  // For each sequence in aSequences, we maintain a pointer (an array index,
  // really) to the element we're currently enumerating in that sequence
  var seqEltPtrs = aSequences.map(i => 0);

  var numProds = 0;
  var done = false;
  while (!done) {
    numProds++;

    // prod = sequence in product we're currently enumerating
    var prod = [];
    for (var i = 0; i < aSequences.length; i++) {
      prod.push(aSequences[i][seqEltPtrs[i]]);
    }
    aCallback(prod);

    // The next sequence in the product differs from the current one by just a
    // single element.  Determine which element that is.  We advance the
    // "rightmost" element pointer to the "right" by one.  If we move past the
    // end of that pointer's sequence, reset the pointer to the first element
    // in its sequence and then try the sequence to the "left", and so on.

    // seqPtr = index of rightmost input sequence whose element pointer is not
    // past the end of the sequence
    var seqPtr = aSequences.length - 1;
    while (!done) {
      // Advance the rightmost element pointer.
      seqEltPtrs[seqPtr]++;

      // The rightmost element pointer is past the end of its sequence.
      if (seqEltPtrs[seqPtr] >= aSequences[seqPtr].length) {
        seqEltPtrs[seqPtr] = 0;
        seqPtr--;

        // All element pointers are past the ends of their sequences.
        if (seqPtr < 0) {
          done = true;
        }
      } else {
        break;
      }
    }
  }
  return numProds;
}

/**
 * Test a query based on passed-in options.
 *
 * @param aSequence
 *        array of options we will use to query.
 */
function test_query_callback(aSequence) {
  Assert.equal(aSequence.length, 2);
  var resultType = aSequence[0];
  var sortingMode = aSequence[1];
  print(
    "\n\n*** Testing default sorting for resultType (" +
      resultType.name +
      ") and sortingMode (" +
      sortingMode.name +
      ")"
  );

  // Skip invalid combinations sorting queries by none.
  if (
    resultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_TAGS_ROOT &&
    (sortingMode.value == Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_ASCENDING ||
      sortingMode.value == Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING)
  ) {
    // This is a bookmark query, we can't sort by visit date.
    sortingMode.value = Ci.nsINavHistoryQueryOptions.SORT_BY_NONE;
  }
  if (
    resultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_QUERY ||
    resultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_SITE_QUERY ||
    resultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_SITE_QUERY
  ) {
    // This is an history query, we can't sort by date added.
    if (
      sortingMode.value ==
        Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_ASCENDING ||
      sortingMode.value ==
        Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_DESCENDING
    ) {
      sortingMode.value = Ci.nsINavHistoryQueryOptions.SORT_BY_NONE;
    }
  }

  // Create a new query with required options.
  var query = PlacesUtils.history.getNewQuery();
  var options = PlacesUtils.history.getNewQueryOptions();
  options.resultType = resultType.value;
  options.sortingMode = sortingMode.value;

  // Compare resultset with expectedData.
  var result = PlacesUtils.history.executeQuery(query, options);
  var root = result.root;
  root.containerOpen = true;

  if (
    resultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_QUERY ||
    resultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_SITE_QUERY
  ) {
    // Date containers are always sorted by date descending.
    check_children_sorting(
      root,
      Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING
    );
  } else {
    check_children_sorting(root, sortingMode.value);
  }

  // Now Check sorting of the first child container.
  var container = root
    .getChild(0)
    .QueryInterface(Ci.nsINavHistoryContainerResultNode);
  container.containerOpen = true;

  if (
    resultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_SITE_QUERY
  ) {
    // Has more than one level of containers, first we check the sorting of
    // the first level (site containers), those won't inherit sorting...
    check_children_sorting(
      container,
      Ci.nsINavHistoryQueryOptions.SORT_BY_TITLE_ASCENDING
    );
    // ...then we check sorting of the contained urls, we can't inherit sorting
    // since the above level does not inherit it, so they will be sorted by
    // title ascending.
    let innerContainer = container
      .getChild(0)
      .QueryInterface(Ci.nsINavHistoryContainerResultNode);
    innerContainer.containerOpen = true;
    check_children_sorting(
      innerContainer,
      Ci.nsINavHistoryQueryOptions.SORT_BY_TITLE_ASCENDING
    );
    innerContainer.containerOpen = false;
  } else if (
    resultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_TAGS_ROOT
  ) {
    // Sorting mode for tag contents is hardcoded for now, to allow for faster
    // duplicates filtering.
    check_children_sorting(
      container,
      Ci.nsINavHistoryQueryOptions.SORT_BY_NONE
    );
  } else {
    check_children_sorting(container, sortingMode.value);
  }

  container.containerOpen = false;
  root.containerOpen = false;

  test_result_sortingMode_change(result, resultType, sortingMode);
}

/**
 * Sets sortingMode on aResult and checks for correct sorting of children.
 * Containers should not change their sorting, while contained uri nodes should.
 *
 * @param aResult
 *        nsINavHistoryResult generated by our query.
 * @param aResultType
 *        required result type.
 * @param aOriginalSortingMode
 *        the sorting mode from query's options.
 */
function test_result_sortingMode_change(
  aResult,
  aResultType,
  aOriginalSortingMode
) {
  var root = aResult.root;
  // Now we set sortingMode on the result and check that containers are not
  // sorted while children are.
  sortingModes.forEach(function sortingModeChecker(aForcedSortingMode) {
    print(
      "\n* Test setting sortingMode (" +
        aForcedSortingMode.name +
        ") " +
        "on result with resultType (" +
        aResultType.name +
        ") " +
        "currently sorted as (" +
        aOriginalSortingMode.name +
        ")"
    );

    aResult.sortingMode = aForcedSortingMode.value;
    root.containerOpen = true;

    if (
      aResultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_QUERY ||
      aResultType.value ==
        Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_SITE_QUERY
    ) {
      // Date containers are always sorted by date descending.
      check_children_sorting(
        root,
        Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING
      );
    } else if (
      aResultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_SITE_QUERY &&
      (aOriginalSortingMode.value ==
        Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_ASCENDING ||
        aOriginalSortingMode.value ==
          Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING)
    ) {
      // Site containers don't have a good time property to sort by.
      check_children_sorting(root, Ci.nsINavHistoryQueryOptions.SORT_BY_NONE);
    } else {
      check_children_sorting(root, aOriginalSortingMode.value);
    }

    // Now Check sorting of the first child container.
    var container = root
      .getChild(0)
      .QueryInterface(Ci.nsINavHistoryContainerResultNode);
    container.containerOpen = true;

    if (
      aResultType.value ==
      Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_SITE_QUERY
    ) {
      // Has more than one level of containers, first we check the sorting of
      // the first level (site containers), those won't be sorted...
      check_children_sorting(
        container,
        Ci.nsINavHistoryQueryOptions.SORT_BY_TITLE_ASCENDING
      );
      // ...then we check sorting of the second level of containers, result
      // will sort them through recursiveSort.
      let innerContainer = container
        .getChild(0)
        .QueryInterface(Ci.nsINavHistoryContainerResultNode);
      innerContainer.containerOpen = true;
      check_children_sorting(innerContainer, aForcedSortingMode.value);
      innerContainer.containerOpen = false;
    } else {
      if (
        aResultType.value ==
          Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_QUERY ||
        aResultType.value ==
          Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_SITE_QUERY ||
        aResultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_SITE_QUERY
      ) {
        // Date containers are always sorted by date descending.
        check_children_sorting(root, Ci.nsINavHistoryQueryOptions.SORT_BY_NONE);
      } else {
        check_children_sorting(root, aOriginalSortingMode.value);
      }

      // Children should always be sorted.
      check_children_sorting(container, aForcedSortingMode.value);
    }

    container.containerOpen = false;
    root.containerOpen = false;
  });
}

/**
 * Test if children of aRootNode are correctly sorted.
 * @param aRootNode
 *        already opened root node from our query's result.
 * @param aExpectedSortingMode
 *        The sortingMode we expect results to be.
 */
function check_children_sorting(aRootNode, aExpectedSortingMode) {
  var results = [];
  print("Found children:");
  for (let i = 0; i < aRootNode.childCount; i++) {
    results[i] = aRootNode.getChild(i);
    print(i + " " + results[i].title);
  }

  // Helper for case insensitive string comparison.
  function caseInsensitiveStringComparator(a, b) {
    var aLC = a.toLowerCase();
    var bLC = b.toLowerCase();
    if (aLC < bLC) {
      return -1;
    }
    if (aLC > bLC) {
      return 1;
    }
    return 0;
  }

  // Get a comparator based on expected sortingMode.
  var comparator;
  switch (aExpectedSortingMode) {
    case Ci.nsINavHistoryQueryOptions.SORT_BY_NONE:
      comparator = function (a, b) {
        return 0;
      };
      break;
    case Ci.nsINavHistoryQueryOptions.SORT_BY_TITLE_ASCENDING:
      comparator = function (a, b) {
        return caseInsensitiveStringComparator(a.title, b.title);
      };
      break;
    case Ci.nsINavHistoryQueryOptions.SORT_BY_TITLE_DESCENDING:
      comparator = function (a, b) {
        return -caseInsensitiveStringComparator(a.title, b.title);
      };
      break;
    case Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_ASCENDING:
      comparator = function (a, b) {
        return a.time - b.time;
      };
      break;
    case Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING:
      comparator = function (a, b) {
        return b.time - a.time;
      };
    // fall through - we shouldn't do this, see bug 1572437.
    case Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_ASCENDING:
      comparator = function (a, b) {
        return a.dateAdded - b.dateAdded;
      };
      break;
    case Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_DESCENDING:
      comparator = function (a, b) {
        return b.dateAdded - a.dateAdded;
      };
      break;
    default:
      do_throw("Unknown sorting type: " + aExpectedSortingMode);
  }

  // Make an independent copy of the results array and sort it.
  var sortedResults = results.slice();
  sortedResults.sort(comparator);
  // Actually compare returned children with our sorted array.
  for (let i = 0; i < sortedResults.length; i++) {
    if (sortedResults[i].title != results[i].title) {
      print(
        i +
          " index wrong, expected " +
          sortedResults[i].title +
          " found " +
          results[i].title
      );
    }
    Assert.equal(sortedResults[i].title, results[i].title);
  }
}

// Main

add_task(async function test_containersQueries_sorting() {
  // Add visits, bookmarks and tags to our database.
  var timeInMilliseconds = Date.now();
  var visitCount = 0;
  var dayOffset = 0;
  var visits = [];
  pages.forEach(aPageUrl =>
    visits.push({
      isVisit: true,
      isBookmark: true,
      transType: Ci.nsINavHistoryService.TRANSITION_TYPED,
      uri: aPageUrl,
      title: aPageUrl,
      // subtract 5 hours per iteration, to expose more than one day container.
      lastVisit: (timeInMilliseconds - 18000 * 1000 * dayOffset++) * 1000,
      visitCount: visitCount++,
      isTag: true,
      tagArray: tags,
      isInQuery: true,
    })
  );
  await task_populateDB(visits);

  cartProd([resultTypes, sortingModes], test_query_callback);
});