autoformat more files

This commit is contained in:
Zeke Sikelianos 2016-03-25 13:03:49 -07:00 committed by Kevin Sawicki
parent 06b556c34c
commit f35f362272
47 changed files with 4458 additions and 4459 deletions

File diff suppressed because it is too large Load diff

View file

@ -1,63 +1,63 @@
const assert = require('assert'); const assert = require('assert')
const path = require('path'); const path = require('path')
const clipboard = require('electron').clipboard; const clipboard = require('electron').clipboard
const nativeImage = require('electron').nativeImage; const nativeImage = require('electron').nativeImage
describe('clipboard module', function () { describe('clipboard module', function () {
var fixtures = path.resolve(__dirname, 'fixtures'); var fixtures = path.resolve(__dirname, 'fixtures')
describe('clipboard.readImage()', function () { describe('clipboard.readImage()', function () {
it('returns NativeImage intance', function () { it('returns NativeImage intance', function () {
var p = path.join(fixtures, 'assets', 'logo.png'); var p = path.join(fixtures, 'assets', 'logo.png')
var i = nativeImage.createFromPath(p); var i = nativeImage.createFromPath(p)
clipboard.writeImage(p); clipboard.writeImage(p)
assert.equal(clipboard.readImage().toDataURL(), i.toDataURL()); assert.equal(clipboard.readImage().toDataURL(), i.toDataURL())
}); })
}); })
describe('clipboard.readText()', function () { describe('clipboard.readText()', function () {
it('returns unicode string correctly', function () { it('returns unicode string correctly', function () {
var text = '千江有水千江月,万里无云万里天'; var text = '千江有水千江月,万里无云万里天'
clipboard.writeText(text); clipboard.writeText(text)
assert.equal(clipboard.readText(), text); assert.equal(clipboard.readText(), text)
}); })
}); })
describe('clipboard.readHtml()', function () { describe('clipboard.readHtml()', function () {
it('returns markup correctly', function () { it('returns markup correctly', function () {
var text = '<string>Hi</string>'; var text = '<string>Hi</string>'
var markup = process.platform === 'darwin' ? '<meta charset=\'utf-8\'><string>Hi</string>' : process.platform === 'linux' ? '<meta http-equiv="content-type" ' + 'content="text/html; charset=utf-8"><string>Hi</string>' : '<string>Hi</string>'; var markup = process.platform === 'darwin' ? "<meta charset='utf-8'><string>Hi</string>" : process.platform === 'linux' ? '<meta http-equiv="content-type" ' + 'content="text/html; charset=utf-8"><string>Hi</string>' : '<string>Hi</string>'
clipboard.writeHtml(text); clipboard.writeHtml(text)
assert.equal(clipboard.readHtml(), markup); assert.equal(clipboard.readHtml(), markup)
}); })
}); })
describe('clipboard.readRtf', function () { describe('clipboard.readRtf', function () {
it('returns rtf text correctly', function () { it('returns rtf text correctly', function () {
var rtf = "{\\rtf1\\ansi{\\fonttbl\\f0\\fswiss Helvetica;}\\f0\\pard\nThis is some {\\b bold} text.\\par\n}"; var rtf = '{\\rtf1\\ansi{\\fonttbl\\f0\\fswiss Helvetica;}\\f0\\pard\nThis is some {\\b bold} text.\\par\n}'
clipboard.writeRtf(rtf); clipboard.writeRtf(rtf)
assert.equal(clipboard.readRtf(), rtf); assert.equal(clipboard.readRtf(), rtf)
}); })
}); })
describe('clipboard.write()', function () { describe('clipboard.write()', function () {
it('returns data correctly', function () { it('returns data correctly', function () {
var text = 'test'; var text = 'test'
var rtf = '{\\rtf1\\utf8 text}'; var rtf = '{\\rtf1\\utf8 text}'
var p = path.join(fixtures, 'assets', 'logo.png'); var p = path.join(fixtures, 'assets', 'logo.png')
var i = nativeImage.createFromPath(p); var i = nativeImage.createFromPath(p)
var markup = process.platform === 'darwin' ? '<meta charset=\'utf-8\'><b>Hi</b>' : process.platform === 'linux' ? '<meta http-equiv="content-type" ' + 'content="text/html; charset=utf-8"><b>Hi</b>' : '<b>Hi</b>'; var markup = process.platform === 'darwin' ? "<meta charset='utf-8'><b>Hi</b>" : process.platform === 'linux' ? '<meta http-equiv="content-type" ' + 'content="text/html; charset=utf-8"><b>Hi</b>' : '<b>Hi</b>'
clipboard.write({ clipboard.write({
text: "test", text: 'test',
html: '<b>Hi</b>', html: '<b>Hi</b>',
rtf: '{\\rtf1\\utf8 text}', rtf: '{\\rtf1\\utf8 text}',
image: p image: p
}); })
assert.equal(clipboard.readText(), text); assert.equal(clipboard.readText(), text)
assert.equal(clipboard.readHtml(), markup); assert.equal(clipboard.readHtml(), markup)
assert.equal(clipboard.readRtf(), rtf); assert.equal(clipboard.readRtf(), rtf)
assert.equal(clipboard.readImage().toDataURL(), i.toDataURL()); assert.equal(clipboard.readImage().toDataURL(), i.toDataURL())
}); })
}); })
}); })

View file

@ -1,93 +1,93 @@
const assert = require('assert'); const assert = require('assert')
const http = require('http'); const http = require('http')
const multiparty = require('multiparty'); const multiparty = require('multiparty')
const path = require('path'); const path = require('path')
const url = require('url'); const url = require('url')
const remote = require('electron').remote; const remote = require('electron').remote
const app = remote.require('electron').app; const app = remote.require('electron').app
const crashReporter = remote.require('electron').crashReporter; const crashReporter = remote.require('electron').crashReporter
const BrowserWindow = remote.require('electron').BrowserWindow; const BrowserWindow = remote.require('electron').BrowserWindow
describe('crash-reporter module', function () { describe('crash-reporter module', function () {
var fixtures = path.resolve(__dirname, 'fixtures'); var fixtures = path.resolve(__dirname, 'fixtures')
var w = null; var w = null
beforeEach(function () { beforeEach(function () {
w = new BrowserWindow({ w = new BrowserWindow({
show: false show: false
}); })
}); })
afterEach(function () { afterEach(function () {
w.destroy(); w.destroy()
}); })
if (process.mas) { if (process.mas) {
return; return
} }
var isCI = remote.getGlobal('isCi'); var isCI = remote.getGlobal('isCi')
if (isCI) { if (isCI) {
return; return
} }
it('should send minidump when renderer crashes', function (done) { it('should send minidump when renderer crashes', function (done) {
this.timeout(120000); this.timeout(120000)
var called = false; var called = false
var server = http.createServer(function (req, res) { var server = http.createServer(function (req, res) {
server.close(); server.close()
var form = new multiparty.Form(); var form = new multiparty.Form()
form.parse(req, function (error, fields) { form.parse(req, function (error, fields) {
if (called) { if (called) {
return; return
} }
called = true; called = true
assert.equal(fields['prod'], 'Electron'); assert.equal(fields['prod'], 'Electron')
assert.equal(fields['ver'], process.versions['electron']); assert.equal(fields['ver'], process.versions['electron'])
assert.equal(fields['process_type'], 'renderer'); assert.equal(fields['process_type'], 'renderer')
assert.equal(fields['platform'], process.platform); assert.equal(fields['platform'], process.platform)
assert.equal(fields['extra1'], 'extra1'); assert.equal(fields['extra1'], 'extra1')
assert.equal(fields['extra2'], 'extra2'); assert.equal(fields['extra2'], 'extra2')
assert.equal(fields['_productName'], 'Zombies'); assert.equal(fields['_productName'], 'Zombies')
assert.equal(fields['_companyName'], 'Umbrella Corporation'); assert.equal(fields['_companyName'], 'Umbrella Corporation')
assert.equal(fields['_version'], app.getVersion()); assert.equal(fields['_version'], app.getVersion())
res.end('abc-123-def'); res.end('abc-123-def')
done(); done()
}); })
}); })
var port = remote.process.port; var port = remote.process.port
server.listen(port, '127.0.0.1', function () { server.listen(port, '127.0.0.1', function () {
port = server.address().port; port = server.address().port
remote.process.port = port; remote.process.port = port
const crashUrl = url.format({ const crashUrl = url.format({
protocol: 'file', protocol: 'file',
pathname: path.join(fixtures, 'api', 'crash.html'), pathname: path.join(fixtures, 'api', 'crash.html'),
search: "?port=" + port search: '?port=' + port
}); })
if (process.platform === 'darwin') { if (process.platform === 'darwin') {
crashReporter.start({ crashReporter.start({
companyName: 'Umbrella Corporation', companyName: 'Umbrella Corporation',
submitURL: "http://127.0.0.1:" + port submitURL: 'http://127.0.0.1:' + port
}); })
} }
w.loadURL(crashUrl); w.loadURL(crashUrl)
}); })
}); })
describe(".start(options)", function() { describe('.start(options)', function () {
it('requires that the companyName and submitURL options be specified', function () { it('requires that the companyName and submitURL options be specified', function () {
assert.throws(function () { assert.throws(function () {
crashReporter.start({ crashReporter.start({
companyName: 'Missing submitURL' companyName: 'Missing submitURL'
}); })
}); })
assert.throws(function () { assert.throws(function () {
crashReporter.start({ crashReporter.start({
submitURL: 'Missing companyName' submitURL: 'Missing companyName'
}); })
}); })
}); })
}); })
}); })

View file

@ -1,133 +1,133 @@
const assert = require('assert'); const assert = require('assert')
const path = require('path'); const path = require('path')
const BrowserWindow = require('electron').remote.BrowserWindow; const BrowserWindow = require('electron').remote.BrowserWindow
describe('debugger module', function () { describe('debugger module', function () {
var fixtures = path.resolve(__dirname, 'fixtures'); var fixtures = path.resolve(__dirname, 'fixtures')
var w = null; var w = null
beforeEach(function () { beforeEach(function () {
if (w != null) { if (w != null) {
w.destroy(); w.destroy()
} }
w = new BrowserWindow({ w = new BrowserWindow({
show: false, show: false,
width: 400, width: 400,
height: 400 height: 400
}); })
}); })
afterEach(function () { afterEach(function () {
if (w != null) { if (w != null) {
w.destroy(); w.destroy()
} }
w = null; w = null
}); })
describe('debugger.attach', function () { describe('debugger.attach', function () {
it('fails when devtools is already open', function (done) { it('fails when devtools is already open', function (done) {
w.webContents.on('did-finish-load', function () { w.webContents.on('did-finish-load', function () {
w.webContents.openDevTools(); w.webContents.openDevTools()
try { try {
w.webContents.debugger.attach(); w.webContents.debugger.attach()
} catch(err) { } catch(err) {
assert(w.webContents.debugger.isAttached()); assert(w.webContents.debugger.isAttached())
done(); done()
} }
}); })
w.webContents.loadURL('file://' + path.join(fixtures, 'pages', 'a.html')); w.webContents.loadURL('file://' + path.join(fixtures, 'pages', 'a.html'))
}); })
it('fails when protocol version is not supported', function (done) { it('fails when protocol version is not supported', function (done) {
try { try {
w.webContents.debugger.attach("2.0"); w.webContents.debugger.attach('2.0')
} catch(err) { } catch(err) {
assert(!w.webContents.debugger.isAttached()); assert(!w.webContents.debugger.isAttached())
done(); done()
} }
}); })
it('attaches when no protocol version is specified', function (done) { it('attaches when no protocol version is specified', function (done) {
try { try {
w.webContents.debugger.attach(); w.webContents.debugger.attach()
} catch(err) { } catch(err) {
done('unexpected error : ' + err); done('unexpected error : ' + err)
} }
assert(w.webContents.debugger.isAttached()); assert(w.webContents.debugger.isAttached())
done(); done()
}); })
}); })
describe('debugger.detach', function () { describe('debugger.detach', function () {
it('fires detach event', function (done) { it('fires detach event', function (done) {
w.webContents.debugger.on('detach', function (e, reason) { w.webContents.debugger.on('detach', function (e, reason) {
assert.equal(reason, 'target closed'); assert.equal(reason, 'target closed')
assert(!w.webContents.debugger.isAttached()); assert(!w.webContents.debugger.isAttached())
done(); done()
}); })
try { try {
w.webContents.debugger.attach(); w.webContents.debugger.attach()
} catch(err) { } catch(err) {
done('unexpected error : ' + err); done('unexpected error : ' + err)
} }
w.webContents.debugger.detach(); w.webContents.debugger.detach()
}); })
}); })
describe('debugger.sendCommand', function () { describe('debugger.sendCommand', function () {
it('retuns response', function (done) { it('retuns response', function (done) {
w.webContents.loadURL('about:blank'); w.webContents.loadURL('about:blank')
try { try {
w.webContents.debugger.attach(); w.webContents.debugger.attach()
} catch(err) { } catch(err) {
done('unexpected error : ' + err); done('unexpected error : ' + err)
} }
var callback = function (err, res) { var callback = function (err, res) {
assert(!res.wasThrown); assert(!res.wasThrown)
assert.equal(res.result.value, 6); assert.equal(res.result.value, 6)
w.webContents.debugger.detach(); w.webContents.debugger.detach()
done(); done()
}; }
const params = { const params = {
"expression": "4+2", 'expression': '4+2',
}; }
w.webContents.debugger.sendCommand("Runtime.evaluate", params, callback); w.webContents.debugger.sendCommand('Runtime.evaluate', params, callback)
}); })
it('fires message event', function (done) { it('fires message event', function (done) {
var url = process.platform != 'win32' ? var url = process.platform != 'win32' ?
'file://' + path.join(fixtures, 'pages', 'a.html') : 'file://' + path.join(fixtures, 'pages', 'a.html') :
'file:///' + path.join(fixtures, 'pages', 'a.html').replace(/\\/g, '/'); 'file:///' + path.join(fixtures, 'pages', 'a.html').replace(/\\/g, '/')
w.webContents.loadURL(url); w.webContents.loadURL(url)
try { try {
w.webContents.debugger.attach(); w.webContents.debugger.attach()
} catch(err) { } catch(err) {
done('unexpected error : ' + err); done('unexpected error : ' + err)
} }
w.webContents.debugger.on('message', function (e, method, params) { w.webContents.debugger.on('message', function (e, method, params) {
if(method == "Console.messageAdded") { if (method == 'Console.messageAdded') {
assert.equal(params.message.type, 'log'); assert.equal(params.message.type, 'log')
assert.equal(params.message.url, url); assert.equal(params.message.url, url)
assert.equal(params.message.text, 'a'); assert.equal(params.message.text, 'a')
w.webContents.debugger.detach(); w.webContents.debugger.detach()
done(); done()
} }
}); })
w.webContents.debugger.sendCommand("Console.enable"); w.webContents.debugger.sendCommand('Console.enable')
}); })
it('returns error message when command fails', function (done) { it('returns error message when command fails', function (done) {
w.webContents.loadURL('about:blank'); w.webContents.loadURL('about:blank')
try { try {
w.webContents.debugger.attach(); w.webContents.debugger.attach()
} catch(err) { } catch(err) {
done('unexpected error : ' + err); done('unexpected error : ' + err)
} }
w.webContents.debugger.sendCommand("Test", function(err) { w.webContents.debugger.sendCommand('Test', function (err) {
assert.equal(err.message, '\'Test\' wasn\'t found'); assert.equal(err.message, "'Test' wasn't found")
w.webContents.debugger.detach(); w.webContents.debugger.detach()
done(); done()
}); })
}); })
}); })
}); })

View file

