Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Side by Side Diff: test/_common.js

Issue 29375915: Issue 4878 - Start using ESLint for adblockpluscore (Closed)
Patch Set: Removed unused imports Created March 15, 2017, 3:11 a.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff | Download patch
« no previous file with comments | « test/.eslintrc.json ('k') | test/domainRestrictions.js » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 /* 1 /*
2 * This file is part of Adblock Plus <https://adblockplus.org/>, 2 * This file is part of Adblock Plus <https://adblockplus.org/>,
3 * Copyright (C) 2006-2016 Eyeo GmbH 3 * Copyright (C) 2006-2016 Eyeo GmbH
4 * 4 *
5 * Adblock Plus is free software: you can redistribute it and/or modify 5 * Adblock Plus is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 3 as 6 * it under the terms of the GNU General Public License version 3 as
7 * published by the Free Software Foundation. 7 * published by the Free Software Foundation.
8 * 8 *
9 * Adblock Plus is distributed in the hope that it will be useful, 9 * Adblock Plus is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. 15 * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>.
16 */ 16 */
17 17
18 "use strict"; 18 "use strict";
19 19
20 let fs = require("fs"); 20 const fs = require("fs");
21 let path = require("path"); 21 const path = require("path");
22 let SandboxedModule = require("sandboxed-module"); 22 const SandboxedModule = require("sandboxed-module");
23 23
24 const Cr = exports.Cr = { 24 const Cr = exports.Cr = {
25 NS_OK: 0, 25 NS_OK: 0,
26 NS_BINDING_ABORTED: 0x804B0002, 26 NS_BINDING_ABORTED: 0x804B0002,
27 NS_ERROR_FAILURE: 0x80004005 27 NS_ERROR_FAILURE: 0x80004005
28 }; 28 };
29 29
30 const MILLIS_IN_SECOND = exports.MILLIS_IN_SECOND = 1000; 30 const MILLIS_IN_SECOND = exports.MILLIS_IN_SECOND = 1000;
31 const MILLIS_IN_MINUTE = exports.MILLIS_IN_MINUTE = 60 * MILLIS_IN_SECOND; 31 const MILLIS_IN_MINUTE = exports.MILLIS_IN_MINUTE = 60 * MILLIS_IN_SECOND;
32 const MILLIS_IN_HOUR = exports.MILLIS_IN_HOUR = 60 * MILLIS_IN_MINUTE; 32 const MILLIS_IN_HOUR = exports.MILLIS_IN_HOUR = 60 * MILLIS_IN_MINUTE;
33 const MILLIS_IN_DAY = exports.MILLIS_IN_DAY = 24 * MILLIS_IN_HOUR; 33
34 function URL(urlString)
35 {
36 return require("url").parse(urlString);
37 }
38
39 let Services = {
40 obs: {
41 addObserver() {}
42 },
43 vc: {
44 compare(v1, v2)
45 {
46 function comparePart(p1, p2)
47 {
48 if (p1 != "*" && p2 == "*")
49 return -1;
50 else if (p1 == "*" && p2 != "*")
51 return 1;
52 else if (p1 == p2)
53 return 0;
54 return parseInt(p1, 10) - parseInt(p2, 10);
55 }
56
57 let parts1 = v1.split(".");
58 let parts2 = v2.split(".");
59 for (let i = 0; i < Math.max(parts1.length, parts2.length); i++)
60 {
61 let result = comparePart(parts1[i] || "0", parts2[i] || "0");
62 if (result != 0)
63 return result;
64 }
65 return 0;
66 }
67 }
68 };
69 let XPCOMUtils = {
70 generateQI() {}
71 };
72 let FileUtils = {};
73 let resources = {Services, XPCOMUtils, FileUtils};
34 74
35 let globals = { 75 let globals = {
36 atob: data => new Buffer(data, "base64").toString("binary"), 76 atob: data => new Buffer(data, "base64").toString("binary"),
37 btoa: data => new Buffer(data, "binary").toString("base64"), 77 btoa: data => new Buffer(data, "binary").toString("base64"),
38 Ci: { 78 Ci: {
39 }, 79 },
40 Cu: { 80 Cu: {
41 import: () => {}, 81 import(resource)
42 reportError: e => undefined 82 {
83 let match = /^resource:\/\/gre\/modules\/(.+)\.jsm$/.exec(resource);
84 let resourceName = match && match[1];
85 if (resourceName && resources.hasOwnProperty(resourceName))
86 return {[resourceName]: resources[resourceName]};
87
88 throw new Error(
89 "Attempt to import unknown JavaScript module " + resource
90 );
91 },
92 reportError(e) {}
43 }, 93 },
44 console: { 94 console: {
45 log: () => undefined, 95 log() {},
46 error: () => undefined, 96 error() {}
47 }, 97 },
48 navigator: { 98 navigator: {
49 }, 99 },
50 onShutdown: { 100 onShutdown: {
51 add: () => 101 add() {}
52 {
53 }
54 }, 102 },
55 Services: { 103 URL
56 obs: {
57 addObserver: () =>
58 {
59 }
60 },
61 vc: {
62 compare: (v1, v2) =>
63 {
64 function comparePart(p1, p2)
65 {
66 if (p1 != "*" && p2 == "*")
67 return -1;
68 else if (p1 == "*" && p2 != "*")
69 return 1;
70 else if (p1 == p2)
71 return 0;
72 else
73 return parseInt(p1, 10) - parseInt(p2, 10);
74 }
75
76 let parts1 = v1.split(".");
77 let parts2 = v2.split(".");
78 for (let i = 0; i < Math.max(parts1.length, parts2.length); i++)
79 {
80 let result = comparePart(parts1[i] || "0", parts2[i] || "0");
81 if (result != 0)
82 return result;
83 }
84 return 0;
85 }
86 }
87 },
88 XPCOMUtils: {
89 generateQI: () =>
90 {
91 }
92 },
93 URL: function(urlString)
94 {
95 return require("url").parse(urlString);
96 }
97 }; 104 };
98 105
99 let knownModules = new Map(); 106 let knownModules = new Map();
100 for (let dir of [path.join(__dirname, "stub-modules"), 107 for (let dir of [path.join(__dirname, "stub-modules"),
101 path.join(__dirname, "..", "lib")]) 108 path.join(__dirname, "..", "lib")])
109 {
102 for (let file of fs.readdirSync(path.resolve(dir))) 110 for (let file of fs.readdirSync(path.resolve(dir)))
111 {
103 if (path.extname(file) == ".js") 112 if (path.extname(file) == ".js")
104 knownModules[path.basename(file, ".js")] = path.resolve(dir, file); 113 knownModules[path.basename(file, ".js")] = path.resolve(dir, file);
114 }
115 }
105 116
106 function addExports(exports) 117 function addExports(exports)
107 { 118 {
108 return function(source) 119 return function(source)
109 { 120 {
110 let extraExports = exports[path.basename(this.filename, ".js")]; 121 let extraExports = exports[path.basename(this.filename, ".js")];
111 if (extraExports) 122 if (extraExports)
123 {
112 for (let name of extraExports) 124 for (let name of extraExports)
125 {
113 source += ` 126 source += `
114 Object.defineProperty(exports, "${name}", {get: () => ${name}});`; 127 Object.defineProperty(exports, "${name}", {get: () => ${name}});`;
128 }
129 }
115 return source; 130 return source;
116 }; 131 };
117 } 132 }
118 133
119 function rewriteRequires(source) 134 function rewriteRequires(source)
120 { 135 {
121 function escapeString(str) 136 function escapeString(str)
122 { 137 {
123 return str.replace(/(["'\\])/g, "\\$1"); 138 return str.replace(/(["'\\])/g, "\\$1");
124 } 139 }
(...skipping 12 matching lines...) Expand all
137 options = {}; 152 options = {};
138 153
139 let sourceTransformers = [rewriteRequires]; 154 let sourceTransformers = [rewriteRequires];
140 if (options.extraExports) 155 if (options.extraExports)
141 sourceTransformers.push(addExports(options.extraExports)); 156 sourceTransformers.push(addExports(options.extraExports));
142 157
143 // This module loads itself into a sandbox, keeping track of the require 158 // This module loads itself into a sandbox, keeping track of the require
144 // function which can be used to load further modules into the sandbox. 159 // function which can be used to load further modules into the sandbox.
145 return SandboxedModule.require("./_common", { 160 return SandboxedModule.require("./_common", {
146 globals: Object.assign({}, globals, options.globals), 161 globals: Object.assign({}, globals, options.globals),
147 sourceTransformers: sourceTransformers 162 sourceTransformers
148 }).require; 163 }).require;
149 }; 164 };
150 165
151 exports.require = require; 166 exports.require = require;
152 167
153 exports.setupTimerAndXMLHttp = function() 168 exports.setupTimerAndXMLHttp = function()
154 { 169 {
155 let currentTime = 100000 * MILLIS_IN_HOUR; 170 let currentTime = 100000 * MILLIS_IN_HOUR;
156 let startTime = currentTime; 171 let startTime = currentTime;
157 172
158 let fakeTimer = { 173 let fakeTimer = {
159 callback: null, 174 callback: null,
160 delay: -1, 175 delay: -1,
161 nextExecution: 0, 176 nextExecution: 0,
162 177
163 initWithCallback: function(callback, delay, type) 178 initWithCallback(callback, delay, type)
164 { 179 {
165 if (this.callback) 180 if (this.callback)
166 throw new Error("Only one timer instance supported"); 181 throw new Error("Only one timer instance supported");
167 if (type != 1) 182 if (type != 1)
168 throw new Error("Only TYPE_REPEATING_SLACK timers supported"); 183 throw new Error("Only TYPE_REPEATING_SLACK timers supported");
169 184
170 this.callback = callback; 185 this.callback = callback;
171 this.delay = delay; 186 this.delay = delay;
172 this.nextExecution = currentTime + delay; 187 this.nextExecution = currentTime + delay;
173 }, 188 },
174 189
175 trigger: function() 190 trigger()
176 { 191 {
177 if (currentTime < this.nextExecution) 192 if (currentTime < this.nextExecution)
178 currentTime = this.nextExecution; 193 currentTime = this.nextExecution;
179 try 194 try
180 { 195 {
181 this.callback(); 196 this.callback();
182 } 197 }
183 finally 198 finally
184 { 199 {
185 this.nextExecution = currentTime + this.delay; 200 this.nextExecution = currentTime + this.delay;
186 } 201 }
187 }, 202 },
188 203
189 cancel: function() 204 cancel()
190 { 205 {
191 this.nextExecution = -1; 206 this.nextExecution = -1;
192 } 207 }
193 }; 208 };
194 209
195 let requests = []; 210 let requests = [];
196 function XMLHttpRequest() 211 function XMLHttpRequest()
197 { 212 {
198 this._host = "http://example.com"; 213 this._host = "http://example.com";
199 this._loadHandlers = []; 214 this._loadHandlers = [];
200 this._errorHandlers = []; 215 this._errorHandlers = [];
201 }; 216 }
202 XMLHttpRequest.prototype = 217 XMLHttpRequest.prototype = {
203 {
204 _path: null, 218 _path: null,
205 _data: null, 219 _data: null,
206 _queryString: null, 220 _queryString: null,
207 _loadHandlers: null, 221 _loadHandlers: null,
208 _errorHandlers: null, 222 _errorHandlers: null,
209 status: 0, 223 status: 0,
210 readyState: 0, 224 readyState: 0,
211 responseText: null, 225 responseText: null,
212 226
213 addEventListener: function(eventName, handler, capture) 227 addEventListener(eventName, handler, capture)
214 { 228 {
215 let list; 229 let list;
216 if (eventName == "load") 230 if (eventName == "load")
217 list = this._loadHandlers; 231 list = this._loadHandlers;
218 else if (eventName == "error") 232 else if (eventName == "error")
219 list = this._errorHandlers; 233 list = this._errorHandlers;
220 else 234 else
221 throw new Error("Event type " + eventName + " not supported"); 235 throw new Error("Event type " + eventName + " not supported");
222 236
223 if (list.indexOf(handler) < 0) 237 if (list.indexOf(handler) < 0)
224 list.push(handler); 238 list.push(handler);
225 }, 239 },
226 240
227 removeEventListener: function(eventName, handler, capture) 241 removeEventListener(eventName, handler, capture)
228 { 242 {
229 let list; 243 let list;
230 if (eventName == "load") 244 if (eventName == "load")
231 list = this._loadHandlers; 245 list = this._loadHandlers;
232 else if (eventName == "error") 246 else if (eventName == "error")
233 list = this._errorHandlers; 247 list = this._errorHandlers;
234 else 248 else
235 throw new Error("Event type " + eventName + " not supported"); 249 throw new Error("Event type " + eventName + " not supported");
236 250
237 let index = list.indexOf(handler); 251 let index = list.indexOf(handler);
238 if (index >= 0) 252 if (index >= 0)
239 list.splice(index, 1); 253 list.splice(index, 1);
240 }, 254 },
241 255
242 open: function(method, url, async, user, password) 256 open(method, url, async, user, password)
243 { 257 {
244 if (method != "GET") 258 if (method != "GET")
245 throw new Error("Only GET requests are supported"); 259 throw new Error("Only GET requests are supported");
246 if (typeof async != "undefined" && !async) 260 if (typeof async != "undefined" && !async)
247 throw new Error("Sync requests are not supported"); 261 throw new Error("Sync requests are not supported");
248 if (typeof user != "undefined" || typeof password != "undefined") 262 if (typeof user != "undefined" || typeof password != "undefined")
249 throw new Error("User authentification is not supported"); 263 throw new Error("User authentification is not supported");
250 264
251 let match = /^data:[^,]+,/.exec(url); 265 let match = /^data:[^,]+,/.exec(url);
252 if (match) 266 if (match)
253 { 267 {
254 this._data = decodeURIComponent(url.substr(match[0].length)); 268 this._data = decodeURIComponent(url.substr(match[0].length));
255 return; 269 return;
256 } 270 }
257 271
258 if (url.substr(0, this._host.length + 1) != this._host + "/") 272 if (url.substr(0, this._host.length + 1) != this._host + "/")
259 throw new Error("Unexpected URL: " + url + " (URL starting with " + this ._host + "expected)"); 273 throw new Error("Unexpected URL: " + url + " (URL starting with " + this ._host + "expected)");
260 274
261 this._path = url.substr(this._host.length); 275 this._path = url.substr(this._host.length);
262 276
263 let queryIndex = this._path.indexOf("?"); 277 let queryIndex = this._path.indexOf("?");
264 this._queryString = ""; 278 this._queryString = "";
265 if (queryIndex >= 0) 279 if (queryIndex >= 0)
266 { 280 {
267 this._queryString = this._path.substr(queryIndex + 1); 281 this._queryString = this._path.substr(queryIndex + 1);
268 this._path = this._path.substr(0, queryIndex); 282 this._path = this._path.substr(0, queryIndex);
269 } 283 }
270 }, 284 },
271 285
272 send: function(data) 286 send(data)
273 { 287 {
274 if (!this._data && !this._path) 288 if (!this._data && !this._path)
275 throw new Error("No request path set"); 289 throw new Error("No request path set");
276 if (typeof data != "undefined" && data) 290 if (typeof data != "undefined" && data)
277 throw new Error("Sending data to server is not supported"); 291 throw new Error("Sending data to server is not supported");
278 292
279 requests.push(Promise.resolve().then(() => 293 requests.push(Promise.resolve().then(() =>
280 { 294 {
281 let result = [Cr.NS_OK, 404, ""]; 295 let result = [Cr.NS_OK, 404, ""];
282 if (this._data) 296 if (this._data)
(...skipping 10 matching lines...) Expand all
293 [this.channel.status, this.channel.responseStatus, this.responseText] = result; 307 [this.channel.status, this.channel.responseStatus, this.responseText] = result;
294 this.status = this.channel.responseStatus; 308 this.status = this.channel.responseStatus;
295 309
296 let eventName = (this.channel.status == Cr.NS_OK ? "load" : "error"); 310 let eventName = (this.channel.status == Cr.NS_OK ? "load" : "error");
297 let event = {type: eventName}; 311 let event = {type: eventName};
298 for (let handler of this["_" + eventName + "Handlers"]) 312 for (let handler of this["_" + eventName + "Handlers"])
299 handler.call(this, event); 313 handler.call(this, event);
300 })); 314 }));
301 }, 315 },
302 316
303 overrideMimeType: function(mime) 317 overrideMimeType(mime)
304 { 318 {
305 }, 319 },
306 320
307 channel: 321 channel:
308 { 322 {
309 status: -1, 323 status: -1,
310 responseStatus: 0, 324 responseStatus: 0,
311 loadFlags: 0, 325 loadFlags: 0,
312 INHIBIT_CACHING: 0, 326 INHIBIT_CACHING: 0,
313 VALIDATE_ALWAYS: 0, 327 VALIDATE_ALWAYS: 0,
314 QueryInterface: () => this 328 QueryInterface: () => this
315 } 329 }
316 }; 330 };
317 331
318 XMLHttpRequest.requestHandlers = {}; 332 XMLHttpRequest.requestHandlers = {};
319 this.registerHandler = (path, handler) => 333 this.registerHandler = (requestPath, handler) =>
320 { 334 {
321 XMLHttpRequest.requestHandlers[path] = handler; 335 XMLHttpRequest.requestHandlers[requestPath] = handler;
322 }; 336 };
323 337
324 function waitForRequests() 338 function waitForRequests()
325 { 339 {
326 if (requests.length) 340 if (requests.length)
327 { 341 {
328 let result = Promise.all(requests); 342 let result = Promise.all(requests);
329 requests = []; 343 requests = [];
330 return result.catch(e => 344 return result.catch(e =>
331 { 345 {
332 console.error(e); 346 console.error(e);
333 }).then(() => waitForRequests()); 347 }).then(() => waitForRequests());
334 } 348 }
335 else 349 return Promise.resolve();
336 return Promise.resolve();
337 } 350 }
338 351
339 function runScheduledTasks(maxMillis) 352 function runScheduledTasks(maxMillis)
340 { 353 {
341 let endTime = currentTime + maxMillis; 354 let endTime = currentTime + maxMillis;
342 if (fakeTimer.nextExecution < 0 || fakeTimer.nextExecution > endTime) 355 if (fakeTimer.nextExecution < 0 || fakeTimer.nextExecution > endTime)
343 { 356 {
344 currentTime = endTime; 357 currentTime = endTime;
345 return Promise.resolve(); 358 return Promise.resolve();
346 } 359 }
347 else 360 fakeTimer.trigger();
348 { 361 return waitForRequests().then(() => runScheduledTasks(endTime - currentTime) );
349 fakeTimer.trigger();
350 return waitForRequests().then(() => runScheduledTasks(endTime - currentTim e));
351 }
352
353 currentTime = endTime;
354 } 362 }
355 363
356 this.runScheduledTasks = (maxHours, initial, skip) => 364 this.runScheduledTasks = (maxHours, initial, skip) =>
357 { 365 {
358 if (typeof maxHours != "number") 366 if (typeof maxHours != "number")
359 throw new Error("Numerical parameter expected"); 367 throw new Error("Numerical parameter expected");
360 if (typeof initial != "number") 368 if (typeof initial != "number")
361 initial = 0; 369 initial = 0;
362 if (typeof skip != "number") 370 if (typeof skip != "number")
363 skip = 0; 371 skip = 0;
(...skipping 28 matching lines...) Expand all
392 createInstance: () => fakeTimer 400 createInstance: () => fakeTimer
393 } 401 }
394 }, 402 },
395 Ci: { 403 Ci: {
396 nsITimer: 404 nsITimer:
397 { 405 {
398 TYPE_ONE_SHOT: 0, 406 TYPE_ONE_SHOT: 0,
399 TYPE_REPEATING_SLACK: 1, 407 TYPE_REPEATING_SLACK: 1,
400 TYPE_REPEATING_PRECISE: 2 408 TYPE_REPEATING_PRECISE: 2
401 }, 409 },
402 nsIHttpChannel: () => null, 410 nsIHttpChannel: () => null
403 }, 411 },
404 Cr, 412 Cr,
405 XMLHttpRequest, 413 XMLHttpRequest,
406 Date: { 414 Date: {
407 now: () => currentTime 415 now: () => currentTime
408 } 416 }
409 }; 417 };
410 }; 418 };
411 419
420 console.warn = console.log;
421
412 exports.setupRandomResult = function() 422 exports.setupRandomResult = function()
413 { 423 {
414 let randomResult = 0.5; 424 let randomResult = 0.5;
415 Object.defineProperty(this, "randomResult", { 425 Object.defineProperty(this, "randomResult", {
416 get: () => randomResult, 426 get: () => randomResult,
417 set: value => randomResult = value 427 set: value => randomResult = value
418 }); 428 });
419 429
420 return { 430 return {
421 Math: { 431 Math: {
422 random: () => randomResult, 432 random: () => randomResult,
423 min: Math.min, 433 min: Math.min,
424 max: Math.max, 434 max: Math.max,
425 round: Math.round 435 round: Math.round
426 } 436 }
427 }; 437 };
428 }; 438 };
429 439
430 exports.unexpectedError = function(error) 440 exports.unexpectedError = function(error)
431 { 441 {
432 console.error(error); 442 console.error(error);
433 this.ok(false, "Unexpected error: " + error); 443 this.ok(false, "Unexpected error: " + error);
434 }; 444 };
OLDNEW
« no previous file with comments | « test/.eslintrc.json ('k') | test/domainRestrictions.js » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld