summaryrefslogtreecommitdiffstats
path: root/toolkit/components/webextensions/test/xpcshell/test_ext_topSites.js
blob: eb3f552ed5b813dd1019a428bf79551290ff943c (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
"use strict";

Cu.import("resource://gre/modules/NewTabUtils.jsm");


function TestProvider(getLinksFn) {
  this.getLinks = getLinksFn;
  this._observers = new Set();
}

TestProvider.prototype = {
  addObserver: function(observer) {
    this._observers.add(observer);
  },
  notifyLinkChanged: function(link, index = -1, deleted = false) {
    this._notifyObservers("onLinkChanged", link, index, deleted);
  },
  notifyManyLinksChanged: function() {
    this._notifyObservers("onManyLinksChanged");
  },
  _notifyObservers: function(observerMethodName, ...args) {
    args.unshift(this);
    for (let obs of this._observers) {
      if (obs[observerMethodName]) {
        obs[observerMethodName].apply(NewTabUtils.links, args);
      }
    }
  },
};

function makeLinks(links) {
  // Important: To avoid test failures due to clock jitter on Windows XP, call
  // Date.now() once here, not each time through the loop.
  let frecency = 0;
  let now = Date.now() * 1000;
  let places = [];
  links.map((link, i) => {
    places.push({
      url: link.url,
      title: link.title,
      lastVisitDate: now - i,
      frecency: frecency++,
    });
  });
  return places;
}

add_task(function* test_topSites() {
  let expect = [{url: "http://example.com/", title: "site#-1"},
                {url: "http://example0.com/", title: "site#0"},
                {url: "http://example1.com/", title: "site#1"},
                {url: "http://example2.com/", title: "site#2"},
                {url: "http://example3.com/", title: "site#3"}];

  let extension = ExtensionTestUtils.loadExtension({
    manifest: {
      "permissions": [
        "topSites",
      ],
    },
    background() {
      browser.topSites.get(result => {
        browser.test.sendMessage("done", result);
      });
    },
  });


  let expectedLinks = makeLinks(expect);
  let provider = new TestProvider(done => done(expectedLinks));

  NewTabUtils.initWithoutProviders();
  NewTabUtils.links.addProvider(provider);

  yield NewTabUtils.links.populateCache();

  yield extension.startup();

  let result = yield extension.awaitMessage("done");
  Assert.deepEqual(expect, result, "got topSites");

  yield extension.unload();

  NewTabUtils.links.removeProvider(provider);
});