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
|
/* 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/. */
const TEST_MSG = "ContentSearchTest";
const CONTENT_SEARCH_MSG = "ContentSearch";
const TEST_CONTENT_SCRIPT_BASENAME = "contentSearch.js";
// This timeout is absurdly high to avoid random failures like bug 1087120.
// That bug was reported when the timeout was 5 seconds, so let's try 10.
const SUGGESTIONS_TIMEOUT = 10000;
var gMsgMan;
/* eslint no-undef:"error" */
/* import-globals-from ../../components/search/test/head.js */
Services.scriptloader.loadSubScript(
"chrome://mochitests/content/browser/browser/components/search/test/head.js",
this);
let originalEngine = Services.search.currentEngine;
add_task(function* setup() {
yield promiseNewEngine("testEngine.xml", {
setAsCurrent: true,
testPath: "chrome://mochitests/content/browser/browser/components/search/test/",
});
registerCleanupFunction(() => {
Services.search.currentEngine = originalEngine;
});
});
add_task(function* GetState() {
yield addTab();
gMsgMan.sendAsyncMessage(TEST_MSG, {
type: "GetState",
});
let msg = yield waitForTestMsg("State");
checkMsg(msg, {
type: "State",
data: yield currentStateObj(),
});
});
add_task(function* SetCurrentEngine() {
yield addTab();
let newCurrentEngine = null;
let oldCurrentEngine = Services.search.currentEngine;
let engines = Services.search.getVisibleEngines();
for (let engine of engines) {
if (engine != oldCurrentEngine) {
newCurrentEngine = engine;
break;
}
}
if (!newCurrentEngine) {
info("Couldn't find a non-selected search engine, " +
"skipping this part of the test");
return;
}
gMsgMan.sendAsyncMessage(TEST_MSG, {
type: "SetCurrentEngine",
data: newCurrentEngine.name,
});
let deferred = Promise.defer();
Services.obs.addObserver(function obs(subj, topic, data) {
info("Test observed " + data);
if (data == "engine-current") {
ok(true, "Test observed engine-current");
Services.obs.removeObserver(obs, "browser-search-engine-modified");
deferred.resolve();
}
}, "browser-search-engine-modified", false);
let searchPromise = waitForTestMsg("CurrentEngine");
info("Waiting for test to observe engine-current...");
yield deferred.promise;
let msg = yield searchPromise;
checkMsg(msg, {
type: "CurrentEngine",
data: yield currentEngineObj(newCurrentEngine),
});
Services.search.currentEngine = oldCurrentEngine;
msg = yield waitForTestMsg("CurrentEngine");
checkMsg(msg, {
type: "CurrentEngine",
data: yield currentEngineObj(oldCurrentEngine),
});
});
add_task(function* modifyEngine() {
yield addTab();
let engine = Services.search.currentEngine;
let oldAlias = engine.alias;
engine.alias = "ContentSearchTest";
let msg = yield waitForTestMsg("CurrentState");
checkMsg(msg, {
type: "CurrentState",
data: yield currentStateObj(),
});
engine.alias = oldAlias;
msg = yield waitForTestMsg("CurrentState");
checkMsg(msg, {
type: "CurrentState",
data: yield currentStateObj(),
});
});
add_task(function* search() {
yield addTab();
let engine = Services.search.currentEngine;
let data = {
engineName: engine.name,
searchString: "ContentSearchTest",
healthReportKey: "ContentSearchTest",
searchPurpose: "ContentSearchTest",
};
let submissionURL =
engine.getSubmission(data.searchString, "", data.whence).uri.spec;
gMsgMan.sendAsyncMessage(TEST_MSG, {
type: "Search",
data: data,
expectedURL: submissionURL,
});
let msg = yield waitForTestMsg("loadStopped");
Assert.equal(msg.data.url, submissionURL, "Correct search page loaded");
});
add_task(function* searchInBackgroundTab() {
// This test is like search(), but it opens a new tab after starting a search
// in another. In other words, it performs a search in a background tab. The
// search page should be loaded in the same tab that performed the search, in
// the background tab.
yield addTab();
let engine = Services.search.currentEngine;
let data = {
engineName: engine.name,
searchString: "ContentSearchTest",
healthReportKey: "ContentSearchTest",
searchPurpose: "ContentSearchTest",
};
let submissionURL =
engine.getSubmission(data.searchString, "", data.whence).uri.spec;
gMsgMan.sendAsyncMessage(TEST_MSG, {
type: "Search",
data: data,
expectedURL: submissionURL,
});
let newTab = gBrowser.addTab();
gBrowser.selectedTab = newTab;
registerCleanupFunction(() => gBrowser.removeTab(newTab));
let msg = yield waitForTestMsg("loadStopped");
Assert.equal(msg.data.url, submissionURL, "Correct search page loaded");
});
add_task(function* badImage() {
yield addTab();
// If the bad image URI caused an exception to be thrown within ContentSearch,
// then we'll hang waiting for the CurrentState responses triggered by the new
// engine. That's what we're testing, and obviously it shouldn't happen.
let vals = yield waitForNewEngine("contentSearchBadImage.xml", 1);
let engine = vals[0];
let finalCurrentStateMsg = vals[vals.length - 1];
let expectedCurrentState = yield currentStateObj();
let expectedEngine =
expectedCurrentState.engines.find(e => e.name == engine.name);
ok(!!expectedEngine, "Sanity check: engine should be in expected state");
ok(expectedEngine.iconBuffer === null,
"Sanity check: icon array buffer of engine in expected state " +
"should be null: " + expectedEngine.iconBuffer);
checkMsg(finalCurrentStateMsg, {
type: "CurrentState",
data: expectedCurrentState,
});
// Removing the engine triggers a final CurrentState message. Wait for it so
// it doesn't trip up subsequent tests.
Services.search.removeEngine(engine);
yield waitForTestMsg("CurrentState");
});
add_task(function* GetSuggestions_AddFormHistoryEntry_RemoveFormHistoryEntry() {
yield addTab();
// Add the test engine that provides suggestions.
let vals = yield waitForNewEngine("contentSearchSuggestions.xml", 0);
let engine = vals[0];
let searchStr = "browser_ContentSearch.js-suggestions-";
// Add a form history suggestion and wait for Satchel to notify about it.
gMsgMan.sendAsyncMessage(TEST_MSG, {
type: "AddFormHistoryEntry",
data: searchStr + "form",
});
let deferred = Promise.defer();
Services.obs.addObserver(function onAdd(subj, topic, data) {
if (data == "formhistory-add") {
Services.obs.removeObserver(onAdd, "satchel-storage-changed");
executeSoon(() => deferred.resolve());
}
}, "satchel-storage-changed", false);
yield deferred.promise;
// Send GetSuggestions using the test engine. Its suggestions should appear
// in the remote suggestions in the Suggestions response below.
gMsgMan.sendAsyncMessage(TEST_MSG, {
type: "GetSuggestions",
data: {
engineName: engine.name,
searchString: searchStr,
remoteTimeout: SUGGESTIONS_TIMEOUT,
},
});
// Check the Suggestions response.
let msg = yield waitForTestMsg("Suggestions");
checkMsg(msg, {
type: "Suggestions",
data: {
engineName: engine.name,
searchString: searchStr,
formHistory: [searchStr + "form"],
remote: [searchStr + "foo", searchStr + "bar"],
},
});
// Delete the form history suggestion and wait for Satchel to notify about it.
gMsgMan.sendAsyncMessage(TEST_MSG, {
type: "RemoveFormHistoryEntry",
data: searchStr + "form",
});
deferred = Promise.defer();
Services.obs.addObserver(function onRemove(subj, topic, data) {
if (data == "formhistory-remove") {
Services.obs.removeObserver(onRemove, "satchel-storage-changed");
executeSoon(() => deferred.resolve());
}
}, "satchel-storage-changed", false);
yield deferred.promise;
// Send GetSuggestions again.
gMsgMan.sendAsyncMessage(TEST_MSG, {
type: "GetSuggestions",
data: {
engineName: engine.name,
searchString: searchStr,
remoteTimeout: SUGGESTIONS_TIMEOUT,
},
});
// The formHistory suggestions in the Suggestions response should be empty.
msg = yield waitForTestMsg("Suggestions");
checkMsg(msg, {
type: "Suggestions",
data: {
engineName: engine.name,
searchString: searchStr,
formHistory: [],
remote: [searchStr + "foo", searchStr + "bar"],
},
});
// Finally, clean up by removing the test engine.
Services.search.removeEngine(engine);
yield waitForTestMsg("CurrentState");
});
function buffersEqual(actualArrayBuffer, expectedArrayBuffer) {
let expectedView = new Int8Array(expectedArrayBuffer);
let actualView = new Int8Array(actualArrayBuffer);
for (let i = 0; i < expectedView.length; i++) {
if (actualView[i] != expectedView[i]) {
return false;
}
}
return true;
}
function arrayBufferEqual(actualArrayBuffer, expectedArrayBuffer) {
ok(actualArrayBuffer instanceof ArrayBuffer, "Actual value is ArrayBuffer.");
ok(expectedArrayBuffer instanceof ArrayBuffer, "Expected value is ArrayBuffer.");
Assert.equal(actualArrayBuffer.byteLength, expectedArrayBuffer.byteLength,
"Array buffers have the same length.");
ok(buffersEqual(actualArrayBuffer, expectedArrayBuffer), "Buffers are equal.");
}
function checkArrayBuffers(actual, expected) {
if (actual instanceof ArrayBuffer) {
arrayBufferEqual(actual, expected);
}
if (typeof actual == "object") {
for (let i in actual) {
checkArrayBuffers(actual[i], expected[i]);
}
}
}
function checkMsg(actualMsg, expectedMsgData) {
let actualMsgData = actualMsg.data;
SimpleTest.isDeeply(actualMsg.data, expectedMsgData, "Checking message");
// Engines contain ArrayBuffers which we have to compare byte by byte and
// not as Objects (like SimpleTest.isDeeply does).
checkArrayBuffers(actualMsgData, expectedMsgData);
}
function waitForMsg(name, type) {
let deferred = Promise.defer();
info("Waiting for " + name + " message " + type + "...");
gMsgMan.addMessageListener(name, function onMsg(msg) {
info("Received " + name + " message " + msg.data.type + "\n");
if (msg.data.type == type) {
gMsgMan.removeMessageListener(name, onMsg);
deferred.resolve(msg);
}
});
return deferred.promise;
}
function waitForTestMsg(type) {
return waitForMsg(TEST_MSG, type);
}
function waitForNewEngine(basename, numImages) {
info("Waiting for engine to be added: " + basename);
// Wait for the search events triggered by adding the new engine.
// engine-added engine-loaded
let expectedSearchEvents = ["CurrentState", "CurrentState"];
// engine-changed for each of the images
for (let i = 0; i < numImages; i++) {
expectedSearchEvents.push("CurrentState");
}
let eventPromises = expectedSearchEvents.map(e => waitForTestMsg(e));
// Wait for addEngine().
let addDeferred = Promise.defer();
let url = getRootDirectory(gTestPath) + basename;
Services.search.addEngine(url, null, "", false, {
onSuccess: function (engine) {
info("Search engine added: " + basename);
addDeferred.resolve(engine);
},
onError: function (errCode) {
ok(false, "addEngine failed with error code " + errCode);
addDeferred.reject();
},
});
return Promise.all([addDeferred.promise].concat(eventPromises));
}
function addTab() {
let deferred = Promise.defer();
let tab = gBrowser.addTab();
gBrowser.selectedTab = tab;
tab.linkedBrowser.addEventListener("load", function load() {
tab.linkedBrowser.removeEventListener("load", load, true);
let url = getRootDirectory(gTestPath) + TEST_CONTENT_SCRIPT_BASENAME;
gMsgMan = tab.linkedBrowser.messageManager;
gMsgMan.sendAsyncMessage(CONTENT_SEARCH_MSG, {
type: "AddToWhitelist",
data: ["about:blank"],
});
waitForMsg(CONTENT_SEARCH_MSG, "AddToWhitelistAck").then(() => {
gMsgMan.loadFrameScript(url, false);
deferred.resolve();
});
}, true);
registerCleanupFunction(() => gBrowser.removeTab(tab));
return deferred.promise;
}
var currentStateObj = Task.async(function* () {
let state = {
engines: [],
currentEngine: yield currentEngineObj(),
};
for (let engine of Services.search.getVisibleEngines()) {
let uri = engine.getIconURLBySize(16, 16);
state.engines.push({
name: engine.name,
iconBuffer: yield arrayBufferFromDataURI(uri),
hidden: false,
});
}
return state;
});
var currentEngineObj = Task.async(function* () {
let engine = Services.search.currentEngine;
let uriFavicon = engine.getIconURLBySize(16, 16);
let bundle = Services.strings.createBundle("chrome://global/locale/autocomplete.properties");
return {
name: engine.name,
placeholder: bundle.formatStringFromName("searchWithEngine", [engine.name], 1),
iconBuffer: yield arrayBufferFromDataURI(uriFavicon),
};
});
function arrayBufferFromDataURI(uri) {
if (!uri) {
return Promise.resolve(null);
}
let deferred = Promise.defer();
let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].
createInstance(Ci.nsIXMLHttpRequest);
xhr.open("GET", uri, true);
xhr.responseType = "arraybuffer";
xhr.onerror = () => {
deferred.resolve(null);
};
xhr.onload = () => {
deferred.resolve(xhr.response);
};
try {
xhr.send();
}
catch (err) {
return Promise.resolve(null);
}
return deferred.promise;
}
|