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

const { PlacesUtils } = ChromeUtils.importESModule(
  "resource://gre/modules/PlacesUtils.sys.mjs"
);
const { NewTabUtils } = ChromeUtils.importESModule(
  "resource://gre/modules/NewTabUtils.sys.mjs"
);
const { PlacesTestUtils } = ChromeUtils.importESModule(
  "resource://testing-common/PlacesTestUtils.sys.mjs"
);

const SEARCH_SHORTCUTS_EXPERIMENT_PREF =
  "browser.newtabpage.activity-stream.improvesearch.topSiteSearchShortcuts";

// A small 1x1 test png
const IMAGE_1x1 =
  "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==";

add_task(async function test_topSites() {
  Services.prefs.setBoolPref(SEARCH_SHORTCUTS_EXPERIMENT_PREF, false);
  let visits = [];
  const numVisits = 15; // To make sure we get frecency.
  let visitDate = new Date(1999, 9, 9, 9, 9).getTime();

  function setVisit(visit) {
    for (let j = 0; j < numVisits; ++j) {
      visitDate -= 1000;
      visit.visits.push({ date: new Date(visitDate) });
    }
    visits.push(visit);
  }
  // Stick a couple sites into history.
  for (let i = 0; i < 2; ++i) {
    setVisit({
      url: `http://example${i}.com/`,
      title: `visit${i}`,
      visits: [],
    });
    setVisit({
      url: `http://www.example${i}.com/foobar`,
      title: `visit${i}-www`,
      visits: [],
    });
  }
  NewTabUtils.init();
  await PlacesUtils.history.insertMany(visits);

  // Insert a favicon to show that favicons are not returned by default.
  let faviconData = new Map();
  faviconData.set("http://example0.com", IMAGE_1x1);
  await PlacesTestUtils.addFavicons(faviconData);

  // Ensure our links show up in activityStream.
  let links = await NewTabUtils.activityStreamLinks.getTopSites({
    onePerDomain: false,
    topsiteFrecency: 1,
  });

  equal(
    links.length,
    visits.length,
    "Top sites has been successfully initialized"
  );

  // Drop the visits.visits for later testing.
  visits = visits.map(v => {
    return { url: v.url, title: v.title, favicon: undefined, type: "url" };
  });

  // Test that results from all providers are returned by default.
  let extension = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: ["topSites"],
    },
    background() {
      browser.test.onMessage.addListener(async options => {
        let sites = await browser.topSites.get(options);
        browser.test.sendMessage("sites", sites);
      });
    },
  });

  await extension.startup();

  function getSites(options) {
    extension.sendMessage(options);
    return extension.awaitMessage("sites");
  }

  Assert.deepEqual(
    [visits[0], visits[2]],
    await getSites(),
    "got topSites default"
  );
  Assert.deepEqual(
    visits,
    await getSites({ onePerDomain: false }),
    "got topSites all links"
  );

  NewTabUtils.activityStreamLinks.blockURL(visits[0]);
  ok(
    NewTabUtils.blockedLinks.isBlocked(visits[0]),
    `link ${visits[0].url} is blocked`
  );

  Assert.deepEqual(
    [visits[2], visits[1]],
    await getSites(),
    "got topSites with blocked links filtered out"
  );
  Assert.deepEqual(
    [visits[0], visits[2]],
    await getSites({ includeBlocked: true }),
    "got topSites with blocked links included"
  );

  // Test favicon result
  let topSites = await getSites({ includeBlocked: true, includeFavicon: true });
  equal(topSites[0].favicon, IMAGE_1x1, "received favicon");

  equal(
    1,
    (await getSites({ limit: 1, includeBlocked: true })).length,
    "limit 1 topSite"
  );

  NewTabUtils.uninit();
  await extension.unload();
  await PlacesUtils.history.clear();
  Services.prefs.clearUserPref(SEARCH_SHORTCUTS_EXPERIMENT_PREF);
});

// Test pinned likns and search shortcuts.
add_task(async function test_topSites_complete() {
  Services.prefs.setBoolPref(SEARCH_SHORTCUTS_EXPERIMENT_PREF, true);
  NewTabUtils.init();
  let time = new Date();
  let pinnedIndex = 0;
  let entries = [
    {
      url: `http://pinned1.com/`,
      title: "pinned1",
      type: "url",
      pinned: pinnedIndex++,
      visitDate: time,
    },
    {
      url: `http://search1.com/`,
      title: "@search1",
      type: "search",
      pinned: pinnedIndex++,
      visitDate: new Date(--time),
    },
    {
      url: `https://amazon.com`,
      title: "@amazon",
      type: "search",
      visitDate: new Date(--time),
    },
    {
      url: `http://history1.com/`,
      title: "history1",
      type: "url",
      visitDate: new Date(--time),
    },
    {
      url: `http://history2.com/`,
      title: "history2",
      type: "url",
      visitDate: new Date(--time),
    },
    {
      url: `https://blocked1.com/`,
      title: "blocked1",
      type: "blocked",
      visitDate: new Date(--time),
    },
  ];

  for (let entry of entries) {
    // Build up frecency.
    await PlacesUtils.history.insert({
      url: entry.url,
      title: entry.title,
      visits: new Array(15).fill({
        date: entry.visitDate,
        transition: PlacesUtils.history.TRANSITIONS.LINK,
      }),
    });
    // Insert a favicon to show that favicons are not returned by default.
    await PlacesTestUtils.addFavicons(new Map([[entry.url, IMAGE_1x1]]));
    if (entry.pinned !== undefined) {
      let info =
        entry.type == "search"
          ? { url: entry.url, label: entry.title, searchTopSite: true }
          : { url: entry.url, title: entry.title };
      NewTabUtils.pinnedLinks.pin(info, entry.pinned);
    }
    if (entry.type == "blocked") {
      NewTabUtils.activityStreamLinks.blockURL({ url: entry.url });
    }
  }

  // Some transformation is necessary to match output data.
  let expectedResults = entries
    .filter(e => e.type != "blocked")
    .map(e => {
      e.favicon = undefined;
      delete e.visitDate;
      delete e.pinned;
      return e;
    });

  let extension = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: ["topSites"],
    },
    background() {
      browser.test.onMessage.addListener(async options => {
        let sites = await browser.topSites.get(options);
        browser.test.sendMessage("sites", sites);
      });
    },
  });

  await extension.startup();

  // Test that results are returned by the API.
  function getSites(options) {
    extension.sendMessage(options);
    return extension.awaitMessage("sites");
  }

  Assert.deepEqual(
    expectedResults,
    await getSites({ includePinned: true, includeSearchShortcuts: true }),
    "got topSites all links"
  );

  // Test no shortcuts.
  dump(JSON.stringify(await getSites({ includePinned: true })) + "\n");
  Assert.ok(
    !(await getSites({ includePinned: true })).some(
      link => link.type == "search"
    ),
    "should get no shortcuts"
  );

  // Test favicons.
  let topSites = await getSites({
    includePinned: true,
    includeSearchShortcuts: true,
    includeFavicon: true,
  });
  Assert.ok(
    topSites.every(f => f.favicon == IMAGE_1x1),
    "favicon is correct"
  );

  // Test options.limit.
  Assert.equal(
    1,
    (
      await getSites({
        includePinned: true,
        includeSearchShortcuts: true,
        limit: 1,
      })
    ).length,
    "limit to 1 topSite"
  );

  // Clear history for a pinned entry, then check results.
  await PlacesUtils.history.remove("http://pinned1.com/");
  let links = await getSites({ includePinned: true });
  Assert.ok(
    links.find(link => link.url == "http://pinned1.com/"),
    "Check unvisited pinned links are returned."
  );
  links = await getSites();
  Assert.ok(
    !links.find(link => link.url == "http://pinned1.com/"),
    "Check unvisited pinned links are not returned."
  );

  await extension.unload();
  NewTabUtils.uninit();
  await PlacesUtils.history.clear();
  await PlacesUtils.bookmarks.eraseEverything();
  Services.prefs.clearUserPref(SEARCH_SHORTCUTS_EXPERIMENT_PREF);
});