This repository has been archived by the owner on Dec 11, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 975
/
brave.js
565 lines (501 loc) · 18.7 KB
/
brave.js
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
var Application = require('spectron').Application
var chai = require('chai')
require('./coMocha')
const path = require('path')
const fs = require('fs')
const os = require('os')
const {getTargetAboutUrl, isSourceAboutUrl} = require('../../js/lib/appUrlUtil')
var chaiAsPromised = require('chai-as-promised')
chai.should()
chai.use(chaiAsPromised)
const Server = require('./server')
// toggle me for more verbose logs! :)
const logVerboseEnabled = false
const logVerbose = (string) => {
if (logVerboseEnabled) {
console.log(string)
}
}
const generateUserDataDir = () => {
return path.join(os.tmpdir(), 'brave-test', (new Date().getTime()) + Math.floor(Math.random() * 1000).toString())
}
const rmDir = (dirPath) => {
try {
var files = fs.readdirSync(dirPath)
} catch (e) {
console.error(e)
return
}
if (files.length > 0) {
for (var i = 0; i < files.length; i++) {
var filePath = path.join(dirPath, files[i])
try {
if (fs.statSync(filePath).isFile()) {
fs.unlinkSync(filePath)
} else {
rmDir(filePath)
}
} catch (e) {
console.warn(e)
}
}
}
try {
fs.rmdirSync(dirPath)
} catch (e) {
console.error(e)
return
}
}
var promiseMapSeries = function (array, iterator) {
var length = array.length
var current = Promise.resolve()
var results = new Array(length)
for (var i = 0; i < length; ++i) {
current = results[i] = current.then(function (i) {
return iterator(array[i])
}.bind(undefined, i))
}
return Promise.all(results)
}
let userDataDir = generateUserDataDir()
var exports = {
keys: {
COMMAND: '\ue03d',
CONTROL: '\ue009',
ESCAPE: '\ue00c',
RETURN: '\ue006',
SHIFT: '\ue008'
},
browserWindowUrl: 'file://' + path.resolve(__dirname, '..', '..') + '/app/extensions/brave/index.html',
newTabUrl: 'chrome-extension://mnojpmjdmbbfmejpflffifhffcmidifd/about-newtab.html',
beforeAllServerSetup: function (context) {
context.beforeAll(function (done) {
Server.create(`${__dirname}/../fixtures/`, (err, _server) => {
if (err) {
console.log(err.stack)
}
exports.server = _server
done()
})
})
},
beforeAll: function (context) {
context.timeout(30000)
context.beforeAll(function () {
return exports.startApp.call(this)
})
// define ipc send/on
context.beforeAll(function () {
exports.addCommands.call(this)
})
exports.beforeAllServerSetup(context)
context.beforeEach(function () {
chaiAsPromised.transferPromiseness = this.app.client.transferPromiseness
})
context.afterAll(function () {
exports.server.stop()
})
context.afterAll(function () {
return exports.stopApp.call(this)
})
},
beforeEach: function (context) {
context.timeout(30000)
exports.beforeAllServerSetup(context)
context.beforeEach(function () {
return exports.startApp.call(this)
})
// define ipc send/on
context.beforeEach(function () {
exports.addCommands.call(this)
})
context.beforeEach(function () {
chaiAsPromised.transferPromiseness = this.app.client.transferPromiseness
})
context.afterEach(function () {
return exports.stopApp.call(this)
})
},
addCommands: function () {
this.app.client.addCommand('ipcSend', function (message, ...param) {
return this.execute(function (message, ...param) {
return require('electron').remote.getCurrentWindow().webContents.send(message, ...param)
}, message, ...param).then((response) => response.value)
})
this.app.client.addCommand('ipcSendRenderer', function (message, ...param) {
return this.execute(function (message, ...param) {
return require('electron').ipcRenderer.send(message, ...param)
}, message, ...param).then((response) => response.value)
})
var windowHandlesOrig = this.app.client.windowHandles
Object.getPrototypeOf(this.app.client).windowHandles = function () {
return windowHandlesOrig.apply(this)
.then(function (response) {
var handles = response.value
return promiseMapSeries(handles, (handle) => {
return this.window(handle).getUrl().catch((err) => {
console.error('Error retreiving window handle ' + handle, err)
return ''
})
}).then((urls) => {
var newHandles = []
for (var i = 0; i < urls.length; i++) {
// ignore extension urls unless they are "about" pages
// if (!(urls[i].startsWith('chrome-extension') && !urls[i].match(/about-.*\.html$/))) {
if (urls[i].startsWith(exports.browserWindowUrl)) {
newHandles.push(handles[i])
}
}
response.value = newHandles
return response
})
})
}
this.app.client.addCommand('tabHandles', function (index) {
return windowHandlesOrig.apply(this)
.then(function (response) {
var handles = response.value
return promiseMapSeries(handles, (handle) => {
return this.window(handle).getUrl()
}).then((urls) => {
var newHandles = []
for (var i = 0; i < urls.length; i++) {
// ignore extension urls unless they are "about" pages
if (!(urls[i].startsWith('chrome-extension') && !urls[i].match(/about-.*\.html$/)) &&
// ignore window urls
!urls[i].startsWith('file:')) {
newHandles.push(handles[i])
}
}
response.value = newHandles
return response
})
})
})
this.app.client.addCommand('tabByIndex', function (index) {
logVerbose('tabByIndex(' + index + ')')
return this.tabHandles().then((response) => response.value).then(function (handles) {
logVerbose('tabHandles() => handles.length = ' + handles.length + '; handles[' + index + '] = "' + handles[index] + '";')
return this.window(handles[index])
})
})
this.app.client.addCommand('getTabCount', function () {
return this.tabHandles().then((response) => response.value).then(function (handles) {
logVerbose('getTabCount() => ' + handles.length)
return handles.length
})
})
this.app.client.addCommand('waitForBrowserWindow', function () {
return this.waitUntil(function () {
logVerbose('waitForBrowserWindow()')
return this.windowByUrl(exports.browserWindowUrl).then((response) => {
logVerbose('waitForBrowserWindow() => ' + JSON.stringify(response))
return response
}, () => {
logVerbose('waitForBrowserWindow() => false')
return false
})
})
})
this.app.client.addCommand('waitForUrl', function (url) {
return this.waitUntil(function () {
logVerbose('waitForUrl("' + url + '")')
return this.tabByUrl(url).then((response) => {
logVerbose('tabByUrl("' + url + '") => ' + JSON.stringify(response))
return response
}, () => {
logVerbose('tabByUrl("' + url + '") => false')
return false
})
})
})
this.app.client.addCommand('waitForTabCount', function (tabCount) {
logVerbose('waitForTabCount(' + tabCount + ')')
return this.waitUntil(function () {
return this.getTabCount().then((count) => {
return count === tabCount
})
})
})
this.app.client.addCommand('loadUrl', function (url) {
if (isSourceAboutUrl(url)) {
url = getTargetAboutUrl(url)
}
logVerbose('loadUrl("' + url + '")')
return this.url(url).then((response) => {
logVerbose('loadUrl.url() => ' + JSON.stringify(response))
}, (error) => {
logVerbose('loadUrl.url() => ERROR: ' + JSON.stringify(error))
}).waitForUrl(url)
})
this.app.client.addCommand('getAppState', function () {
return this.execute(function () {
return window.appStoreRenderer.state.toJS()
})
})
this.app.client.addCommand('getWindowState', function () {
return this.execute(function () {
return window.windowStore.state.toJS()
})
})
this.app.client.addCommand('setContextMenuDetail', function () {
return this.execute(function () {
return window.windowActions.setContextMenuDetail()
})
})
this.app.client.addCommand('showFindbar', function (show, key = 1) {
return this.execute(function (show, key) {
window.windowActions.setFindbarShown(Object.assign({
windowId: require('electron').remote.getCurrentWindow().id,
key
}), show !== false)
}, show, key)
})
this.app.client.addCommand('openBraveMenu', function (braveMenu, braveryPanel) {
logVerbose('openBraveMenu()')
return this.windowByUrl(exports.browserWindowUrl)
.waitForVisible(braveMenu)
.click(braveMenu)
.waitForVisible(braveryPanel)
})
this.app.client.addCommand('setPinned', function (location, isPinned, options = {}) {
return this.execute(function (location, isPinned, options) {
var Immutable = require('immutable')
window.windowActions.setPinned(Immutable.fromJS(Object.assign({
windowId: require('electron').remote.getCurrentWindow().id,
location
}, options)), isPinned)
}, location, isPinned, options)
})
this.app.client.addCommand('ipcOn', function (message, fn) {
return this.execute(function (message, fn) {
return require('electron').remote.getCurrentWindow().webContents.on(message, fn)
}, message, fn).then((response) => response.value)
})
this.app.client.addCommand('newWindowAction', function (frameOpts, browserOpts) {
return this.execute(function () {
return require('../../../js/actions/appActions').newWindow()
}, frameOpts, browserOpts).then((response) => response.value)
})
/**
* Adds a site to the sites list, such as a bookmarks.
*
* @param {object} siteDetail - Properties for the siteDetail to add
* @param {string} tag - A site tag from js/constants/siteTags.js
*/
this.app.client.addCommand('addSite', function (siteDetail, tag) {
return this.execute(function (siteDetail, tag) {
return require('../../../js/actions/appActions').addSite(siteDetail, tag)
}, siteDetail, tag).then((response) => response.value)
})
/**
* Adds a list sites to the sites list, including bookmark and foler.
*
* @param {object} siteDetail - Properties for the siteDetail to add
*/
this.app.client.addCommand('addSiteList', function (siteDetail) {
return this.execute(function (siteDetail) {
return require('../../../js/actions/appActions').addSite(siteDetail)
}, siteDetail).then((response) => response.value)
})
/**
* Removes a site from the sites list, or removes a bookmark.
*
* @param {object} siteDetail - Properties for the frame to add
* @param {string} tag - A site tag from js/constants/siteTags.js
*/
this.app.client.addCommand('removeSite', function (siteDetail, tag) {
return this.execute(function (siteDetail, tag) {
return require('../../../js/actions/appActions').removeSite(siteDetail, tag)
}, siteDetail, tag).then((response) => response.value)
})
/**
* Changes a setting
*
* @param {string} key - the setting key to change
* @param value - The setting value to change to
*/
this.app.client.addCommand('changeSetting', function (key, value) {
return this.execute(function (key, value) {
return require('../../../js/actions/appActions').changeSetting(key, value)
}, key, value).then((response) => response.value)
})
/**
* Changes a site setting
*
* @param {string} key - the setting key to change
* @param value - The setting value to change to
*/
this.app.client.addCommand('changeSiteSetting', function (hostPattern, key, value) {
return this.execute(function (hostPattern, key, value) {
return require('../../../js/actions/appActions').changeSiteSetting(hostPattern, key, value)
}, hostPattern, key, value).then((response) => response.value)
})
/**
* Clears application data
*
* @param {object} clearDataDetail - the options to use for clearing
*/
this.app.client.addCommand('clearAppData', function (clearDataDetail) {
return this.execute(function (clearDataDetail) {
return require('../../../js/actions/appActions').clearAppData(clearDataDetail)
}, clearDataDetail).then((response) => response.value)
})
this.app.client.addCommand('getDefaultWindowHeight', function () {
return this.execute(function () {
let screen = require('electron').screen
let primaryDisplay = screen.getPrimaryDisplay()
return primaryDisplay.workAreaSize.height
}).then((response) => response.value)
})
this.app.client.addCommand('getDefaultWindowWidth', function () {
return this.execute(function () {
let screen = require('electron').screen
let primaryDisplay = screen.getPrimaryDisplay()
return primaryDisplay.workAreaSize.width
}).then((response) => response.value)
})
this.app.client.addCommand('getPrimaryDisplayHeight', function () {
return this.execute(function () {
let screen = require('electron').screen
return screen.getPrimaryDisplay().bounds.height
}).then((response) => response.value)
})
this.app.client.addCommand('isDarwin', function () {
return this.execute(function () {
return navigator.platform === 'MacIntel'
}).then((response) => response.value)
})
this.app.client.addCommand('getPrimaryDisplayWidth', function () {
return this.execute(function () {
let screen = require('electron').screen
return screen.getPrimaryDisplay().bounds.width
}).then((response) => response.value)
})
this.app.client.addCommand('resizeWindow', function (width, height) {
return this.execute(function (width, height) {
return require('electron').remote.getCurrentWindow().setSize(width, height)
}, width, height).then((response) => response.value)
})
this.app.client.addCommand('windowParentByUrl', function (url, childSelector = 'webview') {
var context = this
return this.windowHandles().then((response) => response.value).then(function (handles) {
return promiseMapSeries(handles, function (handle) {
return context.window(handle).getAttribute(childSelector, 'src').catch(() => '')
})
}).then(function (response) {
let index = response.indexOf(url)
if (index !== -1) {
return context.windowByIndex(index)
} else {
return undefined
}
})
})
this.app.client.addCommand('windowByUrl', function (url) {
var context = this
return this.windowHandles().then((response) => response.value).then(function (handles) {
return promiseMapSeries(handles, function (handle) {
return context.window(handle).getUrl()
}).then(function (response) {
let index = response.indexOf(url)
if (index !== -1) {
return context.window(handles[index])
} else {
return undefined
}
})
})
})
this.app.client.addCommand('tabByUrl', function (url) {
var context = this
return this.tabHandles().then((response) => response.value).then(function (handles) {
return promiseMapSeries(handles, function (handle) {
return context.window(handle).getUrl()
}).then(function (response) {
let index = response.indexOf(url)
if (index !== -1) {
return context.window(handles[index])
} else {
return undefined
}
})
})
})
this.app.client.addCommand('sendWebviewEvent', function (frameKey, eventName, ...params) {
return this.execute(function (frameKey, eventName, ...params) {
const webview = document.querySelector('webview[data-frame-key="' + frameKey + '"]')
// Get the internal view instance ID from the selected webview
var v8Util = process.atomBinding('v8_util')
var internal = v8Util.getHiddenValue(webview, 'internal')
internal.viewInstanceId
// This allows you to send more args than just the event itself like would only
// be possible with dispatchEvent.
require('electron').ipcRenderer.emit('ELECTRON_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-' + internal.viewInstanceId, ...params)
}, frameKey, eventName, ...params).then((response) => response.value)
})
this.app.client.addCommand('waitForElementFocus', function (selector) {
let activeElement
return this.waitForVisible(selector)
.element(selector)
.then(function (el) { activeElement = el })
.waitUntil(function () {
return this.elementActive()
.then(function (el) {
return el.value.ELEMENT === activeElement.value.ELEMENT
})
})
})
this.app.client.addCommand('waitForDataFile', function (dataFile) {
logVerbose('waitForDataFile("' + dataFile + '")')
return this.waitUntil(function () {
return this.getAppState().then((val) => {
logVerbose('waitForDataFile("' + dataFile + '") => ' + JSON.stringify(val.value[dataFile]))
return val.value[dataFile] && val.value[dataFile].etag && val.value[dataFile].etag.length > 0
})
}, 10000)
})
},
startApp: function () {
if (process.env.KEEP_BRAVE_USER_DATA_DIR) {
console.log('BRAVE_USER_DATA_DIR=' + userDataDir)
}
let env = {
NODE_ENV: 'test',
BRAVE_USER_DATA_DIR: userDataDir
}
this.app = new Application({
waitforInterval: 100,
waitforTimeout: 1000,
quitTimeout: 0,
path: './node_modules/.bin/electron',
env,
args: ['./', '--debug=5858', '--enable-logging', '--v=1']
})
return this.app.start()
},
stopApp: function (cleanSessionStore = true) {
let stop = this.app.stop().then((app) => {
if (cleanSessionStore) {
if (!process.env.KEEP_BRAVE_USER_DATA_DIR) {
userDataDir && rmDir(userDataDir)
}
userDataDir = generateUserDataDir()
}
return app
})
// this.app.client.getMainProcessLogs().then(function (logs) {
// logs.forEach(function (log) {
// console.log(log)
// })
// })
// this.app.client.getRenderProcessLogs().then(function (logs) {
// logs.forEach(function (log) {
// console.log(log)
// })
// })
return stop
}
}
module.exports = exports