@ -1,27 +1,27 @@
const assert = require('assert'); const assert = require('assert')
const deprecations = require('electron').deprecations; const deprecations = require('electron').deprecations
describe('deprecations', function () { describe('deprecations', function () {
beforeEach(function () { beforeEach(function () {
deprecations.setHandler(null); deprecations.setHandler(null)
process.throwDeprecation = true; process.throwDeprecation = true
}); })
it('allows a deprecation handler function to be specified', function () { it('allows a deprecation handler function to be specified', function () {
var messages = []; var messages = []
deprecations.setHandler(function (message) { deprecations.setHandler(function (message) {
messages.push(message); messages.push(message)
}); })
require('electron').webFrame.registerUrlSchemeAsSecure('some-scheme'); require('electron').webFrame.registerUrlSchemeAsSecure('some-scheme')
assert.deepEqual(messages, ['registerUrlSchemeAsSecure is deprecated. Use registerURLSchemeAsSecure instead.']); assert.deepEqual(messages, ['registerUrlSchemeAsSecure is deprecated. Use registerURLSchemeAsSecure instead.'])
}); })
it('throws an exception if no deprecation handler is specified', function () { it('throws an exception if no deprecation handler is specified', function () {
assert.throws(function () { assert.throws(function () {
require('electron').webFrame.registerUrlSchemeAsPrivileged('some-scheme'); require('electron').webFrame.registerUrlSchemeAsPrivileged('some-scheme')
}, "registerUrlSchemeAsPrivileged is deprecated. Use registerURLSchemeAsPrivileged instead."); }, 'registerUrlSchemeAsPrivileged is deprecated. Use registerURLSchemeAsPrivileged instead.')
}); })
}); })

View file

@ -1,27 +1,27 @@
const assert = require('assert'); const assert = require('assert')
const desktopCapturer = require('electron').desktopCapturer; const desktopCapturer = require('electron').desktopCapturer
describe('desktopCapturer', function () { describe('desktopCapturer', function () {
it('should return a non-empty array of sources', function (done) { it('should return a non-empty array of sources', function (done) {
desktopCapturer.getSources({ desktopCapturer.getSources({
types: ['window', 'screen'] types: ['window', 'screen']
}, function (error, sources) { }, function (error, sources) {
assert.equal(error, null); assert.equal(error, null)
assert.notEqual(sources.length, 0); assert.notEqual(sources.length, 0)
done(); done()
}); })
}); })
it('does not throw an error when called more than once (regression)', function (done) { it('does not throw an error when called more than once (regression)', function (done) {
var callCount = 0; var callCount = 0
var callback = function (error, sources) { var callback = function (error, sources) {
callCount++; callCount++
assert.equal(error, null); assert.equal(error, null)
assert.notEqual(sources.length, 0); assert.notEqual(sources.length, 0)
if (callCount === 2) done(); if (callCount === 2) done()
}; }
desktopCapturer.getSources({types: ['window', 'screen']}, callback); desktopCapturer.getSources({types: ['window', 'screen']}, callback)
desktopCapturer.getSources({types: ['window', 'screen']}, callback); desktopCapturer.getSources({types: ['window', 'screen']}, callback)
}); })
}); })

View file

@ -1,210 +1,210 @@
'use strict'; 'use strict'
const assert = require('assert'); const assert = require('assert')
const path = require('path'); const path = require('path')
const ipcRenderer = require('electron').ipcRenderer; const ipcRenderer = require('electron').ipcRenderer
const remote = require('electron').remote; const remote = require('electron').remote
const ipcMain = remote.require('electron').ipcMain; const ipcMain = remote.require('electron').ipcMain
const BrowserWindow = remote.require('electron').BrowserWindow; const BrowserWindow = remote.require('electron').BrowserWindow
const comparePaths = function (path1, path2) { const comparePaths = function (path1, path2) {
if (process.platform === 'win32') { if (process.platform === 'win32') {
path1 = path1.toLowerCase(); path1 = path1.toLowerCase()
path2 = path2.toLowerCase(); path2 = path2.toLowerCase()
}
assert.equal(path1, path2)
} }
assert.equal(path1, path2);
};
describe('ipc module', function () { describe('ipc module', function () {
var fixtures = path.join(__dirname, 'fixtures'); var fixtures = path.join(__dirname, 'fixtures')
describe('remote.require', function () { describe('remote.require', function () {
it('should returns same object for the same module', function () { it('should returns same object for the same module', function () {
var dialog1 = remote.require('electron'); var dialog1 = remote.require('electron')
var dialog2 = remote.require('electron'); var dialog2 = remote.require('electron')
assert.equal(dialog1, dialog2); assert.equal(dialog1, dialog2)
}); })
it('should work when object contains id property', function () { it('should work when object contains id property', function () {
var a = remote.require(path.join(fixtures, 'module', 'id.js')); var a = remote.require(path.join(fixtures, 'module', 'id.js'))
assert.equal(a.id, 1127); assert.equal(a.id, 1127)
}); })
it('should search module from the user app', function () { it('should search module from the user app', function () {
comparePaths(path.normalize(remote.process.mainModule.filename), path.resolve(__dirname, 'static', 'main.js')); comparePaths(path.normalize(remote.process.mainModule.filename), path.resolve(__dirname, 'static', 'main.js'))
comparePaths(path.normalize(remote.process.mainModule.paths[0]), path.resolve(__dirname, 'static', 'node_modules')); comparePaths(path.normalize(remote.process.mainModule.paths[0]), path.resolve(__dirname, 'static', 'node_modules'))
}); })
}); })
describe('remote.createFunctionWithReturnValue', function () { describe('remote.createFunctionWithReturnValue', function () {
it('should be called in browser synchronously', function () { it('should be called in browser synchronously', function () {
var buf = new Buffer('test'); var buf = new Buffer('test')
var call = remote.require(path.join(fixtures, 'module', 'call.js')); var call = remote.require(path.join(fixtures, 'module', 'call.js'))
var result = call.call(remote.createFunctionWithReturnValue(buf)); var result = call.call(remote.createFunctionWithReturnValue(buf))
assert.equal(result.constructor.name, 'Buffer'); assert.equal(result.constructor.name, 'Buffer')
}); })
}); })
describe('remote object in renderer', function () { describe('remote object in renderer', function () {
it('can change its properties', function () { it('can change its properties', function () {
var property = remote.require(path.join(fixtures, 'module', 'property.js')); var property = remote.require(path.join(fixtures, 'module', 'property.js'))
assert.equal(property.property, 1127); assert.equal(property.property, 1127)
property.property = 1007; property.property = 1007
assert.equal(property.property, 1007); assert.equal(property.property, 1007)
var property2 = remote.require(path.join(fixtures, 'module', 'property.js')); var property2 = remote.require(path.join(fixtures, 'module', 'property.js'))
assert.equal(property2.property, 1007); assert.equal(property2.property, 1007)
property.property = 1127; property.property = 1127
}); })
it('can construct an object from its member', function () { it('can construct an object from its member', function () {
var call = remote.require(path.join(fixtures, 'module', 'call.js')); var call = remote.require(path.join(fixtures, 'module', 'call.js'))
var obj = new call.constructor; var obj = new call.constructor
assert.equal(obj.test, 'test'); assert.equal(obj.test, 'test')
}); })
it('can reassign and delete its member functions', function () { it('can reassign and delete its member functions', function () {
var remoteFunctions = remote.require(path.join(fixtures, 'module', 'function.js')); var remoteFunctions = remote.require(path.join(fixtures, 'module', 'function.js'))
assert.equal(remoteFunctions.aFunction(), 1127); assert.equal(remoteFunctions.aFunction(), 1127)
remoteFunctions.aFunction = function () { return 1234; }; remoteFunctions.aFunction = function () { return 1234; }
assert.equal(remoteFunctions.aFunction(), 1234); assert.equal(remoteFunctions.aFunction(), 1234)
assert.equal(delete remoteFunctions.aFunction, true); assert.equal(delete remoteFunctions.aFunction, true)
}); })
}); })
describe('remote value in browser', function () { describe('remote value in browser', function () {
var print = path.join(fixtures, 'module', 'print_name.js'); var print = path.join(fixtures, 'module', 'print_name.js')
it('keeps its constructor name for objects', function () { it('keeps its constructor name for objects', function () {
var buf = new Buffer('test'); var buf = new Buffer('test')
var print_name = remote.require(print); var print_name = remote.require(print)
assert.equal(print_name.print(buf), 'Buffer'); assert.equal(print_name.print(buf), 'Buffer')
}); })
it('supports instanceof Date', function () { it('supports instanceof Date', function () {
var now = new Date(); var now = new Date()
var print_name = remote.require(print); var print_name = remote.require(print)
assert.equal(print_name.print(now), 'Date'); assert.equal(print_name.print(now), 'Date')
assert.deepEqual(print_name.echo(now), now); assert.deepEqual(print_name.echo(now), now)
}); })
}); })
describe('remote promise', function () { describe('remote promise', function () {
it('can be used as promise in each side', function (done) { it('can be used as promise in each side', function (done) {
var promise = remote.require(path.join(fixtures, 'module', 'promise.js')); var promise = remote.require(path.join(fixtures, 'module', 'promise.js'))
promise.twicePromise(Promise.resolve(1234)).then(function (value) { promise.twicePromise(Promise.resolve(1234)).then(function (value) {
assert.equal(value, 2468); assert.equal(value, 2468)
done(); done()
}); })
}); })
}); })
describe('remote webContents', function () { describe('remote webContents', function () {
it('can return same object with different getters', function () { it('can return same object with different getters', function () {
var contents1 = remote.getCurrentWindow().webContents; var contents1 = remote.getCurrentWindow().webContents
var contents2 = remote.getCurrentWebContents(); var contents2 = remote.getCurrentWebContents()
assert(contents1 == contents2); assert(contents1 == contents2)
}); })
}); })
describe('remote class', function () { describe('remote class', function () {
let cl = remote.require(path.join(fixtures, 'module', 'class.js')); let cl = remote.require(path.join(fixtures, 'module', 'class.js'))
let base = cl.base; let base = cl.base
let derived = cl.derived; let derived = cl.derived
it('can get methods', function () { it('can get methods', function () {
assert.equal(base.method(), 'method'); assert.equal(base.method(), 'method')
}); })
it('can get properties', function () { it('can get properties', function () {
assert.equal(base.readonly, 'readonly'); assert.equal(base.readonly, 'readonly')
}); })
it('can change properties', function () { it('can change properties', function () {
assert.equal(base.value, 'old'); assert.equal(base.value, 'old')
base.value = 'new'; base.value = 'new'
assert.equal(base.value, 'new'); assert.equal(base.value, 'new')
base.value = 'old'; base.value = 'old'
}); })
it('has unenumerable methods', function () { it('has unenumerable methods', function () {
assert(!base.hasOwnProperty('method')); assert(!base.hasOwnProperty('method'))
assert(Object.getPrototypeOf(base).hasOwnProperty('method')); assert(Object.getPrototypeOf(base).hasOwnProperty('method'))
}); })
it('keeps prototype chain in derived class', function () { it('keeps prototype chain in derived class', function () {
assert.equal(derived.method(), 'method'); assert.equal(derived.method(), 'method')
assert.equal(derived.readonly, 'readonly'); assert.equal(derived.readonly, 'readonly')
assert(!derived.hasOwnProperty('method')); assert(!derived.hasOwnProperty('method'))
let proto = Object.getPrototypeOf(derived); let proto = Object.getPrototypeOf(derived)
assert(!proto.hasOwnProperty('method')); assert(!proto.hasOwnProperty('method'))
assert(Object.getPrototypeOf(proto).hasOwnProperty('method')); assert(Object.getPrototypeOf(proto).hasOwnProperty('method'))
}); })
}); })
describe('ipc.sender.send', function () { describe('ipc.sender.send', function () {
it('should work when sending an object containing id property', function (done) { it('should work when sending an object containing id property', function (done) {
var obj = { var obj = {
id: 1, id: 1,
name: 'ly' name: 'ly'
}; }
ipcRenderer.once('message', function (event, message) { ipcRenderer.once('message', function (event, message) {
assert.deepEqual(message, obj); assert.deepEqual(message, obj)
done(); done()
}); })
ipcRenderer.send('message', obj); ipcRenderer.send('message', obj)
}); })
it('can send instance of Date', function (done) { it('can send instance of Date', function (done) {
const currentDate = new Date(); const currentDate = new Date()
ipcRenderer.once('message', function (event, value) { ipcRenderer.once('message', function (event, value) {
assert.equal(value, currentDate.toISOString()); assert.equal(value, currentDate.toISOString())
done(); done()
}); })
ipcRenderer.send('message', currentDate); ipcRenderer.send('message', currentDate)
}); })
}); })
describe('ipc.sendSync', function () { describe('ipc.sendSync', function () {
it('can be replied by setting event.returnValue', function () { it('can be replied by setting event.returnValue', function () {
var msg = ipcRenderer.sendSync('echo', 'test'); var msg = ipcRenderer.sendSync('echo', 'test')
assert.equal(msg, 'test'); assert.equal(msg, 'test')
}); })
it('does not crash when reply is not sent and browser is destroyed', function (done) { it('does not crash when reply is not sent and browser is destroyed', function (done) {
this.timeout(10000); this.timeout(10000)
var w = new BrowserWindow({ var w = new BrowserWindow({
show: false show: false
}); })
ipcMain.once('send-sync-message', function (event) { ipcMain.once('send-sync-message', function (event) {
event.returnValue = null; event.returnValue = null
w.destroy(); w.destroy()
done(); done()
}); })
w.loadURL('file://' + path.join(fixtures, 'api', 'send-sync-message.html')); w.loadURL('file://' + path.join(fixtures, 'api', 'send-sync-message.html'))
}); })
}); })
describe('remote listeners', function () { describe('remote listeners', function () {
var w = null; var w = null
afterEach(function () { afterEach(function () {
w.destroy(); w.destroy()
}); })
it('can be added and removed correctly', function () { it('can be added and removed correctly', function () {
w = new BrowserWindow({ w = new BrowserWindow({
show: false show: false
}); })
var listener = function() {}; var listener = function () {}
w.on('test', listener); w.on('test', listener)
assert.equal(w.listenerCount('test'), 1); assert.equal(w.listenerCount('test'), 1)
w.removeListener('test', listener); w.removeListener('test', listener)
assert.equal(w.listenerCount('test'), 0); assert.equal(w.listenerCount('test'), 0)
}); })
}); })
}); })

View file

@ -1,10 +1,10 @@
const assert = require('assert'); const assert = require('assert')
const remote = require('electron').remote; const remote = require('electron').remote
const ipcRenderer = require('electron').ipcRenderer; const ipcRenderer = require('electron').ipcRenderer
const Menu = remote.require('electron').Menu; const Menu = remote.require('electron').Menu
const MenuItem = remote.require('electron').MenuItem; const MenuItem = remote.require('electron').MenuItem
describe('menu module', function () { describe('menu module', function () {
describe('Menu.buildFromTemplate', function () { describe('Menu.buildFromTemplate', function () {
@ -14,12 +14,12 @@ describe('menu module', function() {
label: 'text', label: 'text',
extra: 'field' extra: 'field'
} }
]); ])
assert.equal(menu.items[0].extra, 'field'); assert.equal(menu.items[0].extra, 'field')
}); })
it('does not modify the specified template', function () { it('does not modify the specified template', function () {
var template = ipcRenderer.sendSync('eval', "var template = [{label: 'text', submenu: [{label: 'sub'}]}];\nrequire('electron').Menu.buildFromTemplate(template);\ntemplate;"); var template = ipcRenderer.sendSync('eval', "var template = [{label: 'text', submenu: [{label: 'sub'}]}];\nrequire('electron').Menu.buildFromTemplate(template);\ntemplate;")
assert.deepStrictEqual(template, [ assert.deepStrictEqual(template, [
{ {
label: 'text', label: 'text',
@ -29,8 +29,8 @@ describe('menu module', function() {
} }
] ]
} }
]); ])
}); })
it('does not throw exceptions for undefined/null values', function () { it('does not throw exceptions for undefined/null values', function () {
assert.doesNotThrow(function () { assert.doesNotThrow(function () {
@ -43,9 +43,9 @@ describe('menu module', function() {
label: 'text again', label: 'text again',
accelerator: null accelerator: null
} }
]); ])
}); })
}); })
describe('Menu.buildFromTemplate should reorder based on item position specifiers', function () { describe('Menu.buildFromTemplate should reorder based on item position specifiers', function () {
it('should position before existing item', function () { it('should position before existing item', function () {
@ -61,11 +61,11 @@ describe('menu module', function() {
id: '1', id: '1',
position: 'before=2' position: 'before=2'
} }
]); ])
assert.equal(menu.items[0].label, '1'); assert.equal(menu.items[0].label, '1')
assert.equal(menu.items[1].label, '2'); assert.equal(menu.items[1].label, '2')
assert.equal(menu.items[2].label, '3'); assert.equal(menu.items[2].label, '3')
}); })
it('should position after existing item', function () { it('should position after existing item', function () {
var menu = Menu.buildFromTemplate([ var menu = Menu.buildFromTemplate([
@ -80,11 +80,11 @@ describe('menu module', function() {
id: '2', id: '2',
position: 'after=1' position: 'after=1'
} }
]); ])
assert.equal(menu.items[0].label, '1'); assert.equal(menu.items[0].label, '1')
assert.equal(menu.items[1].label, '2'); assert.equal(menu.items[1].label, '2')
assert.equal(menu.items[2].label, '3'); assert.equal(menu.items[2].label, '3')
}); })
it('should position at endof existing separator groups', function () { it('should position at endof existing separator groups', function () {
var menu = Menu.buildFromTemplate([ var menu = Menu.buildFromTemplate([
@ -119,16 +119,16 @@ describe('menu module', function() {
id: '3', id: '3',
position: 'endof=numbers' position: 'endof=numbers'
} }
]); ])
assert.equal(menu.items[0].id, 'numbers'); assert.equal(menu.items[0].id, 'numbers')
assert.equal(menu.items[1].label, '1'); assert.equal(menu.items[1].label, '1')
assert.equal(menu.items[2].label, '2'); assert.equal(menu.items[2].label, '2')
assert.equal(menu.items[3].label, '3'); assert.equal(menu.items[3].label, '3')
assert.equal(menu.items[4].id, 'letters'); assert.equal(menu.items[4].id, 'letters')
assert.equal(menu.items[5].label, 'a'); assert.equal(menu.items[5].label, 'a')
assert.equal(menu.items[6].label, 'b'); assert.equal(menu.items[6].label, 'b')
assert.equal(menu.items[7].label, 'c'); assert.equal(menu.items[7].label, 'c')
}); })
it('should create separator group if endof does not reference existing separator group', function () { it('should create separator group if endof does not reference existing separator group', function () {
var menu = Menu.buildFromTemplate([ var menu = Menu.buildFromTemplate([
@ -157,16 +157,16 @@ describe('menu module', function() {
id: '3', id: '3',
position: 'endof=numbers' position: 'endof=numbers'
} }
]); ])
assert.equal(menu.items[0].id, 'letters'); assert.equal(menu.items[0].id, 'letters')
assert.equal(menu.items[1].label, 'a'); assert.equal(menu.items[1].label, 'a')
assert.equal(menu.items[2].label, 'b'); assert.equal(menu.items[2].label, 'b')
assert.equal(menu.items[3].label, 'c'); assert.equal(menu.items[3].label, 'c')
assert.equal(menu.items[4].id, 'numbers'); assert.equal(menu.items[4].id, 'numbers')
assert.equal(menu.items[5].label, '1'); assert.equal(menu.items[5].label, '1')
assert.equal(menu.items[6].label, '2'); assert.equal(menu.items[6].label, '2')
assert.equal(menu.items[7].label, '3'); assert.equal(menu.items[7].label, '3')
}); })
it('should continue inserting items at next index when no specifier is present', function () { it('should continue inserting items at next index when no specifier is present', function () {
var menu = Menu.buildFromTemplate([ var menu = Menu.buildFromTemplate([
@ -187,15 +187,15 @@ describe('menu module', function() {
label: '3', label: '3',
id: '3' id: '3'
} }
]); ])
assert.equal(menu.items[0].label, '1'); assert.equal(menu.items[0].label, '1')
assert.equal(menu.items[1].label, '2'); assert.equal(menu.items[1].label, '2')
assert.equal(menu.items[2].label, '3'); assert.equal(menu.items[2].label, '3')
assert.equal(menu.items[3].label, '4'); assert.equal(menu.items[3].label, '4')
assert.equal(menu.items[4].label, '5'); assert.equal(menu.items[4].label, '5')
}); })
}); })
}); })
describe('Menu.insert', function () { describe('Menu.insert', function () {
it('should store item in @items by its index', function () { it('should store item in @items by its index', function () {
@ -207,17 +207,17 @@ describe('menu module', function() {
}, { }, {
label: '3' label: '3'
} }
]); ])
var item = new MenuItem({ var item = new MenuItem({
label: 'inserted' label: 'inserted'
}); })
menu.insert(1, item); menu.insert(1, item)
assert.equal(menu.items[0].label, '1'); assert.equal(menu.items[0].label, '1')
assert.equal(menu.items[1].label, 'inserted'); assert.equal(menu.items[1].label, 'inserted')
assert.equal(menu.items[2].label, '2'); assert.equal(menu.items[2].label, '2')
assert.equal(menu.items[3].label, '3'); assert.equal(menu.items[3].label, '3')
}); })
}); })
describe('MenuItem.click', function () { describe('MenuItem.click', function () {
it('should be called with the item object passed', function (done) { it('should be called with the item object passed', function (done) {
@ -225,15 +225,15 @@ describe('menu module', function() {
{ {
label: 'text', label: 'text',
click: function (item) { click: function (item) {
assert.equal(item.constructor.name, 'MenuItem'); assert.equal(item.constructor.name, 'MenuItem')
assert.equal(item.label, 'text'); assert.equal(item.label, 'text')
done(); done()
} }
} }
]); ])
menu.delegate.executeCommand(menu.items[0].commandId); menu.delegate.executeCommand(menu.items[0].commandId)
}); })
}); })
describe('MenuItem with checked property', function () { describe('MenuItem with checked property', function () {
it('clicking an checkbox item should flip the checked property', function () { it('clicking an checkbox item should flip the checked property', function () {
@ -242,11 +242,11 @@ describe('menu module', function() {
label: 'text', label: 'text',
type: 'checkbox' type: 'checkbox'
} }
]); ])
assert.equal(menu.items[0].checked, false); assert.equal(menu.items[0].checked, false)
menu.delegate.executeCommand(menu.items[0].commandId); menu.delegate.executeCommand(menu.items[0].commandId)
assert.equal(menu.items[0].checked, true); assert.equal(menu.items[0].checked, true)
}); })
it('clicking an radio item should always make checked property true', function () { it('clicking an radio item should always make checked property true', function () {
var menu = Menu.buildFromTemplate([ var menu = Menu.buildFromTemplate([
@ -254,109 +254,109 @@ describe('menu module', function() {
label: 'text', label: 'text',
type: 'radio' type: 'radio'
} }
]); ])
menu.delegate.executeCommand(menu.items[0].commandId); menu.delegate.executeCommand(menu.items[0].commandId)
assert.equal(menu.items[0].checked, true); assert.equal(menu.items[0].checked, true)
menu.delegate.executeCommand(menu.items[0].commandId); menu.delegate.executeCommand(menu.items[0].commandId)
assert.equal(menu.items[0].checked, true); assert.equal(menu.items[0].checked, true)
}); })
it('at least have one item checked in each group', function () { it('at least have one item checked in each group', function () {
var i, j, k, menu, template; var i, j, k, menu, template
template = []; template = []
for (i = j = 0; j <= 10; i = ++j) { for (i = j = 0; j <= 10; i = ++j) {
template.push({ template.push({
label: "" + i, label: '' + i,
type: 'radio' type: 'radio'
}); })
} }
template.push({ template.push({
type: 'separator' type: 'separator'
}); })
for (i = k = 12; k <= 20; i = ++k) { for (i = k = 12; k <= 20; i = ++k) {
template.push({ template.push({
label: "" + i, label: '' + i,
type: 'radio' type: 'radio'
}); })
} }
menu = Menu.buildFromTemplate(template); menu = Menu.buildFromTemplate(template)
menu.delegate.menuWillShow(); menu.delegate.menuWillShow()
assert.equal(menu.items[0].checked, true); assert.equal(menu.items[0].checked, true)
assert.equal(menu.items[12].checked, true); assert.equal(menu.items[12].checked, true)
}); })
it('should assign groupId automatically', function () { it('should assign groupId automatically', function () {
var groupId, i, j, k, l, m, menu, template; var groupId, i, j, k, l, m, menu, template
template = []; template = []
for (i = j = 0; j <= 10; i = ++j) { for (i = j = 0; j <= 10; i = ++j) {
template.push({ template.push({
label: "" + i, label: '' + i,
type: 'radio' type: 'radio'
}); })
} }
template.push({ template.push({
type: 'separator' type: 'separator'
}); })
for (i = k = 12; k <= 20; i = ++k) { for (i = k = 12; k <= 20; i = ++k) {
template.push({ template.push({
label: "" + i, label: '' + i,
type: 'radio' type: 'radio'
}); })
} }
menu = Menu.buildFromTemplate(template); menu = Menu.buildFromTemplate(template)
groupId = menu.items[0].groupId; groupId = menu.items[0].groupId
for (i = l = 0; l <= 10; i = ++l) { for (i = l = 0; l <= 10; i = ++l) {
assert.equal(menu.items[i].groupId, groupId); assert.equal(menu.items[i].groupId, groupId)
} }
for (i = m = 12; m <= 20; i = ++m) { for (i = m = 12; m <= 20; i = ++m) {
assert.equal(menu.items[i].groupId, groupId + 1); assert.equal(menu.items[i].groupId, groupId + 1)
} }
}); })
it("setting 'checked' should flip other items' 'checked' property", function () { it("setting 'checked' should flip other items' 'checked' property", function () {
var i, j, k, l, m, menu, n, o, p, q, template; var i, j, k, l, m, menu, n, o, p, q, template
template = []; template = []
for (i = j = 0; j <= 10; i = ++j) { for (i = j = 0; j <= 10; i = ++j) {
template.push({ template.push({
label: "" + i, label: '' + i,
type: 'radio' type: 'radio'
}); })
} }
template.push({ template.push({
type: 'separator' type: 'separator'
}); })
for (i = k = 12; k <= 20; i = ++k) { for (i = k = 12; k <= 20; i = ++k) {
template.push({ template.push({
label: "" + i, label: '' + i,
type: 'radio' type: 'radio'
}); })
} }
menu = Menu.buildFromTemplate(template); menu = Menu.buildFromTemplate(template)
for (i = l = 0; l <= 10; i = ++l) { for (i = l = 0; l <= 10; i = ++l) {
assert.equal(menu.items[i].checked, false); assert.equal(menu.items[i].checked, false)
} }
menu.items[0].checked = true; menu.items[0].checked = true
assert.equal(menu.items[0].checked, true); assert.equal(menu.items[0].checked, true)
for (i = m = 1; m <= 10; i = ++m) { for (i = m = 1; m <= 10; i = ++m) {
assert.equal(menu.items[i].checked, false); assert.equal(menu.items[i].checked, false)
} }
menu.items[10].checked = true; menu.items[10].checked = true
assert.equal(menu.items[10].checked, true); assert.equal(menu.items[10].checked, true)
for (i = n = 0; n <= 9; i = ++n) { for (i = n = 0; n <= 9; i = ++n) {
assert.equal(menu.items[i].checked, false); assert.equal(menu.items[i].checked, false)
} }
for (i = o = 12; o <= 20; i = ++o) { for (i = o = 12; o <= 20; i = ++o) {
assert.equal(menu.items[i].checked, false); assert.equal(menu.items[i].checked, false)
} }
menu.items[12].checked = true; menu.items[12].checked = true
assert.equal(menu.items[10].checked, true); assert.equal(menu.items[10].checked, true)
for (i = p = 0; p <= 9; i = ++p) { for (i = p = 0; p <= 9; i = ++p) {
assert.equal(menu.items[i].checked, false); assert.equal(menu.items[i].checked, false)
} }
assert.equal(menu.items[12].checked, true); assert.equal(menu.items[12].checked, true)
for (i = q = 13; q <= 20; i = ++q) { for (i = q = 13; q <= 20; i = ++q) {
assert.equal(menu.items[i].checked, false); assert.equal(menu.items[i].checked, false)
} }
}); })
}); })
}); })

View file

@ -1,51 +1,51 @@
'use strict'; 'use strict'
const assert = require('assert'); const assert = require('assert')
const nativeImage = require('electron').nativeImage; const nativeImage = require('electron').nativeImage
const path = require('path'); const path = require('path')
describe('nativeImage module', () => { describe('nativeImage module', () => {
describe('createFromPath(path)', () => { describe('createFromPath(path)', () => {
it('returns an empty image for invalid paths', () => { it('returns an empty image for invalid paths', () => {
assert(nativeImage.createFromPath('').isEmpty()); assert(nativeImage.createFromPath('').isEmpty())
assert(nativeImage.createFromPath('does-not-exist.png').isEmpty()); assert(nativeImage.createFromPath('does-not-exist.png').isEmpty())
}); })
it('loads images from paths relative to the current working directory', () => { it('loads images from paths relative to the current working directory', () => {
const imagePath = `.${path.sep}${path.join('spec', 'fixtures', 'assets', 'logo.png')}`; const imagePath = `.${path.sep}${path.join('spec', 'fixtures', 'assets', 'logo.png')}`
const image = nativeImage.createFromPath(imagePath); const image = nativeImage.createFromPath(imagePath)
assert(!image.isEmpty()); assert(!image.isEmpty())
assert.equal(image.getSize().height, 190); assert.equal(image.getSize().height, 190)
assert.equal(image.getSize().width, 538); assert.equal(image.getSize().width, 538)
}); })
it('loads images from paths with `.` segments', () => { it('loads images from paths with `.` segments', () => {
const imagePath = `${path.join(__dirname, 'fixtures')}${path.sep}.${path.sep}${path.join('assets', 'logo.png')}`; const imagePath = `${path.join(__dirname, 'fixtures')}${path.sep}.${path.sep}${path.join('assets', 'logo.png')}`
const image = nativeImage.createFromPath(imagePath); const image = nativeImage.createFromPath(imagePath)
assert(!image.isEmpty()); assert(!image.isEmpty())
assert.equal(image.getSize().height, 190); assert.equal(image.getSize().height, 190)
assert.equal(image.getSize().width, 538); assert.equal(image.getSize().width, 538)
}); })
it('loads images from paths with `..` segments', () => { it('loads images from paths with `..` segments', () => {
const imagePath = `${path.join(__dirname, 'fixtures', 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`; const imagePath = `${path.join(__dirname, 'fixtures', 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`
const image = nativeImage.createFromPath(imagePath); const image = nativeImage.createFromPath(imagePath)
assert(!image.isEmpty()); assert(!image.isEmpty())
assert.equal(image.getSize().height, 190); assert.equal(image.getSize().height, 190)
assert.equal(image.getSize().width, 538); assert.equal(image.getSize().width, 538)
}); })
it('Gets an NSImage pointer on OS X', () => { it('Gets an NSImage pointer on OS X', () => {
if (process.platform !== 'darwin') return; if (process.platform !== 'darwin') return
const imagePath = `${path.join(__dirname, 'fixtures', 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`; const imagePath = `${path.join(__dirname, 'fixtures', 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`
const image = nativeImage.createFromPath(imagePath); const image = nativeImage.createFromPath(imagePath)
const nsimage = image.getNativeHandle(); const nsimage = image.getNativeHandle()
assert.equal(nsimage.length, 8); assert.equal(nsimage.length, 8)
// If all bytes are null, that's Bad // If all bytes are null, that's Bad
assert.equal(nsimage.reduce((acc,x) => acc || (x != 0), false), true); assert.equal(nsimage.reduce((acc, x) => acc || (x != 0), false), true)
}); })
}); })
}); })

File diff suppressed because it is too large Load diff

View file

@ -1,21 +1,21 @@
const assert = require('assert'); const assert = require('assert')
const screen = require('electron').screen; const screen = require('electron').screen
describe('screen module', function () { describe('screen module', function () {
describe('screen.getCursorScreenPoint()', function () { describe('screen.getCursorScreenPoint()', function () {
it('returns a point object', function () { it('returns a point object', function () {
var point = screen.getCursorScreenPoint(); var point = screen.getCursorScreenPoint()
assert.equal(typeof point.x, 'number'); assert.equal(typeof point.x, 'number')
assert.equal(typeof point.y, 'number'); assert.equal(typeof point.y, 'number')
}); })
}); })
describe('screen.getPrimaryDisplay()', function () { describe('screen.getPrimaryDisplay()', function () {
it('returns a display object', function () { it('returns a display object', function () {
var display = screen.getPrimaryDisplay(); var display = screen.getPrimaryDisplay()
assert.equal(typeof display.scaleFactor, 'number'); assert.equal(typeof display.scaleFactor, 'number')
assert(display.size.width > 0); assert(display.size.width > 0)
assert(display.size.height > 0); assert(display.size.height > 0)
}); })
}); })
}); })

View file

@ -1,67 +1,67 @@
const assert = require('assert'); const assert = require('assert')
const http = require('http'); const http = require('http')
const path = require('path'); const path = require('path')
const fs = require('fs'); const fs = require('fs')
const ipcRenderer = require('electron').ipcRenderer; const ipcRenderer = require('electron').ipcRenderer
const remote = require('electron').remote; const remote = require('electron').remote
const ipcMain = remote.ipcMain; const ipcMain = remote.ipcMain
const session = remote.session; const session = remote.session
const BrowserWindow = remote.BrowserWindow; const BrowserWindow = remote.BrowserWindow
describe('session module', function () { describe('session module', function () {
this.timeout(10000); this.timeout(10000)
var fixtures = path.resolve(__dirname, 'fixtures'); var fixtures = path.resolve(__dirname, 'fixtures')
var w = null; var w = null
var url = "http://127.0.0.1"; var url = 'http://127.0.0.1'
beforeEach(function () { beforeEach(function () {
w = new BrowserWindow({ w = new BrowserWindow({
show: false, show: false,
width: 400, width: 400,
height: 400 height: 400
}); })
}); })
afterEach(function () { afterEach(function () {
w.destroy(); w.destroy()
}); })
describe('session.cookies', function () { describe('session.cookies', function () {
it('should get cookies', function (done) { it('should get cookies', function (done) {
var server = http.createServer(function (req, res) { var server = http.createServer(function (req, res) {
res.setHeader('Set-Cookie', ['0=0']); res.setHeader('Set-Cookie', ['0=0'])
res.end('finished'); res.end('finished')
server.close(); server.close()
}); })
server.listen(0, '127.0.0.1', function () { server.listen(0, '127.0.0.1', function () {
var port = server.address().port; var port = server.address().port
w.loadURL(url + ":" + port); w.loadURL(url + ':' + port)
w.webContents.on('did-finish-load', function () { w.webContents.on('did-finish-load', function () {
w.webContents.session.cookies.get({ w.webContents.session.cookies.get({
url: url url: url
}, function (error, list) { }, function (error, list) {
var cookie, i, len; var cookie, i, len
if (error) { if (error) {
return done(error); return done(error)
} }
for (i = 0, len = list.length; i < len; i++) { for (i = 0, len = list.length; i < len; i++) {
cookie = list[i]; cookie = list[i]
if (cookie.name === '0') { if (cookie.name === '0') {
if (cookie.value === '0') { if (cookie.value === '0') {
return done(); return done()
} else { } else {
return done("cookie value is " + cookie.value + " while expecting 0"); return done('cookie value is ' + cookie.value + ' while expecting 0')
} }
} }
} }
done('Can not find cookie'); done('Can not find cookie')
}); })
}); })
}); })
}); })
it('should over-write the existent cookie', function (done) { it('should over-write the existent cookie', function (done) {
session.defaultSession.cookies.set({ session.defaultSession.cookies.set({
@ -70,29 +70,29 @@ describe('session module', function() {
value: '1' value: '1'
}, function (error) { }, function (error) {
if (error) { if (error) {
return done(error); return done(error)
} }
session.defaultSession.cookies.get({ session.defaultSession.cookies.get({
url: url url: url
}, function (error, list) { }, function (error, list) {
var cookie, i, len; var cookie, i, len
if (error) { if (error) {
return done(error); return done(error)
} }
for (i = 0, len = list.length; i < len; i++) { for (i = 0, len = list.length; i < len; i++) {
cookie = list[i]; cookie = list[i]
if (cookie.name === '1') { if (cookie.name === '1') {
if (cookie.value === '1') { if (cookie.value === '1') {
return done(); return done()
} else { } else {
return done("cookie value is " + cookie.value + " while expecting 1"); return done('cookie value is ' + cookie.value + ' while expecting 1')
} }
} }
} }
done('Can not find cookie'); done('Can not find cookie')
}); })
}); })
}); })
it('should remove cookies', function (done) { it('should remove cookies', function (done) {
session.defaultSession.cookies.set({ session.defaultSession.cookies.set({
@ -101,165 +101,165 @@ describe('session module', function() {
value: '2' value: '2'
}, function (error) { }, function (error) {
if (error) { if (error) {
return done(error); return done(error)
} }
session.defaultSession.cookies.remove(url, '2', function () { session.defaultSession.cookies.remove(url, '2', function () {
session.defaultSession.cookies.get({ session.defaultSession.cookies.get({
url: url url: url
}, function (error, list) { }, function (error, list) {
var cookie, i, len; var cookie, i, len
if (error) { if (error) {
return done(error); return done(error)
} }
for (i = 0, len = list.length; i < len; i++) { for (i = 0, len = list.length; i < len; i++) {
cookie = list[i]; cookie = list[i]
if (cookie.name === '2') { if (cookie.name === '2') {
return done('Cookie not deleted'); return done('Cookie not deleted')
} }
} }
done(); done()
}); })
}); })
}); })
}); })
}); })
describe('session.clearStorageData(options)', function () { describe('session.clearStorageData(options)', function () {
fixtures = path.resolve(__dirname, 'fixtures'); fixtures = path.resolve(__dirname, 'fixtures')
it('clears localstorage data', function (done) { it('clears localstorage data', function (done) {
ipcMain.on('count', function (event, count) { ipcMain.on('count', function (event, count) {
ipcMain.removeAllListeners('count'); ipcMain.removeAllListeners('count')
assert(!count); assert(!count)
done(); done()
}); })
w.loadURL('file://' + path.join(fixtures, 'api', 'localstorage.html')); w.loadURL('file://' + path.join(fixtures, 'api', 'localstorage.html'))
w.webContents.on('did-finish-load', function () { w.webContents.on('did-finish-load', function () {
var options = { var options = {
origin: "file://", origin: 'file://',
storages: ['localstorage'], storages: ['localstorage'],
quotas: ['persistent'] quotas: ['persistent']
}; }
w.webContents.session.clearStorageData(options, function () { w.webContents.session.clearStorageData(options, function () {
w.webContents.send('getcount'); w.webContents.send('getcount')
}); })
}); })
}); })
}); })
describe('session will-download event', function () { describe('session will-download event', function () {
var w = null; var w = null
beforeEach(function () { beforeEach(function () {
w = new BrowserWindow({ w = new BrowserWindow({
show: false, show: false,
width: 400, width: 400,
height: 400 height: 400
}); })
}); })
afterEach(function () { afterEach(function () {
w.destroy(); w.destroy()
}); })
it('can cancel default download behavior', function (done) { it('can cancel default download behavior', function (done) {
const mockFile = new Buffer(1024); const mockFile = new Buffer(1024)
const contentDisposition = 'inline; filename="mockFile.txt"'; const contentDisposition = 'inline; filename="mockFile.txt"'
const downloadServer = http.createServer(function (req, res) { const downloadServer = http.createServer(function (req, res) {
res.writeHead(200, { res.writeHead(200, {
'Content-Length': mockFile.length, 'Content-Length': mockFile.length,
'Content-Type': 'application/plain', 'Content-Type': 'application/plain',
'Content-Disposition': contentDisposition 'Content-Disposition': contentDisposition
}); })
res.end(mockFile); res.end(mockFile)
downloadServer.close(); downloadServer.close()
}); })
downloadServer.listen(0, '127.0.0.1', function () { downloadServer.listen(0, '127.0.0.1', function () {
const port = downloadServer.address().port; const port = downloadServer.address().port
const url = "http://127.0.0.1:" + port + '/'; const url = 'http://127.0.0.1:' + port + '/'
ipcRenderer.sendSync('set-download-option', false, true); ipcRenderer.sendSync('set-download-option', false, true)
w.loadURL(url); w.loadURL(url)
ipcRenderer.once('download-error', function (event, downloadUrl, filename, error) { ipcRenderer.once('download-error', function (event, downloadUrl, filename, error) {
assert.equal(downloadUrl, url); assert.equal(downloadUrl, url)
assert.equal(filename, 'mockFile.txt'); assert.equal(filename, 'mockFile.txt')
assert.equal(error, 'Object has been destroyed'); assert.equal(error, 'Object has been destroyed')
done(); done()
}); })
}); })
}); })
}); })
describe('DownloadItem', function () { describe('DownloadItem', function () {
var mockPDF = new Buffer(1024 * 1024 * 5); var mockPDF = new Buffer(1024 * 1024 * 5)
var contentDisposition = 'inline; filename="mock.pdf"'; var contentDisposition = 'inline; filename="mock.pdf"'
var downloadFilePath = path.join(fixtures, 'mock.pdf'); var downloadFilePath = path.join(fixtures, 'mock.pdf')
var downloadServer = http.createServer(function (req, res) { var downloadServer = http.createServer(function (req, res) {
res.writeHead(200, { res.writeHead(200, {
'Content-Length': mockPDF.length, 'Content-Length': mockPDF.length,
'Content-Type': 'application/pdf', 'Content-Type': 'application/pdf',
'Content-Disposition': contentDisposition 'Content-Disposition': contentDisposition
}); })
res.end(mockPDF); res.end(mockPDF)
downloadServer.close(); downloadServer.close()
}); })
var assertDownload = function (event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename, port) { var assertDownload = function (event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename, port) {
assert.equal(state, 'completed'); assert.equal(state, 'completed')
assert.equal(filename, 'mock.pdf'); assert.equal(filename, 'mock.pdf')
assert.equal(url, "http://127.0.0.1:" + port + "/"); assert.equal(url, 'http://127.0.0.1:' + port + '/')
assert.equal(mimeType, 'application/pdf'); assert.equal(mimeType, 'application/pdf')
assert.equal(receivedBytes, mockPDF.length); assert.equal(receivedBytes, mockPDF.length)
assert.equal(totalBytes, mockPDF.length); assert.equal(totalBytes, mockPDF.length)
assert.equal(disposition, contentDisposition); assert.equal(disposition, contentDisposition)
assert(fs.existsSync(downloadFilePath)); assert(fs.existsSync(downloadFilePath))
fs.unlinkSync(downloadFilePath); fs.unlinkSync(downloadFilePath)
}; }
it('can download using BrowserWindow.loadURL', function (done) { it('can download using BrowserWindow.loadURL', function (done) {
downloadServer.listen(0, '127.0.0.1', function () { downloadServer.listen(0, '127.0.0.1', function () {
var port = downloadServer.address().port; var port = downloadServer.address().port
ipcRenderer.sendSync('set-download-option', false, false); ipcRenderer.sendSync('set-download-option', false, false)
w.loadURL(url + ":" + port); w.loadURL(url + ':' + port)
ipcRenderer.once('download-done', function (event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename) { ipcRenderer.once('download-done', function (event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename) {
assertDownload(event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename, port); assertDownload(event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename, port)
done(); done()
}); })
}); })
}); })
it('can download using WebView.downloadURL', function (done) { it('can download using WebView.downloadURL', function (done) {
downloadServer.listen(0, '127.0.0.1', function () { downloadServer.listen(0, '127.0.0.1', function () {
var port = downloadServer.address().port; var port = downloadServer.address().port
ipcRenderer.sendSync('set-download-option', false, false); ipcRenderer.sendSync('set-download-option', false, false)
var webview = new WebView; var webview = new WebView
webview.src = "file://" + fixtures + "/api/blank.html"; webview.src = 'file://' + fixtures + '/api/blank.html'
webview.addEventListener('did-finish-load', function () { webview.addEventListener('did-finish-load', function () {
webview.downloadURL(url + ":" + port + "/"); webview.downloadURL(url + ':' + port + '/')
}); })
ipcRenderer.once('download-done', function (event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename) { ipcRenderer.once('download-done', function (event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename) {
assertDownload(event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename, port); assertDownload(event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename, port)
document.body.removeChild(webview); document.body.removeChild(webview)
done(); done()
}); })
document.body.appendChild(webview); document.body.appendChild(webview)
}); })
}); })
it('can cancel download', function (done) { it('can cancel download', function (done) {
downloadServer.listen(0, '127.0.0.1', function () { downloadServer.listen(0, '127.0.0.1', function () {
var port = downloadServer.address().port; var port = downloadServer.address().port
ipcRenderer.sendSync('set-download-option', true, false); ipcRenderer.sendSync('set-download-option', true, false)
w.loadURL(url + ":" + port + "/"); w.loadURL(url + ':' + port + '/')
ipcRenderer.once('download-done', function (event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename) { ipcRenderer.once('download-done', function (event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename) {
assert.equal(state, 'cancelled'); assert.equal(state, 'cancelled')
assert.equal(filename, 'mock.pdf'); assert.equal(filename, 'mock.pdf')
assert.equal(mimeType, 'application/pdf'); assert.equal(mimeType, 'application/pdf')
assert.equal(receivedBytes, 0); assert.equal(receivedBytes, 0)
assert.equal(totalBytes, mockPDF.length); assert.equal(totalBytes, mockPDF.length)
assert.equal(disposition, contentDisposition); assert.equal(disposition, contentDisposition)
done(); done()
}); })
}); })
}); })
}); })
}); })

View file

@ -1,19 +1,19 @@
const assert = require('assert'); const assert = require('assert')
const path = require('path'); const path = require('path')
const webFrame = require('electron').webFrame; const webFrame = require('electron').webFrame
describe('webFrame module', function () { describe('webFrame module', function () {
var fixtures = path.resolve(__dirname, 'fixtures'); var fixtures = path.resolve(__dirname, 'fixtures')
describe('webFrame.registerURLSchemeAsPrivileged', function () { describe('webFrame.registerURLSchemeAsPrivileged', function () {
it('supports fetch api', function (done) { it('supports fetch api', function (done) {
webFrame.registerURLSchemeAsPrivileged('file'); webFrame.registerURLSchemeAsPrivileged('file')
var url = "file://" + fixtures + "/assets/logo.png"; var url = 'file://' + fixtures + '/assets/logo.png'
fetch(url).then(function (response) { fetch(url).then(function (response) {
assert(response.ok); assert(response.ok)
done(); done()
}).catch(function (err) { }).catch(function (err) {
done('unexpected error : ' + err); done('unexpected error : ' + err)
}); })
}); })
}); })
}); })

View file

@ -1,413 +1,412 @@
const assert = require('assert'); const assert = require('assert')
const http = require('http'); const http = require('http')
const qs = require('querystring'); const qs = require('querystring')
const remote = require('electron').remote; const remote = require('electron').remote
const session = remote.session; const session = remote.session
describe('webRequest module', function () { describe('webRequest module', function () {
var ses = session.defaultSession; var ses = session.defaultSession
var server = http.createServer(function (req, res) { var server = http.createServer(function (req, res) {
res.setHeader('Custom', ['Header']); res.setHeader('Custom', ['Header'])
var content = req.url; var content = req.url
if (req.headers.accept === '*/*;test/header') { if (req.headers.accept === '*/*;test/header') {
content += 'header/received'; content += 'header/received'
} }
res.end(content); res.end(content)
}); })
var defaultURL = null; var defaultURL = null
before(function (done) { before(function (done) {
server.listen(0, '127.0.0.1', function () { server.listen(0, '127.0.0.1', function () {
var port = server.address().port; var port = server.address().port
defaultURL = "http://127.0.0.1:" + port + "/"; defaultURL = 'http://127.0.0.1:' + port + '/'
done(); done()
}); })
}); })
after(function () { after(function () {
server.close(); server.close()
}); })
describe('webRequest.onBeforeRequest', function () { describe('webRequest.onBeforeRequest', function () {
afterEach(function () { afterEach(function () {
ses.webRequest.onBeforeRequest(null); ses.webRequest.onBeforeRequest(null)
}); })
it('can cancel the request', function (done) { it('can cancel the request', function (done) {
ses.webRequest.onBeforeRequest(function (details, callback) { ses.webRequest.onBeforeRequest(function (details, callback) {
callback({ callback({
cancel: true cancel: true
}); })
}); })
$.ajax({ $.ajax({
url: defaultURL, url: defaultURL,
success: function () { success: function () {
done('unexpected success'); done('unexpected success')
}, },
error: function () { error: function () {
done(); done()
} }
}); })
}); })
it('can filter URLs', function (done) { it('can filter URLs', function (done) {
var filter = { var filter = {
urls: [defaultURL + "filter/*"] urls: [defaultURL + 'filter/*']
}; }
ses.webRequest.onBeforeRequest(filter, function (details, callback) { ses.webRequest.onBeforeRequest(filter, function (details, callback) {
callback({ callback({
cancel: true cancel: true
}); })
}); })
$.ajax({ $.ajax({
url: defaultURL + "nofilter/test", url: defaultURL + 'nofilter/test',
success: function (data) { success: function (data) {
assert.equal(data, '/nofilter/test'); assert.equal(data, '/nofilter/test')
$.ajax({ $.ajax({
url: defaultURL + "filter/test", url: defaultURL + 'filter/test',
success: function () { success: function () {
done('unexpected success'); done('unexpected success')
}, },
error: function () { error: function () {
done(); done()
} }
}); })
}, },
error: function (xhr, errorType) { error: function (xhr, errorType) {
done(errorType); done(errorType)
} }
}); })
}); })
it('receives details object', function (done) { it('receives details object', function (done) {
ses.webRequest.onBeforeRequest(function (details, callback) { ses.webRequest.onBeforeRequest(function (details, callback) {
assert.equal(typeof details.id, 'number'); assert.equal(typeof details.id, 'number')
assert.equal(typeof details.timestamp, 'number'); assert.equal(typeof details.timestamp, 'number')
assert.equal(details.url, defaultURL); assert.equal(details.url, defaultURL)
assert.equal(details.method, 'GET'); assert.equal(details.method, 'GET')
assert.equal(details.resourceType, 'xhr'); assert.equal(details.resourceType, 'xhr')
assert(!details.uploadData); assert(!details.uploadData)
callback({}); callback({})
}); })
$.ajax({ $.ajax({
url: defaultURL, url: defaultURL,
success: function (data) { success: function (data) {
assert.equal(data, '/'); assert.equal(data, '/')
done(); done()
}, },
error: function (xhr, errorType) { error: function (xhr, errorType) {
done(errorType); done(errorType)
} }
}); })
}); })
it('receives post data in details object', function (done) { it('receives post data in details object', function (done) {
var postData = { var postData = {
name: 'post test', name: 'post test',
type: 'string' type: 'string'
}; }
ses.webRequest.onBeforeRequest(function (details, callback) { ses.webRequest.onBeforeRequest(function (details, callback) {
assert.equal(details.url, defaultURL); assert.equal(details.url, defaultURL)
assert.equal(details.method, 'POST'); assert.equal(details.method, 'POST')
assert.equal(details.uploadData.length, 1); assert.equal(details.uploadData.length, 1)
var data = qs.parse(details.uploadData[0].bytes.toString()); var data = qs.parse(details.uploadData[0].bytes.toString())
assert.deepEqual(data, postData); assert.deepEqual(data, postData)
callback({ callback({
cancel: true cancel: true
}); })
}); })
$.ajax({ $.ajax({
url: defaultURL, url: defaultURL,
type: 'POST', type: 'POST',
data: postData, data: postData,
success: function() { success: function () {},
},
error: function () { error: function () {
done(); done()
} }
}); })
}); })
it('can redirect the request', function (done) { it('can redirect the request', function (done) {
ses.webRequest.onBeforeRequest(function (details, callback) { ses.webRequest.onBeforeRequest(function (details, callback) {
if (details.url === defaultURL) { if (details.url === defaultURL) {
callback({ callback({
redirectURL: defaultURL + "redirect" redirectURL: defaultURL + 'redirect'
}); })
} else { } else {
callback({}); callback({})
} }
}); })
$.ajax({ $.ajax({
url: defaultURL, url: defaultURL,
success: function (data) { success: function (data) {
assert.equal(data, '/redirect'); assert.equal(data, '/redirect')
done(); done()
}, },
error: function (xhr, errorType) { error: function (xhr, errorType) {
done(errorType); done(errorType)
} }
}); })
}); })
}); })
describe('webRequest.onBeforeSendHeaders', function () { describe('webRequest.onBeforeSendHeaders', function () {
afterEach(function () { afterEach(function () {
ses.webRequest.onBeforeSendHeaders(null); ses.webRequest.onBeforeSendHeaders(null)
}); })
it('receives details object', function (done) { it('receives details object', function (done) {
ses.webRequest.onBeforeSendHeaders(function (details, callback) { ses.webRequest.onBeforeSendHeaders(function (details, callback) {
assert.equal(typeof details.requestHeaders, 'object'); assert.equal(typeof details.requestHeaders, 'object')
callback({}); callback({})
}); })
$.ajax({ $.ajax({
url: defaultURL, url: defaultURL,
success: function (data) { success: function (data) {
assert.equal(data, '/'); assert.equal(data, '/')
done(); done()
}, },
error: function (xhr, errorType) { error: function (xhr, errorType) {
done(errorType); done(errorType)
} }
}); })
}); })
it('can change the request headers', function (done) { it('can change the request headers', function (done) {
ses.webRequest.onBeforeSendHeaders(function (details, callback) { ses.webRequest.onBeforeSendHeaders(function (details, callback) {
var requestHeaders = details.requestHeaders; var requestHeaders = details.requestHeaders
requestHeaders.Accept = '*/*;test/header'; requestHeaders.Accept = '*/*;test/header'
callback({ callback({
requestHeaders: requestHeaders requestHeaders: requestHeaders
}); })
}); })
$.ajax({ $.ajax({
url: defaultURL, url: defaultURL,
success: function (data) { success: function (data) {
assert.equal(data, '/header/received'); assert.equal(data, '/header/received')
done(); done()
}, },
error: function (xhr, errorType) { error: function (xhr, errorType) {
done(errorType); done(errorType)
} }
}); })
}); })
it('resets the whole headers', function (done) { it('resets the whole headers', function (done) {
var requestHeaders = { var requestHeaders = {
Test: 'header' Test: 'header'
}; }
ses.webRequest.onBeforeSendHeaders(function (details, callback) { ses.webRequest.onBeforeSendHeaders(function (details, callback) {
callback({ callback({
requestHeaders: requestHeaders requestHeaders: requestHeaders
}); })
}); })
ses.webRequest.onSendHeaders(function (details) { ses.webRequest.onSendHeaders(function (details) {
assert.deepEqual(details.requestHeaders, requestHeaders); assert.deepEqual(details.requestHeaders, requestHeaders)
done(); done()
}); })
$.ajax({ $.ajax({
url: defaultURL, url: defaultURL,
error: function (xhr, errorType) { error: function (xhr, errorType) {
done(errorType); done(errorType)
} }
}); })
}); })
}); })
describe('webRequest.onSendHeaders', function () { describe('webRequest.onSendHeaders', function () {
afterEach(function () { afterEach(function () {
ses.webRequest.onSendHeaders(null); ses.webRequest.onSendHeaders(null)
}); })
it('receives details object', function (done) { it('receives details object', function (done) {
ses.webRequest.onSendHeaders(function (details) { ses.webRequest.onSendHeaders(function (details) {
assert.equal(typeof details.requestHeaders, 'object'); assert.equal(typeof details.requestHeaders, 'object')
}); })
$.ajax({ $.ajax({
url: defaultURL, url: defaultURL,
success: function (data) { success: function (data) {
assert.equal(data, '/'); assert.equal(data, '/')
done(); done()
}, },
error: function (xhr, errorType) { error: function (xhr, errorType) {
done(errorType); done(errorType)
} }
}); })
}); })
}); })
describe('webRequest.onHeadersReceived', function () { describe('webRequest.onHeadersReceived', function () {
afterEach(function () { afterEach(function () {
ses.webRequest.onHeadersReceived(null); ses.webRequest.onHeadersReceived(null)
}); })
it('receives details object', function (done) { it('receives details object', function (done) {
ses.webRequest.onHeadersReceived(function (details, callback) { ses.webRequest.onHeadersReceived(function (details, callback) {
assert.equal(details.statusLine, 'HTTP/1.1 200 OK'); assert.equal(details.statusLine, 'HTTP/1.1 200 OK')
assert.equal(details.statusCode, 200); assert.equal(details.statusCode, 200)
assert.equal(details.responseHeaders['Custom'], 'Header'); assert.equal(details.responseHeaders['Custom'], 'Header')
callback({}); callback({})
}); })
$.ajax({ $.ajax({
url: defaultURL, url: defaultURL,
success: function (data) { success: function (data) {
assert.equal(data, '/'); assert.equal(data, '/')
done(); done()
}, },
error: function (xhr, errorType) { error: function (xhr, errorType) {
done(errorType); done(errorType)
} }
}); })
}); })
it('can change the response header', function (done) { it('can change the response header', function (done) {
ses.webRequest.onHeadersReceived(function (details, callback) { ses.webRequest.onHeadersReceived(function (details, callback) {
var responseHeaders = details.responseHeaders; var responseHeaders = details.responseHeaders
responseHeaders['Custom'] = ['Changed']; responseHeaders['Custom'] = ['Changed']
callback({ callback({
responseHeaders: responseHeaders responseHeaders: responseHeaders
}); })
}); })
$.ajax({ $.ajax({
url: defaultURL, url: defaultURL,
success: function (data, status, xhr) { success: function (data, status, xhr) {
assert.equal(xhr.getResponseHeader('Custom'), 'Changed'); assert.equal(xhr.getResponseHeader('Custom'), 'Changed')
assert.equal(data, '/'); assert.equal(data, '/')
done(); done()
}, },
error: function (xhr, errorType) { error: function (xhr, errorType) {
done(errorType); done(errorType)
} }
}); })
}); })
it('does not change header by default', function (done) { it('does not change header by default', function (done) {
ses.webRequest.onHeadersReceived(function (details, callback) { ses.webRequest.onHeadersReceived(function (details, callback) {
callback({}); callback({})
}); })
$.ajax({ $.ajax({
url: defaultURL, url: defaultURL,
success: function (data, status, xhr) { success: function (data, status, xhr) {
assert.equal(xhr.getResponseHeader('Custom'), 'Header'); assert.equal(xhr.getResponseHeader('Custom'), 'Header')
assert.equal(data, '/'); assert.equal(data, '/')
done(); done()
}, },
error: function (xhr, errorType) { error: function (xhr, errorType) {
done(errorType); done(errorType)
} }
}); })
}); })
}); })
describe('webRequest.onResponseStarted', function () { describe('webRequest.onResponseStarted', function () {
afterEach(function () { afterEach(function () {
ses.webRequest.onResponseStarted(null); ses.webRequest.onResponseStarted(null)
}); })
it('receives details object', function (done) { it('receives details object', function (done) {
ses.webRequest.onResponseStarted(function (details) { ses.webRequest.onResponseStarted(function (details) {
assert.equal(typeof details.fromCache, 'boolean'); assert.equal(typeof details.fromCache, 'boolean')
assert.equal(details.statusLine, 'HTTP/1.1 200 OK'); assert.equal(details.statusLine, 'HTTP/1.1 200 OK')
assert.equal(details.statusCode, 200); assert.equal(details.statusCode, 200)
assert.equal(details.responseHeaders['Custom'], 'Header'); assert.equal(details.responseHeaders['Custom'], 'Header')
}); })
$.ajax({ $.ajax({
url: defaultURL, url: defaultURL,
success: function (data, status, xhr) { success: function (data, status, xhr) {
assert.equal(xhr.getResponseHeader('Custom'), 'Header'); assert.equal(xhr.getResponseHeader('Custom'), 'Header')
assert.equal(data, '/'); assert.equal(data, '/')
done(); done()
}, },
error: function (xhr, errorType) { error: function (xhr, errorType) {
done(errorType); done(errorType)
} }
}); })
}); })
}); })
describe('webRequest.onBeforeRedirect', function () { describe('webRequest.onBeforeRedirect', function () {
afterEach(function () { afterEach(function () {
ses.webRequest.onBeforeRedirect(null); ses.webRequest.onBeforeRedirect(null)
ses.webRequest.onBeforeRequest(null); ses.webRequest.onBeforeRequest(null)
}); })
it('receives details object', function (done) { it('receives details object', function (done) {
var redirectURL = defaultURL + "redirect"; var redirectURL = defaultURL + 'redirect'
ses.webRequest.onBeforeRequest(function (details, callback) { ses.webRequest.onBeforeRequest(function (details, callback) {
if (details.url === defaultURL) { if (details.url === defaultURL) {
callback({ callback({
redirectURL: redirectURL redirectURL: redirectURL
}); })
} else { } else {
callback({}); callback({})
} }
}); })
ses.webRequest.onBeforeRedirect(function (details) { ses.webRequest.onBeforeRedirect(function (details) {
assert.equal(typeof details.fromCache, 'boolean'); assert.equal(typeof details.fromCache, 'boolean')
assert.equal(details.statusLine, 'HTTP/1.1 307 Internal Redirect'); assert.equal(details.statusLine, 'HTTP/1.1 307 Internal Redirect')
assert.equal(details.statusCode, 307); assert.equal(details.statusCode, 307)
assert.equal(details.redirectURL, redirectURL); assert.equal(details.redirectURL, redirectURL)
}); })
$.ajax({ $.ajax({
url: defaultURL, url: defaultURL,
success: function (data) { success: function (data) {
assert.equal(data, '/redirect'); assert.equal(data, '/redirect')
done(); done()
}, },
error: function (xhr, errorType) { error: function (xhr, errorType) {
done(errorType); done(errorType)
} }
}); })
}); })
}); })
describe('webRequest.onCompleted', function () { describe('webRequest.onCompleted', function () {
afterEach(function () { afterEach(function () {
ses.webRequest.onCompleted(null); ses.webRequest.onCompleted(null)
}); })
it('receives details object', function (done) { it('receives details object', function (done) {
ses.webRequest.onCompleted(function (details) { ses.webRequest.onCompleted(function (details) {
assert.equal(typeof details.fromCache, 'boolean'); assert.equal(typeof details.fromCache, 'boolean')
assert.equal(details.statusLine, 'HTTP/1.1 200 OK'); assert.equal(details.statusLine, 'HTTP/1.1 200 OK')
assert.equal(details.statusCode, 200); assert.equal(details.statusCode, 200)
}); })
$.ajax({ $.ajax({
url: defaultURL, url: defaultURL,
success: function (data) { success: function (data) {
assert.equal(data, '/'); assert.equal(data, '/')
done(); done()
}, },
error: function (xhr, errorType) { error: function (xhr, errorType) {
done(errorType); done(errorType)
} }
}); })
}); })
}); })
describe('webRequest.onErrorOccurred', function () { describe('webRequest.onErrorOccurred', function () {
afterEach(function () { afterEach(function () {
ses.webRequest.onErrorOccurred(null); ses.webRequest.onErrorOccurred(null)
ses.webRequest.onBeforeRequest(null); ses.webRequest.onBeforeRequest(null)
}); })
it('receives details object', function (done) { it('receives details object', function (done) {
ses.webRequest.onBeforeRequest(function (details, callback) { ses.webRequest.onBeforeRequest(function (details, callback) {
callback({ callback({
cancel: true cancel: true
}); })
}); })
ses.webRequest.onErrorOccurred(function (details) { ses.webRequest.onErrorOccurred(function (details) {
assert.equal(details.error, 'net::ERR_BLOCKED_BY_CLIENT'); assert.equal(details.error, 'net::ERR_BLOCKED_BY_CLIENT')
done(); done()
}); })
$.ajax({ $.ajax({
url: defaultURL, url: defaultURL,
success: function () { success: function () {
done('unexpected success'); done('unexpected success')
} }
}); })
}); })
}); })
}); })

File diff suppressed because it is too large Load diff

View file

@ -1,396 +1,396 @@
const assert = require('assert'); const assert = require('assert')
const http = require('http'); const http = require('http')
const path = require('path'); const path = require('path')
const ws = require('ws'); const ws = require('ws')
const remote = require('electron').remote; const remote = require('electron').remote
const BrowserWindow = remote.require('electron').BrowserWindow; const BrowserWindow = remote.require('electron').BrowserWindow
const session = remote.require('electron').session; const session = remote.require('electron').session
const isCI = remote.getGlobal('isCi'); const isCI = remote.getGlobal('isCi')
describe('chromium feature', function () { describe('chromium feature', function () {
var fixtures = path.resolve(__dirname, 'fixtures'); var fixtures = path.resolve(__dirname, 'fixtures')
var listener = null; var listener = null
afterEach(function () { afterEach(function () {
if (listener != null) { if (listener != null) {
window.removeEventListener('message', listener); window.removeEventListener('message', listener)
} }
listener = null; listener = null
}); })
xdescribe('heap snapshot', function () { xdescribe('heap snapshot', function () {
it('does not crash', function () { it('does not crash', function () {
process.atomBinding('v8_util').takeHeapSnapshot(); process.atomBinding('v8_util').takeHeapSnapshot()
}); })
}); })
describe('sending request of http protocol urls', function () { describe('sending request of http protocol urls', function () {
it('does not crash', function (done) { it('does not crash', function (done) {
this.timeout(5000); this.timeout(5000)
var server = http.createServer(function (req, res) { var server = http.createServer(function (req, res) {
res.end(); res.end()
server.close(); server.close()
done(); done()
}); })
server.listen(0, '127.0.0.1', function () { server.listen(0, '127.0.0.1', function () {
var port = server.address().port; var port = server.address().port
$.get("http://127.0.0.1:" + port); $.get('http://127.0.0.1:' + port)
}); })
}); })
}); })
describe('document.hidden', function () { describe('document.hidden', function () {
var url = "file://" + fixtures + "/pages/document-hidden.html"; var url = 'file://' + fixtures + '/pages/document-hidden.html'
var w = null; var w = null
afterEach(function () { afterEach(function () {
w != null ? w.destroy() : void 0; w != null ? w.destroy() : void 0
}); })
it('is set correctly when window is not shown', function (done) { it('is set correctly when window is not shown', function (done) {
w = new BrowserWindow({ w = new BrowserWindow({
show: false show: false
}); })
w.webContents.on('ipc-message', function (event, args) { w.webContents.on('ipc-message', function (event, args) {
assert.deepEqual(args, ['hidden', true]); assert.deepEqual(args, ['hidden', true])
done(); done()
}); })
w.loadURL(url); w.loadURL(url)
}); })
it('is set correctly when window is inactive', function (done) { it('is set correctly when window is inactive', function (done) {
w = new BrowserWindow({ w = new BrowserWindow({
show: false show: false
}); })
w.webContents.on('ipc-message', function (event, args) { w.webContents.on('ipc-message', function (event, args) {
assert.deepEqual(args, ['hidden', false]); assert.deepEqual(args, ['hidden', false])
done(); done()
}); })
w.showInactive(); w.showInactive()
w.loadURL(url); w.loadURL(url)
}); })
}); })
xdescribe('navigator.webkitGetUserMedia', function () { xdescribe('navigator.webkitGetUserMedia', function () {
it('calls its callbacks', function (done) { it('calls its callbacks', function (done) {
this.timeout(5000); this.timeout(5000)
navigator.webkitGetUserMedia({ navigator.webkitGetUserMedia({
audio: true, audio: true,
video: false video: false
}, function () { }, function () {
done(); done()
}, function () { }, function () {
done(); done()
}); })
}); })
}); })
describe('navigator.mediaDevices', function () { describe('navigator.mediaDevices', function () {
if (process.env.TRAVIS === 'true') { if (process.env.TRAVIS === 'true') {
return; return
} }
if (isCI && process.platform === 'linux') { if (isCI && process.platform === 'linux') {
return; return
} }
it('can return labels of enumerated devices', function (done) { it('can return labels of enumerated devices', function (done) {
navigator.mediaDevices.enumerateDevices().then((devices) => { navigator.mediaDevices.enumerateDevices().then((devices) => {
const labels = devices.map((device) => device.label); const labels = devices.map((device) => device.label)
const labelFound = labels.some((label) => !!label); const labelFound = labels.some((label) => !!label)
if (labelFound) if (labelFound)
done(); done()
else else
done('No device labels found: ' + JSON.stringify(labels)); done('No device labels found: ' + JSON.stringify(labels))
}).catch(done); }).catch(done)
}); })
}); })
describe('navigator.language', function () { describe('navigator.language', function () {
it('should not be empty', function () { it('should not be empty', function () {
assert.notEqual(navigator.language, ''); assert.notEqual(navigator.language, '')
}); })
}); })
describe('navigator.serviceWorker', function () { describe('navigator.serviceWorker', function () {
var url = "file://" + fixtures + "/pages/service-worker/index.html"; var url = 'file://' + fixtures + '/pages/service-worker/index.html'
var w = null; var w = null
afterEach(function () { afterEach(function () {
w != null ? w.destroy() : void 0; w != null ? w.destroy() : void 0
}); })
it('should register for file scheme', function (done) { it('should register for file scheme', function (done) {
w = new BrowserWindow({ w = new BrowserWindow({
show: false show: false
}); })
w.webContents.on('ipc-message', function (event, args) { w.webContents.on('ipc-message', function (event, args) {
if (args[0] === 'reload') { if (args[0] === 'reload') {
w.webContents.reload(); w.webContents.reload()
} else if (args[0] === 'error') { } else if (args[0] === 'error') {
done('unexpected error : ' + args[1]); done('unexpected error : ' + args[1])
} else if (args[0] === 'response') { } else if (args[0] === 'response') {
assert.equal(args[1], 'Hello from serviceWorker!'); assert.equal(args[1], 'Hello from serviceWorker!')
session.defaultSession.clearStorageData({ session.defaultSession.clearStorageData({
storages: ['serviceworkers'] storages: ['serviceworkers']
}, function () { }, function () {
done(); done()
}); })
} }
}); })
w.loadURL(url); w.loadURL(url)
}); })
}); })
describe('window.open', function () { describe('window.open', function () {
this.timeout(20000); this.timeout(20000)
it('returns a BrowserWindowProxy object', function () { it('returns a BrowserWindowProxy object', function () {
var b = window.open('about:blank', '', 'show=no'); var b = window.open('about:blank', '', 'show=no')
assert.equal(b.closed, false); assert.equal(b.closed, false)
assert.equal(b.constructor.name, 'BrowserWindowProxy'); assert.equal(b.constructor.name, 'BrowserWindowProxy')
b.close(); b.close()
}); })
it('accepts "nodeIntegration" as feature', function (done) { it('accepts "nodeIntegration" as feature', function (done) {
var b; var b
listener = function (event) { listener = function (event) {
assert.equal(event.data, 'undefined'); assert.equal(event.data, 'undefined')
b.close(); b.close()
done(); done()
}; }
window.addEventListener('message', listener); window.addEventListener('message', listener)
b = window.open("file://" + fixtures + "/pages/window-opener-node.html", '', 'nodeIntegration=no,show=no'); b = window.open('file://' + fixtures + '/pages/window-opener-node.html', '', 'nodeIntegration=no,show=no')
}); })
it('inherit options of parent window', function (done) { it('inherit options of parent window', function (done) {
var b; var b
listener = function (event) { listener = function (event) {
var height, ref1, width; var height, ref1, width
ref1 = remote.getCurrentWindow().getSize(), width = ref1[0], height = ref1[1]; ref1 = remote.getCurrentWindow().getSize(), width = ref1[0], height = ref1[1]
assert.equal(event.data, "size: " + width + " " + height); assert.equal(event.data, 'size: ' + width + ' ' + height)
b.close(); b.close()
done(); done()
}; }
window.addEventListener('message', listener); window.addEventListener('message', listener)
b = window.open("file://" + fixtures + "/pages/window-open-size.html", '', 'show=no'); b = window.open('file://' + fixtures + '/pages/window-open-size.html', '', 'show=no')
}); })
it('does not override child options', function (done) { it('does not override child options', function (done) {
var b, size; var b, size
size = { size = {
width: 350, width: 350,
height: 450 height: 450
}; }
listener = function (event) { listener = function (event) {
assert.equal(event.data, "size: " + size.width + " " + size.height); assert.equal(event.data, 'size: ' + size.width + ' ' + size.height)
b.close(); b.close()
done(); done()
}; }
window.addEventListener('message', listener); window.addEventListener('message', listener)
b = window.open("file://" + fixtures + "/pages/window-open-size.html", '', "show=no,width=" + size.width + ",height=" + size.height); b = window.open('file://' + fixtures + '/pages/window-open-size.html', '', 'show=no,width=' + size.width + ',height=' + size.height)
}); })
it('defines a window.location getter', function (done) { it('defines a window.location getter', function (done) {
var b, targetURL; var b, targetURL
targetURL = "file://" + fixtures + "/pages/base-page.html"; targetURL = 'file://' + fixtures + '/pages/base-page.html'
b = window.open(targetURL); b = window.open(targetURL)
BrowserWindow.fromId(b.guestId).webContents.once('did-finish-load', function () { BrowserWindow.fromId(b.guestId).webContents.once('did-finish-load', function () {
assert.equal(b.location, targetURL); assert.equal(b.location, targetURL)
b.close(); b.close()
done(); done()
}); })
}); })
it('defines a window.location setter', function (done) { it('defines a window.location setter', function (done) {
// Load a page that definitely won't redirect // Load a page that definitely won't redirect
var b; var b
b = window.open("about:blank"); b = window.open('about:blank')
BrowserWindow.fromId(b.guestId).webContents.once('did-finish-load', function () { BrowserWindow.fromId(b.guestId).webContents.once('did-finish-load', function () {
// When it loads, redirect // When it loads, redirect
b.location = "file://" + fixtures + "/pages/base-page.html"; b.location = 'file://' + fixtures + '/pages/base-page.html'
BrowserWindow.fromId(b.guestId).webContents.once('did-finish-load', function () { BrowserWindow.fromId(b.guestId).webContents.once('did-finish-load', function () {
// After our second redirect, cleanup and callback // After our second redirect, cleanup and callback
b.close(); b.close()
done(); done()
}); })
}); })
}); })
}); })
describe('window.opener', function () { describe('window.opener', function () {
this.timeout(10000); this.timeout(10000)
var url = "file://" + fixtures + "/pages/window-opener.html"; var url = 'file://' + fixtures + '/pages/window-opener.html'
var w = null; var w = null
afterEach(function () { afterEach(function () {
w != null ? w.destroy() : void 0; w != null ? w.destroy() : void 0
}); })
it('is null for main window', function (done) { it('is null for main window', function (done) {
w = new BrowserWindow({ w = new BrowserWindow({
show: false show: false
}); })
w.webContents.on('ipc-message', function (event, args) { w.webContents.on('ipc-message', function (event, args) {
assert.deepEqual(args, ['opener', null]); assert.deepEqual(args, ['opener', null])
done(); done()
}); })
w.loadURL(url); w.loadURL(url)
}); })
it('is not null for window opened by window.open', function (done) { it('is not null for window opened by window.open', function (done) {
var b; var b
listener = function (event) { listener = function (event) {
assert.equal(event.data, 'object'); assert.equal(event.data, 'object')
b.close(); b.close()
done(); done()
}; }
window.addEventListener('message', listener); window.addEventListener('message', listener)
b = window.open(url, '', 'show=no'); b = window.open(url, '', 'show=no')
}); })
}); })
describe('window.postMessage', function () { describe('window.postMessage', function () {
it('sets the source and origin correctly', function (done) { it('sets the source and origin correctly', function (done) {
var b, sourceId; var b, sourceId
sourceId = remote.getCurrentWindow().id; sourceId = remote.getCurrentWindow().id
listener = function (event) { listener = function (event) {
window.removeEventListener('message', listener); window.removeEventListener('message', listener)
b.close(); b.close()
var message = JSON.parse(event.data); var message = JSON.parse(event.data)
assert.equal(message.data, 'testing'); assert.equal(message.data, 'testing')
assert.equal(message.origin, 'file://'); assert.equal(message.origin, 'file://')
assert.equal(message.sourceEqualsOpener, true); assert.equal(message.sourceEqualsOpener, true)
assert.equal(message.sourceId, sourceId); assert.equal(message.sourceId, sourceId)
assert.equal(event.origin, 'file://'); assert.equal(event.origin, 'file://')
done(); done()
}; }
window.addEventListener('message', listener); window.addEventListener('message', listener)
b = window.open("file://" + fixtures + "/pages/window-open-postMessage.html", '', 'show=no'); b = window.open('file://' + fixtures + '/pages/window-open-postMessage.html', '', 'show=no')
BrowserWindow.fromId(b.guestId).webContents.once('did-finish-load', function () { BrowserWindow.fromId(b.guestId).webContents.once('did-finish-load', function () {
b.postMessage('testing', '*'); b.postMessage('testing', '*')
}); })
}); })
}); })
describe('window.opener.postMessage', function () { describe('window.opener.postMessage', function () {
it('sets source and origin correctly', function (done) { it('sets source and origin correctly', function (done) {
var b; var b
listener = function (event) { listener = function (event) {
window.removeEventListener('message', listener); window.removeEventListener('message', listener)
b.close(); b.close()
assert.equal(event.source, b); assert.equal(event.source, b)
assert.equal(event.origin, 'file://'); assert.equal(event.origin, 'file://')
done(); done()
}; }
window.addEventListener('message', listener); window.addEventListener('message', listener)
b = window.open("file://" + fixtures + "/pages/window-opener-postMessage.html", '', 'show=no'); b = window.open('file://' + fixtures + '/pages/window-opener-postMessage.html', '', 'show=no')
}); })
}); })
describe('creating a Uint8Array under browser side', function () { describe('creating a Uint8Array under browser side', function () {
it('does not crash', function () { it('does not crash', function () {
var RUint8Array = remote.getGlobal('Uint8Array'); var RUint8Array = remote.getGlobal('Uint8Array')
new RUint8Array; new RUint8Array
}); })
}); })
describe('webgl', function () { describe('webgl', function () {
it('can be get as context in canvas', function () { it('can be get as context in canvas', function () {
if (process.platform === 'linux') { if (process.platform === 'linux') {
return; return
} }
var webgl = document.createElement('canvas').getContext('webgl'); var webgl = document.createElement('canvas').getContext('webgl')
assert.notEqual(webgl, null); assert.notEqual(webgl, null)
}); })
}); })
describe('web workers', function () { describe('web workers', function () {
it('Worker can work', function (done) { it('Worker can work', function (done) {
var worker = new Worker('../fixtures/workers/worker.js'); var worker = new Worker('../fixtures/workers/worker.js')
var message = 'ping'; var message = 'ping'
worker.onmessage = function (event) { worker.onmessage = function (event) {
assert.equal(event.data, message); assert.equal(event.data, message)
worker.terminate(); worker.terminate()
done(); done()
}; }
worker.postMessage(message); worker.postMessage(message)
}); })
it('SharedWorker can work', function (done) { it('SharedWorker can work', function (done) {
var worker = new SharedWorker('../fixtures/workers/shared_worker.js'); var worker = new SharedWorker('../fixtures/workers/shared_worker.js')
var message = 'ping'; var message = 'ping'
worker.port.onmessage = function (event) { worker.port.onmessage = function (event) {
assert.equal(event.data, message); assert.equal(event.data, message)
done(); done()
}; }
worker.port.postMessage(message); worker.port.postMessage(message)
}); })
}); })
describe('iframe', function () { describe('iframe', function () {
var iframe = null; var iframe = null
beforeEach(function () { beforeEach(function () {
iframe = document.createElement('iframe'); iframe = document.createElement('iframe')
}); })
afterEach(function () { afterEach(function () {
document.body.removeChild(iframe); document.body.removeChild(iframe)
}); })
it('does not have node integration', function (done) { it('does not have node integration', function (done) {
iframe.src = "file://" + fixtures + "/pages/set-global.html"; iframe.src = 'file://' + fixtures + '/pages/set-global.html'
document.body.appendChild(iframe); document.body.appendChild(iframe)
iframe.onload = function () { iframe.onload = function () {
assert.equal(iframe.contentWindow.test, 'undefined undefined undefined'); assert.equal(iframe.contentWindow.test, 'undefined undefined undefined')
done(); done()
}; }
}); })
}); })
describe('storage', function () { describe('storage', function () {
it('requesting persitent quota works', function (done) { it('requesting persitent quota works', function (done) {
navigator.webkitPersistentStorage.requestQuota(1024 * 1024, function (grantedBytes) { navigator.webkitPersistentStorage.requestQuota(1024 * 1024, function (grantedBytes) {
assert.equal(grantedBytes, 1048576); assert.equal(grantedBytes, 1048576)
done(); done()
}); })
}); })
}); })
describe('websockets', function () { describe('websockets', function () {
var wss = null; var wss = null
var server = null; var server = null
var WebSocketServer = ws.Server; var WebSocketServer = ws.Server
afterEach(function () { afterEach(function () {
wss.close(); wss.close()
server.close(); server.close()
}); })
it('has user agent', function (done) { it('has user agent', function (done) {
server = http.createServer(); server = http.createServer()
server.listen(0, '127.0.0.1', function () { server.listen(0, '127.0.0.1', function () {
var port = server.address().port; var port = server.address().port
wss = new WebSocketServer({ wss = new WebSocketServer({
server: server server: server
}); })
wss.on('error', done); wss.on('error', done)
wss.on('connection', function (ws) { wss.on('connection', function (ws) {
if (ws.upgradeReq.headers['user-agent']) { if (ws.upgradeReq.headers['user-agent']) {
done(); done()
} else { } else {
done('user agent is empty'); done('user agent is empty')
} }
}); })
new WebSocket("ws://127.0.0.1:" + port); new WebSocket('ws://127.0.0.1:' + port)
}); })
}); })
}); })
describe('Promise', function () { describe('Promise', function () {
it('resolves correctly in Node.js calls', function (done) { it('resolves correctly in Node.js calls', function (done) {
@ -400,16 +400,16 @@ describe('chromium feature', function() {
value: function () {} value: function () {}
} }
}) })
}); })
setImmediate(function () { setImmediate(function () {
var called = false; var called = false
Promise.resolve().then(function () { Promise.resolve().then(function () {
done(called ? void 0 : new Error('wrong sequence')); done(called ? void 0 : new Error('wrong sequence'))
}); })
document.createElement('x-element'); document.createElement('x-element')
called = true; called = true
}); })
}); })
it('resolves correctly in Electron calls', function (done) { it('resolves correctly in Electron calls', function (done) {
document.registerElement('y-element', { document.registerElement('y-element', {
@ -418,15 +418,15 @@ describe('chromium feature', function() {
value: function () {} value: function () {}
} }
}) })
}); })
remote.getGlobal('setImmediate')(function () { remote.getGlobal('setImmediate')(function () {
var called = false; var called = false
Promise.resolve().then(function () { Promise.resolve().then(function () {
done(called ? void 0 : new Error('wrong sequence')); done(called ? void 0 : new Error('wrong sequence'))
}); })
document.createElement('y-element'); document.createElement('y-element')
called = true; called = true
}); })
}); })
}); })
}); })

View file

@ -1,12 +1,12 @@
var app = require('electron').app; var app = require('electron').app
app.on('ready', function () { app.on('ready', function () {
// This setImmediate call gets the spec passing on Linux // This setImmediate call gets the spec passing on Linux
setImmediate(function () { setImmediate(function () {
app.exit(123); app.exit(123)
}); })
}); })
process.on('exit', function (code) { process.on('exit', function (code) {
console.log('Exit event with code: ' + code); console.log('Exit event with code: ' + code)
}); })

View file

@ -1,4 +1,4 @@
var fs = require('fs'); var fs = require('fs')
process.on('message', function (file) { process.on('message', function (file) {
process.send(fs.readFileSync(file).toString()); process.send(fs.readFileSync(file).toString())
}); })

View file

@ -1,7 +1,7 @@
exports.call = function (func) { exports.call = function (func) {
return func(); return func()
}; }
exports.constructor = function () { exports.constructor = function () {
this.test = 'test'; this.test = 'test'
}; }

View file

@ -1,22 +1,22 @@
'use strict'; 'use strict'
let value = 'old'; let value = 'old'
class BaseClass { class BaseClass {
method () { method () {
return 'method'; return 'method'
} }
get readonly () { get readonly () {
return 'readonly'; return 'readonly'
} }
get value () { get value () {
return value; return value
} }
set value (val) { set value (val) {
value = val; value = val
} }
} }

View file

@ -1,4 +1,4 @@
var net = require('net'); var net = require('net')
var server = net.createServer(function() {}); var server = net.createServer(function () {})
server.listen(process.argv[2]); server.listen(process.argv[2])
process.exit(0); process.exit(0)

View file

@ -1,14 +1,14 @@
process.on('uncaughtException', function (error) { process.on('uncaughtException', function (error) {
process.send(error.stack); process.send(error.stack)
}); })
var child = require('child_process').fork(__dirname + '/ping.js'); var child = require('child_process').fork(__dirname + '/ping.js')
process.on('message', function (msg) { process.on('message', function (msg) {
child.send(msg); child.send(msg)
}); })
child.on('message', function (msg) { child.on('message', function (msg) {
process.send(msg); process.send(msg)
}); })
child.on('exit', function (code) { child.on('exit', function (code) {
process.exit(code); process.exit(code)
}); })

View file

@ -1 +1 @@
exports.aFunction = function() { return 1127; }; exports.aFunction = function () { return 1127; }

View file

@ -1 +1 @@
exports.id = 1127; exports.id = 1127

View file

@ -3,5 +3,5 @@ process.on('message', function () {
'a'.localeCompare('a'), 'a'.localeCompare('a'),
'ä'.localeCompare('z', 'de'), 'ä'.localeCompare('z', 'de'),
'ä'.localeCompare('a', 'sv', { sensitivity: 'base' }), 'ä'.localeCompare('a', 'sv', { sensitivity: 'base' }),
]); ])
}); })

View file

@ -1,3 +1,3 @@
process.on('message', function () { process.on('message', function () {
process.send(typeof require('original-fs')); process.send(typeof require('original-fs'))
}); })

View file

@ -1,4 +1,4 @@
process.on('message', function (msg) { process.on('message', function (msg) {
process.send(msg); process.send(msg)
process.exit(0); process.exit(0)
}); })

View file

@ -1,4 +1,4 @@
var ipcRenderer = require('electron').ipcRenderer; var ipcRenderer = require('electron').ipcRenderer
ipcRenderer.on('ping', function (event, message) { ipcRenderer.on('ping', function (event, message) {
ipcRenderer.sendToHost('pong', message); ipcRenderer.sendToHost('pong', message)
}); })

View file

@ -1,7 +1,7 @@
setImmediate(function () { setImmediate(function () {
try { try {
console.log([typeof process, typeof setImmediate, typeof global].join(' ')); console.log([typeof process, typeof setImmediate, typeof global].join(' '))
} catch (e) { } catch (e) {
console.log(e.message); console.log(e.message)
} }
}); })

View file

@ -1 +1 @@
console.log([typeof require, typeof module, typeof process].join(' ')); console.log([typeof require, typeof module, typeof process].join(' '))

View file

@ -1,7 +1,7 @@
exports.print = function (obj) { exports.print = function (obj) {
return obj.constructor.name; return obj.constructor.name
}; }
exports.echo = function (obj) { exports.echo = function (obj) {
return obj; return obj
}; }

View file

@ -1,4 +1,4 @@
process.on('message', function () { process.on('message', function () {
process.send(process.argv); process.send(process.argv)
process.exit(0); process.exit(0)
}); })

View file

@ -1,5 +1,5 @@
exports.twicePromise = function (promise) { exports.twicePromise = function (promise) {
return promise.then(function (value) { return promise.then(function (value) {
return value * 2; return value * 2
}); })
}; }

View file

@ -1 +1 @@
exports.property = 1127; exports.property = 1127

View file

@ -1,6 +1,6 @@
process.on('uncaughtException', function (err) { process.on('uncaughtException', function (err) {
process.send(err.message); process.send(err.message)
}); })
require('runas'); require('runas')
process.send('ok'); process.send('ok')

View file

@ -1,4 +1,4 @@
var ipcRenderer = require('electron').ipcRenderer; var ipcRenderer = require('electron').ipcRenderer
window.onload = function () { window.onload = function () {
ipcRenderer.send('answer', typeof window.process); ipcRenderer.send('answer', typeof window.process)
}; }

View file

@ -1 +1 @@
window.test = 'preload'; window.test = 'preload'

View file

@ -1,11 +1,11 @@
process.on('uncaughtException', function (error) { process.on('uncaughtException', function (error) {
process.send(error.message); process.send(error.message)
process.exit(1); process.exit(1)
}); })
process.on('message', function () { process.on('message', function () {
setImmediate(function () { setImmediate(function () {
process.send('ok'); process.send('ok')
process.exit(0); process.exit(0)
}); })
}); })

View file

@ -1,9 +1,9 @@
self.addEventListener('fetch', function (event) { self.addEventListener('fetch', function (event) {
var requestUrl = new URL(event.request.url); var requestUrl = new URL(event.request.url)
if (requestUrl.pathname === '/echo' && if (requestUrl.pathname === '/echo' &&
event.request.headers.has('X-Mock-Response')) { event.request.headers.has('X-Mock-Response')) {
var mockResponse = new Response('Hello from serviceWorker!'); var mockResponse = new Response('Hello from serviceWorker!')
event.respondWith(mockResponse); event.respondWith(mockResponse)
} }
}); })

View file

@ -1,7 +1,7 @@
this.onconnect = function (event) { this.onconnect = function (event) {
var port = event.ports[0]; var port = event.ports[0]
port.start(); port.start()
port.onmessage = function (event) { port.onmessage = function (event) {
port.postMessage(event.data); port.postMessage(event.data)
}; }
}; }

View file

@ -1,3 +1,3 @@
this.onmessage = function (msg) { this.onmessage = function (msg) {
this.postMessage(msg.data); this.postMessage(msg.data)
}; }

View file

@ -1,47 +1,47 @@
const assert = require('assert'); const assert = require('assert')
const path = require('path'); const path = require('path')
const temp = require('temp'); const temp = require('temp')
describe('third-party module', function () { describe('third-party module', function () {
var fixtures = path.join(__dirname, 'fixtures'); var fixtures = path.join(__dirname, 'fixtures')
temp.track(); temp.track()
if (process.platform !== 'win32' || process.execPath.toLowerCase().indexOf('\\out\\d\\') === -1) { if (process.platform !== 'win32' || process.execPath.toLowerCase().indexOf('\\out\\d\\') === -1) {
describe('runas', function () { describe('runas', function () {
it('can be required in renderer', function () { it('can be required in renderer', function () {
require('runas'); require('runas')
}); })
it('can be required in node binary', function (done) { it('can be required in node binary', function (done) {
var runas = path.join(fixtures, 'module', 'runas.js'); var runas = path.join(fixtures, 'module', 'runas.js')
var child = require('child_process').fork(runas); var child = require('child_process').fork(runas)
child.on('message', function (msg) { child.on('message', function (msg) {
assert.equal(msg, 'ok'); assert.equal(msg, 'ok')
done(); done()
}); })
}); })
}); })
describe('ffi', function () { describe('ffi', function () {
it('does not crash', function () { it('does not crash', function () {
var ffi = require('ffi'); var ffi = require('ffi')
var libm = ffi.Library('libm', { var libm = ffi.Library('libm', {
ceil: ['double', ['double']] ceil: ['double', ['double']]
}); })
assert.equal(libm.ceil(1.5), 2); assert.equal(libm.ceil(1.5), 2)
}); })
}); })
} }
describe('q', function () { describe('q', function () {
var Q = require('q'); var Q = require('q')
describe('Q.when', function () { describe('Q.when', function () {
it('emits the fullfil callback', function (done) { it('emits the fullfil callback', function (done) {
Q(true).then(function (val) { Q(true).then(function (val) {
assert.equal(val, true); assert.equal(val, true)
done(); done()
}); })
}); })
}); })
}); })
}); })

View file

@ -1,220 +1,220 @@
const assert = require('assert'); const assert = require('assert')
const child_process = require('child_process'); const child_process = require('child_process')
const fs = require('fs'); const fs = require('fs')
const path = require('path'); const path = require('path')
const os = require('os'); const os = require('os')
const remote = require('electron').remote; const remote = require('electron').remote
describe('node feature', function () { describe('node feature', function () {
var fixtures = path.join(__dirname, 'fixtures'); var fixtures = path.join(__dirname, 'fixtures')
describe('child_process', function () { describe('child_process', function () {
describe('child_process.fork', function () { describe('child_process.fork', function () {
it('works in current process', function (done) { it('works in current process', function (done) {
var child = child_process.fork(path.join(fixtures, 'module', 'ping.js')); var child = child_process.fork(path.join(fixtures, 'module', 'ping.js'))
child.on('message', function (msg) { child.on('message', function (msg) {
assert.equal(msg, 'message'); assert.equal(msg, 'message')
done(); done()
}); })
child.send('message'); child.send('message')
}); })
it('preserves args', function (done) { it('preserves args', function (done) {
var args = ['--expose_gc', '-test', '1']; var args = ['--expose_gc', '-test', '1']
var child = child_process.fork(path.join(fixtures, 'module', 'process_args.js'), args); var child = child_process.fork(path.join(fixtures, 'module', 'process_args.js'), args)
child.on('message', function (msg) { child.on('message', function (msg) {
assert.deepEqual(args, msg.slice(2)); assert.deepEqual(args, msg.slice(2))
done(); done()
}); })
child.send('message'); child.send('message')
}); })
it('works in forked process', function (done) { it('works in forked process', function (done) {
var child = child_process.fork(path.join(fixtures, 'module', 'fork_ping.js')); var child = child_process.fork(path.join(fixtures, 'module', 'fork_ping.js'))
child.on('message', function (msg) { child.on('message', function (msg) {
assert.equal(msg, 'message'); assert.equal(msg, 'message')
done(); done()
}); })
child.send('message'); child.send('message')
}); })
it('works in forked process when options.env is specifed', function (done) { it('works in forked process when options.env is specifed', function (done) {
var child = child_process.fork(path.join(fixtures, 'module', 'fork_ping.js'), [], { var child = child_process.fork(path.join(fixtures, 'module', 'fork_ping.js'), [], {
path: process.env['PATH'] path: process.env['PATH']
}); })
child.on('message', function (msg) { child.on('message', function (msg) {
assert.equal(msg, 'message'); assert.equal(msg, 'message')
done(); done()
}); })
child.send('message'); child.send('message')
}); })
it('works in browser process', function (done) { it('works in browser process', function (done) {
var fork = remote.require('child_process').fork; var fork = remote.require('child_process').fork
var child = fork(path.join(fixtures, 'module', 'ping.js')); var child = fork(path.join(fixtures, 'module', 'ping.js'))
child.on('message', function (msg) { child.on('message', function (msg) {
assert.equal(msg, 'message'); assert.equal(msg, 'message')
done(); done()
}); })
child.send('message'); child.send('message')
}); })
it('has String::localeCompare working in script', function (done) { it('has String::localeCompare working in script', function (done) {
var child = child_process.fork(path.join(fixtures, 'module', 'locale-compare.js')); var child = child_process.fork(path.join(fixtures, 'module', 'locale-compare.js'))
child.on('message', function (msg) { child.on('message', function (msg) {
assert.deepEqual(msg, [0, -1, 1]); assert.deepEqual(msg, [0, -1, 1])
done(); done()
}); })
child.send('message'); child.send('message')
}); })
it('has setImmediate working in script', function (done) { it('has setImmediate working in script', function (done) {
var child = child_process.fork(path.join(fixtures, 'module', 'set-immediate.js')); var child = child_process.fork(path.join(fixtures, 'module', 'set-immediate.js'))
child.on('message', function (msg) { child.on('message', function (msg) {
assert.equal(msg, 'ok'); assert.equal(msg, 'ok')
done(); done()
}); })
child.send('message'); child.send('message')
}); })
}); })
}); })
describe('contexts', function () { describe('contexts', function () {
describe('setTimeout in fs callback', function () { describe('setTimeout in fs callback', function () {
if (process.env.TRAVIS === 'true') { if (process.env.TRAVIS === 'true') {
return; return
} }
it('does not crash', function (done) { it('does not crash', function (done) {
fs.readFile(__filename, function () { fs.readFile(__filename, function () {
setTimeout(done, 0); setTimeout(done, 0)
}); })
}); })
}); })
describe('throw error in node context', function () { describe('throw error in node context', function () {
it('gets caught', function (done) { it('gets caught', function (done) {
var error = new Error('boo!'); var error = new Error('boo!')
var lsts = process.listeners('uncaughtException'); var lsts = process.listeners('uncaughtException')
process.removeAllListeners('uncaughtException'); process.removeAllListeners('uncaughtException')
process.on('uncaughtException', function () { process.on('uncaughtException', function () {
var i, len, lst; var i, len, lst
process.removeAllListeners('uncaughtException'); process.removeAllListeners('uncaughtException')
for (i = 0, len = lsts.length; i < len; i++) { for (i = 0, len = lsts.length; i < len; i++) {
lst = lsts[i]; lst = lsts[i]
process.on('uncaughtException', lst); process.on('uncaughtException', lst)
} }
done(); done()
}); })
fs.readFile(__filename, function () { fs.readFile(__filename, function () {
throw error; throw error
}); })
}); })
}); })
describe('setTimeout called under Chromium event loop in browser process', function () { describe('setTimeout called under Chromium event loop in browser process', function () {
it('can be scheduled in time', function (done) { it('can be scheduled in time', function (done) {
remote.getGlobal('setTimeout')(done, 0); remote.getGlobal('setTimeout')(done, 0)
}); })
}); })
describe('setInterval called under Chromium event loop in browser process', function () { describe('setInterval called under Chromium event loop in browser process', function () {
it('can be scheduled in time', function (done) { it('can be scheduled in time', function (done) {
var clear, interval; var clear, interval
clear = function () { clear = function () {
remote.getGlobal('clearInterval')(interval); remote.getGlobal('clearInterval')(interval)
done(); done()
}; }
interval = remote.getGlobal('setInterval')(clear, 10); interval = remote.getGlobal('setInterval')(clear, 10)
}); })
}); })
}); })
describe('message loop', function () { describe('message loop', function () {
describe('process.nextTick', function () { describe('process.nextTick', function () {
it('emits the callback', function (done) { it('emits the callback', function (done) {
process.nextTick(done); process.nextTick(done)
}); })
it('works in nested calls', function (done) { it('works in nested calls', function (done) {
process.nextTick(function () { process.nextTick(function () {
process.nextTick(function () { process.nextTick(function () {
process.nextTick(done); process.nextTick(done)
}); })
}); })
}); })
}); })
describe('setImmediate', function () { describe('setImmediate', function () {
it('emits the callback', function (done) { it('emits the callback', function (done) {
setImmediate(done); setImmediate(done)
}); })
it('works in nested calls', function (done) { it('works in nested calls', function (done) {
setImmediate(function () { setImmediate(function () {
setImmediate(function () { setImmediate(function () {
setImmediate(done); setImmediate(done)
}); })
}); })
}); })
}); })
}); })
describe('net.connect', function () { describe('net.connect', function () {
if (process.platform !== 'darwin') { if (process.platform !== 'darwin') {
return; return
} }
it('emit error when connect to a socket path without listeners', function (done) { it('emit error when connect to a socket path without listeners', function (done) {
var socketPath = path.join(os.tmpdir(), 'atom-shell-test.sock'); var socketPath = path.join(os.tmpdir(), 'atom-shell-test.sock')
var script = path.join(fixtures, 'module', 'create_socket.js'); var script = path.join(fixtures, 'module', 'create_socket.js')
var child = child_process.fork(script, [socketPath]); var child = child_process.fork(script, [socketPath])
child.on('exit', function (code) { child.on('exit', function (code) {
assert.equal(code, 0); assert.equal(code, 0)
var client = require('net').connect(socketPath); var client = require('net').connect(socketPath)
client.on('error', function (error) { client.on('error', function (error) {
assert.equal(error.code, 'ECONNREFUSED'); assert.equal(error.code, 'ECONNREFUSED')
done(); done()
}); })
}); })
}); })
}); })
describe('Buffer', function () { describe('Buffer', function () {
it('can be created from WebKit external string', function () { it('can be created from WebKit external string', function () {
var p = document.createElement('p'); var p = document.createElement('p')
p.innerText = '闲云潭影日悠悠,物换星移几度秋'; p.innerText = '闲云潭影日悠悠,物换星移几度秋'
var b = new Buffer(p.innerText); var b = new Buffer(p.innerText)
assert.equal(b.toString(), '闲云潭影日悠悠,物换星移几度秋'); assert.equal(b.toString(), '闲云潭影日悠悠,物换星移几度秋')
assert.equal(Buffer.byteLength(p.innerText), 45); assert.equal(Buffer.byteLength(p.innerText), 45)
}); })
it('correctly parses external one-byte UTF8 string', function () { it('correctly parses external one-byte UTF8 string', function () {
var p = document.createElement('p'); var p = document.createElement('p')
p.innerText = 'Jøhänñéß'; p.innerText = 'Jøhänñéß'
var b = new Buffer(p.innerText); var b = new Buffer(p.innerText)
assert.equal(b.toString(), 'Jøhänñéß'); assert.equal(b.toString(), 'Jøhänñéß')
assert.equal(Buffer.byteLength(p.innerText), 13); assert.equal(Buffer.byteLength(p.innerText), 13)
}); })
}); })
describe('process.stdout', function () { describe('process.stdout', function () {
it('should not throw exception', function () { it('should not throw exception', function () {
process.stdout; process.stdout
}); })
it('should not throw exception when calling write()', function () { it('should not throw exception when calling write()', function () {
process.stdout.write('test'); process.stdout.write('test')
}); })
xit('should have isTTY defined', function () { xit('should have isTTY defined', function () {
assert.equal(typeof process.stdout.isTTY, 'boolean'); assert.equal(typeof process.stdout.isTTY, 'boolean')
}); })
}); })
describe('vm.createContext', function () { describe('vm.createContext', function () {
it('should not crash', function () { it('should not crash', function () {
require('vm').runInNewContext(''); require('vm').runInNewContext('')
}); })
}); })
}); })

View file

@ -1,81 +1,81 @@
// Disable use of deprecated functions. // Disable use of deprecated functions.
process.throwDeprecation = true; process.throwDeprecation = true
const electron = require('electron'); const electron = require('electron')
const app = electron.app; const app = electron.app
const ipcMain = electron.ipcMain; const ipcMain = electron.ipcMain
const dialog = electron.dialog; const dialog = electron.dialog
const BrowserWindow = electron.BrowserWindow; const BrowserWindow = electron.BrowserWindow
const path = require('path'); const path = require('path')
const url = require('url'); const url = require('url')
var argv = require('yargs') var argv = require('yargs')
.boolean('ci') .boolean('ci')
.string('g').alias('g', 'grep') .string('g').alias('g', 'grep')
.boolean('i').alias('i', 'invert') .boolean('i').alias('i', 'invert')
.argv; .argv
var window = null; var window = null
process.port = 0; // will be used by crash-reporter spec. process.port = 0; // will be used by crash-reporter spec.
app.commandLine.appendSwitch('js-flags', '--expose_gc'); app.commandLine.appendSwitch('js-flags', '--expose_gc')
app.commandLine.appendSwitch('ignore-certificate-errors'); app.commandLine.appendSwitch('ignore-certificate-errors')
app.commandLine.appendSwitch('disable-renderer-backgrounding'); app.commandLine.appendSwitch('disable-renderer-backgrounding')
// Accessing stdout in the main process will result in the process.stdout // Accessing stdout in the main process will result in the process.stdout
// throwing UnknownSystemError in renderer process sometimes. This line makes // throwing UnknownSystemError in renderer process sometimes. This line makes
// sure we can reproduce it in renderer process. // sure we can reproduce it in renderer process.
process.stdout; process.stdout
// Access console to reproduce #3482. // Access console to reproduce #3482.
console; console
ipcMain.on('message', function (event, arg) { ipcMain.on('message', function (event, arg) {
event.sender.send('message', arg); event.sender.send('message', arg)
}); })
ipcMain.on('console.log', function (event, args) { ipcMain.on('console.log', function (event, args) {
console.error.apply(console, args); console.error.apply(console, args)
}); })
ipcMain.on('console.error', function (event, args) { ipcMain.on('console.error', function (event, args) {
console.error.apply(console, args); console.error.apply(console, args)
}); })
ipcMain.on('process.exit', function (event, code) { ipcMain.on('process.exit', function (event, code) {
process.exit(code); process.exit(code)
}); })
ipcMain.on('eval', function (event, script) { ipcMain.on('eval', function (event, script) {
event.returnValue = eval(script); event.returnValue = eval(script)
}); })
ipcMain.on('echo', function (event, msg) { ipcMain.on('echo', function (event, msg) {
event.returnValue = msg; event.returnValue = msg
}); })
global.isCi = !!argv.ci; global.isCi = !!argv.ci
if (global.isCi) { if (global.isCi) {
process.removeAllListeners('uncaughtException'); process.removeAllListeners('uncaughtException')
process.on('uncaughtException', function (error) { process.on('uncaughtException', function (error) {
console.error(error, error.stack); console.error(error, error.stack)
process.exit(1); process.exit(1)
}); })
} }
app.on('window-all-closed', function () { app.on('window-all-closed', function () {
app.quit(); app.quit()
}); })
app.on('ready', function () { app.on('ready', function () {
// Test if using protocol module would crash. // Test if using protocol module would crash.
electron.protocol.registerStringProtocol('test-if-crashes', function() {}); electron.protocol.registerStringProtocol('test-if-crashes', function () {})
// Send auto updater errors to window to be verified in specs // Send auto updater errors to window to be verified in specs
electron.autoUpdater.on('error', function (error) { electron.autoUpdater.on('error', function (error) {
window.send('auto-updater-error', error.message); window.send('auto-updater-error', error.message)
}); })
window = new BrowserWindow({ window = new BrowserWindow({
title: 'Electron Tests', title: 'Electron Tests',
@ -85,7 +85,7 @@ app.on('ready', function() {
webPreferences: { webPreferences: {
javascript: true // Test whether web preferences crashes. javascript: true // Test whether web preferences crashes.
}, },
}); })
window.loadURL(url.format({ window.loadURL(url.format({
pathname: __dirname + '/index.html', pathname: __dirname + '/index.html',
protocol: 'file', protocol: 'file',
@ -93,35 +93,35 @@ app.on('ready', function() {
grep: argv.grep, grep: argv.grep,
invert: argv.invert ? 'true' : '' invert: argv.invert ? 'true' : ''
} }
})); }))
window.on('unresponsive', function () { window.on('unresponsive', function () {
var chosen = dialog.showMessageBox(window, { var chosen = dialog.showMessageBox(window, {
type: 'warning', type: 'warning',
buttons: ['Close', 'Keep Waiting'], buttons: ['Close', 'Keep Waiting'],
message: 'Window is not responsing', message: 'Window is not responsing',
detail: 'The window is not responding. Would you like to force close it or just keep waiting?' detail: 'The window is not responding. Would you like to force close it or just keep waiting?'
}); })
if (chosen === 0) window.destroy(); if (chosen === 0) window.destroy()
}); })
// For session's download test, listen 'will-download' event in browser, and // For session's download test, listen 'will-download' event in browser, and
// reply the result to renderer for verifying // reply the result to renderer for verifying
var downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf'); var downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf')
ipcMain.on('set-download-option', function (event, need_cancel, prevent_default) { ipcMain.on('set-download-option', function (event, need_cancel, prevent_default) {
window.webContents.session.once('will-download', function (e, item) { window.webContents.session.once('will-download', function (e, item) {
if (prevent_default) { if (prevent_default) {
e.preventDefault(); e.preventDefault()
const url = item.getURL(); const url = item.getURL()
const filename = item.getFilename(); const filename = item.getFilename()
setImmediate(function () { setImmediate(function () {
try { try {
item.getURL(); item.getURL()
} catch(err) { } catch(err) {
window.webContents.send('download-error', url, filename, err.message); window.webContents.send('download-error', url, filename, err.message)
} }
}); })
} else { } else {
item.setSavePath(downloadFilePath); item.setSavePath(downloadFilePath)
item.on('done', function (e, state) { item.on('done', function (e, state) {
window.webContents.send('download-done', window.webContents.send('download-done',
state, state,
@ -130,23 +130,23 @@ app.on('ready', function() {
item.getReceivedBytes(), item.getReceivedBytes(),
item.getTotalBytes(), item.getTotalBytes(),
item.getContentDisposition(), item.getContentDisposition(),
item.getFilename()); item.getFilename())
}); })
if (need_cancel) if (need_cancel)
item.cancel(); item.cancel()
} }
}); })
event.returnValue = "done"; event.returnValue = 'done'
}); })
ipcMain.on('executeJavaScript', function (event, code, hasCallback) { ipcMain.on('executeJavaScript', function (event, code, hasCallback) {
if (hasCallback) { if (hasCallback) {
window.webContents.executeJavaScript(code, (result) => { window.webContents.executeJavaScript(code, (result) => {
window.webContents.send('executeJavaScript-response', result); window.webContents.send('executeJavaScript-response', result)
}); })
} else { } else {
window.webContents.executeJavaScript(code); window.webContents.executeJavaScript(code)
event.returnValue = "success"; event.returnValue = 'success'
} }
}); })
}); })

File diff suppressed because it is too large Load diff

View file

@ -1,31 +1,31 @@
var app = require('app'); var app = require('app')
var fs = require('fs'); var fs = require('fs')
var path = require('path'); var path = require('path')
var request = require('request'); var request = require('request')
var TARGET_URL = 'https://atom.io/download/atom-shell/index.json'; var TARGET_URL = 'https://atom.io/download/atom-shell/index.json'
function getDate () { function getDate () {
var today = new Date(); var today = new Date()
var year = today.getFullYear(); var year = today.getFullYear()
var month = today.getMonth() + 1; var month = today.getMonth() + 1
if (month <= 9) if (month <= 9)
month = '0' + month; month = '0' + month
var day= today.getDate(); var day = today.getDate()
if (day <= 9) if (day <= 9)
day = '0' + day; day = '0' + day
return year + '-' + month + '-' + day; return year + '-' + month + '-' + day
} }
function getInfoForCurrentVersion () { function getInfoForCurrentVersion () {
var json = {}; var json = {}
json.version = process.versions['atom-shell']; json.version = process.versions['atom-shell']
json.date = getDate(); json.date = getDate()
var names = ['node', 'v8', 'uv', 'zlib', 'openssl', 'modules', 'chrome'] var names = ['node', 'v8', 'uv', 'zlib', 'openssl', 'modules', 'chrome']
for (var i in names) { for (var i in names) {
var name = names[i]; var name = names[i]
json[name] = process.versions[name]; json[name] = process.versions[name]
} }
json.files = [ json.files = [
@ -39,44 +39,44 @@ function getInfoForCurrentVersion() {
'win32-ia32-symbols', 'win32-ia32-symbols',
'win32-x64', 'win32-x64',
'win32-x64-symbols', 'win32-x64-symbols',
]; ]
return json; return json
} }
function getIndexJsInServer (callback) { function getIndexJsInServer (callback) {
request(TARGET_URL, function (e, res, body) { request(TARGET_URL, function (e, res, body) {
if (e) if (e)
callback(e); callback(e)
else if (res.statusCode != 200) else if (res.statusCode != 200)
callback(new Error('Server returned ' + res.statusCode)); callback(new Error('Server returned ' + res.statusCode))
else else
callback(null, JSON.parse(body)); callback(null, JSON.parse(body))
}); })
} }
function findObjectByVersion (all, version) { function findObjectByVersion (all, version) {
for (var i in all) for (var i in all)
if (all[i].version == version) if (all[i].version == version)
return i; return i
return -1; return -1
} }
app.on('ready', function () { app.on('ready', function () {
getIndexJsInServer(function (e, all) { getIndexJsInServer(function (e, all) {
if (e) { if (e) {
console.error(e); console.error(e)
process.exit(1); process.exit(1)
} }
var current = getInfoForCurrentVersion(); var current = getInfoForCurrentVersion()
var found = findObjectByVersion(all, current.version); var found = findObjectByVersion(all, current.version)
if (found == -1) if (found == -1)
all.unshift(current); all.unshift(current)
else else
all[found] = current; all[found] = current
fs.writeFileSync(process.argv[2], JSON.stringify(all)); fs.writeFileSync(process.argv[2], JSON.stringify(all))
process.exit(0); process.exit(0)
}); })
}); })

View file

@ -1,12 +1,12 @@
var fs = require('fs'); var fs = require('fs')
var path = require('path'); var path = require('path')
var runas = require('runas'); var runas = require('runas')
var source = path.resolve(__dirname, '..', '..', 'vendor', 'breakpad', 'msdia80.dll'); var source = path.resolve(__dirname, '..', '..', 'vendor', 'breakpad', 'msdia80.dll')
var target = 'C:\\Program Files\\Common Files\\Microsoft Shared\\VC\\msdia80.dll'; var target = 'C:\\Program Files\\Common Files\\Microsoft Shared\\VC\\msdia80.dll'
if (fs.existsSync(target))
return;
if (!fs.existsSync(target)) {
runas('cmd', runas('cmd',
['/K', 'copy', source, target, '&', 'regsvr32', '/s', target, '&', 'exit'], ['/K', 'copy', source, target, '&', 'regsvr32', '/s', target, '&', 'exit'],
{admin: true}); {admin: true})
}