api-crash-reporter-spec.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. const assert = require('assert')
  2. const childProcess = require('child_process')
  3. const fs = require('fs')
  4. const http = require('http')
  5. const multiparty = require('multiparty')
  6. const path = require('path')
  7. const temp = require('temp').track()
  8. const url = require('url')
  9. const {closeWindow} = require('./window-helpers')
  10. const {remote} = require('electron')
  11. const {app, BrowserWindow, crashReporter} = remote.require('electron')
  12. describe('crashReporter module', () => {
  13. if (process.mas || process.env.DISABLE_CRASH_REPORTER_TESTS) return
  14. let originalTempDirectory = null
  15. let tempDirectory = null
  16. before(() => {
  17. tempDirectory = temp.mkdirSync('electronCrashReporterSpec-')
  18. originalTempDirectory = app.getPath('temp')
  19. app.setPath('temp', tempDirectory)
  20. })
  21. after(() => {
  22. app.setPath('temp', originalTempDirectory)
  23. })
  24. const fixtures = path.resolve(__dirname, 'fixtures')
  25. const generateSpecs = (description, browserWindowOpts) => {
  26. describe(description, () => {
  27. let w = null
  28. let stopServer = null
  29. beforeEach(() => {
  30. stopServer = null
  31. w = new BrowserWindow(Object.assign({ show: false }, browserWindowOpts))
  32. })
  33. afterEach(() => closeWindow(w).then(() => { w = null }))
  34. afterEach(() => {
  35. stopCrashService()
  36. })
  37. afterEach((done) => {
  38. if (stopServer != null) {
  39. stopServer(done)
  40. } else {
  41. done()
  42. }
  43. })
  44. it('should send minidump when renderer crashes', function (done) {
  45. // TODO(alexeykuzmin): Skip the test instead of marking it as passed.
  46. if (process.env.APPVEYOR === 'True') return done()
  47. this.timeout(180000)
  48. stopServer = startServer({
  49. callback (port) {
  50. const crashUrl = url.format({
  51. protocol: 'file',
  52. pathname: path.join(fixtures, 'api', 'crash.html'),
  53. search: '?port=' + port
  54. })
  55. w.loadURL(crashUrl)
  56. },
  57. processType: 'renderer',
  58. done: done
  59. })
  60. })
  61. it('should send minidump when node processes crash', function (done) {
  62. // TODO(alexeykuzmin): Skip the test instead of marking it as passed.
  63. if (process.env.APPVEYOR === 'True') return done()
  64. this.timeout(180000)
  65. stopServer = startServer({
  66. callback (port) {
  67. const crashesDir = path.join(app.getPath('temp'), `${process.platform === 'win32' ? 'Zombies' : app.getName()} Crashes`)
  68. const version = app.getVersion()
  69. const crashPath = path.join(fixtures, 'module', 'crash.js')
  70. if (process.platform === 'win32') {
  71. const crashServiceProcess = childProcess.spawn(process.execPath, [
  72. `--reporter-url=http://127.0.0.1:${port}`,
  73. '--application-name=Zombies',
  74. `--crashes-directory=${crashesDir}`
  75. ], {
  76. env: {
  77. ELECTRON_INTERNAL_CRASH_SERVICE: 1
  78. },
  79. detached: true
  80. })
  81. remote.process.crashServicePid = crashServiceProcess.pid
  82. }
  83. childProcess.fork(crashPath, [port, version, crashesDir], {silent: true})
  84. },
  85. processType: 'browser',
  86. done: done
  87. })
  88. })
  89. it('should not send minidump if uploadToServer is false', function (done) {
  90. this.timeout(180000)
  91. let dumpFile
  92. let crashesDir = crashReporter.getCrashesDirectory()
  93. const existingDumpFiles = new Set()
  94. if (process.platform === 'darwin') {
  95. // crashpad puts the dump files in the "completed" subdirectory
  96. crashesDir = path.join(crashesDir, 'completed')
  97. crashReporter.setUploadToServer(false)
  98. }
  99. const testDone = (uploaded) => {
  100. if (uploaded) return done(new Error('Uploaded crash report'))
  101. if (process.platform === 'darwin') crashReporter.setUploadToServer(true)
  102. assert(fs.existsSync(dumpFile))
  103. done()
  104. }
  105. let pollInterval
  106. const pollDumpFile = () => {
  107. fs.readdir(crashesDir, (err, files) => {
  108. if (err) return
  109. const dumps = files.filter((file) => /\.dmp$/.test(file) && !existingDumpFiles.has(file))
  110. if (!dumps.length) return
  111. assert.equal(1, dumps.length)
  112. dumpFile = path.join(crashesDir, dumps[0])
  113. clearInterval(pollInterval)
  114. // dump file should not be deleted when not uploading, so we wait
  115. // 1s and assert it still exists in `testDone`
  116. setTimeout(testDone, 1000)
  117. })
  118. }
  119. remote.ipcMain.once('list-existing-dumps', (event) => {
  120. fs.readdir(crashesDir, (err, files) => {
  121. if (!err) {
  122. for (const file of files) {
  123. if (/\.dmp$/.test(file)) {
  124. existingDumpFiles.add(file)
  125. }
  126. }
  127. }
  128. event.returnValue = null // allow the renderer to crash
  129. pollInterval = setInterval(pollDumpFile, 100)
  130. })
  131. })
  132. stopServer = startServer({
  133. callback (port) {
  134. const crashUrl = url.format({
  135. protocol: 'file',
  136. pathname: path.join(fixtures, 'api', 'crash.html'),
  137. search: `?port=${port}&skipUpload=1`
  138. })
  139. w.loadURL(crashUrl)
  140. },
  141. processType: 'renderer',
  142. done: testDone.bind(null, true)
  143. })
  144. })
  145. it('should send minidump with updated extra parameters', function (done) {
  146. // TODO(alexeykuzmin): Skip the test instead of marking it as passed.
  147. if (process.env.APPVEYOR === 'True') return done()
  148. this.timeout(180000)
  149. stopServer = startServer({
  150. callback (port) {
  151. const crashUrl = url.format({
  152. protocol: 'file',
  153. pathname: path.join(fixtures, 'api', 'crash-restart.html'),
  154. search: `?port=${port}`
  155. })
  156. w.loadURL(crashUrl)
  157. },
  158. processType: 'renderer',
  159. done: done
  160. })
  161. })
  162. })
  163. }
  164. generateSpecs('without sandbox', {})
  165. generateSpecs('with sandbox', {
  166. webPreferences: {
  167. sandbox: true,
  168. preload: path.join(fixtures, 'module', 'preload-sandbox.js')
  169. }
  170. })
  171. describe('getProductName', () => {
  172. it('returns the product name if one is specified', () => {
  173. const name = crashReporter.getProductName()
  174. const expectedName = (process.platform === 'darwin') ? 'Electron Test' : 'Zombies'
  175. assert.equal(name, expectedName)
  176. })
  177. })
  178. describe('getTempDirectory', () => {
  179. it('returns temp directory for app if one is specified', () => {
  180. const tempDir = crashReporter.getTempDirectory()
  181. assert.equal(tempDir, app.getPath('temp'))
  182. })
  183. })
  184. describe('start(options)', () => {
  185. it('requires that the companyName and submitURL options be specified', () => {
  186. assert.throws(() => {
  187. crashReporter.start({companyName: 'Missing submitURL'})
  188. }, /submitURL is a required option to crashReporter\.start/)
  189. assert.throws(() => {
  190. crashReporter.start({submitURL: 'Missing companyName'})
  191. }, /companyName is a required option to crashReporter\.start/)
  192. })
  193. it('can be called multiple times', () => {
  194. assert.doesNotThrow(() => {
  195. crashReporter.start({
  196. companyName: 'Umbrella Corporation',
  197. submitURL: 'http://127.0.0.1/crashes'
  198. })
  199. crashReporter.start({
  200. companyName: 'Umbrella Corporation 2',
  201. submitURL: 'http://127.0.0.1/more-crashes'
  202. })
  203. })
  204. })
  205. })
  206. describe('getCrashesDirectory', () => {
  207. it('correctly returns the directory', () => {
  208. const crashesDir = crashReporter.getCrashesDirectory()
  209. let dir
  210. if (process.platform === 'win32') {
  211. dir = `${app.getPath('temp')}/Zombies Crashes`
  212. } else {
  213. dir = `${app.getPath('temp')}/Electron Test Crashes`
  214. }
  215. assert.equal(crashesDir, dir)
  216. })
  217. })
  218. describe('getUploadedReports', () => {
  219. it('returns an array of reports', () => {
  220. const reports = crashReporter.getUploadedReports()
  221. assert(typeof reports === 'object')
  222. })
  223. })
  224. describe('getLastCrashReport', () => {
  225. it('correctly returns the most recent report', () => {
  226. const reports = crashReporter.getUploadedReports()
  227. const lastReport = crashReporter.getLastCrashReport()
  228. // Let's find the newest report
  229. const newestReport = reports.reduce((acc, cur) => {
  230. const timestamp = new Date(cur.date).getTime()
  231. return (timestamp > acc.timestamp)
  232. ? { report: cur, timestamp: timestamp }
  233. : acc
  234. }, { timestamp: 0 })
  235. assert(reports.length > 1, 'has more than 1 report')
  236. assert(lastReport != null, 'found a last report')
  237. assert(lastReport.date.toString() === newestReport.report.date.toString(),
  238. 'last report is correct')
  239. })
  240. })
  241. describe('getUploadToServer()', () => {
  242. it('throws an error when called from the renderer process', () => {
  243. assert.throws(() => require('electron').crashReporter.getUploadToServer())
  244. })
  245. it('returns true when uploadToServer is set to true', function () {
  246. if (process.platform !== 'darwin') {
  247. // FIXME(alexeykuzmin): Skip the test.
  248. // this.skip()
  249. return
  250. }
  251. crashReporter.start({
  252. companyName: 'Umbrella Corporation',
  253. submitURL: 'http://127.0.0.1/crashes',
  254. uploadToServer: true
  255. })
  256. assert.equal(crashReporter.getUploadToServer(), true)
  257. })
  258. it('returns false when uploadToServer is set to false', function () {
  259. if (process.platform !== 'darwin') {
  260. // FIXME(alexeykuzmin): Skip the test.
  261. // this.skip()
  262. return
  263. }
  264. crashReporter.start({
  265. companyName: 'Umbrella Corporation',
  266. submitURL: 'http://127.0.0.1/crashes',
  267. uploadToServer: true
  268. })
  269. crashReporter.setUploadToServer(false)
  270. assert.equal(crashReporter.getUploadToServer(), false)
  271. })
  272. })
  273. describe('setUploadToServer(uploadToServer)', () => {
  274. it('throws an error when called from the renderer process', () => {
  275. assert.throws(() => require('electron').crashReporter.setUploadToServer('arg'))
  276. })
  277. it('sets uploadToServer false when called with false', function () {
  278. if (process.platform !== 'darwin') {
  279. // FIXME(alexeykuzmin): Skip the test.
  280. // this.skip()
  281. return
  282. }
  283. crashReporter.start({
  284. companyName: 'Umbrella Corporation',
  285. submitURL: 'http://127.0.0.1/crashes',
  286. uploadToServer: true
  287. })
  288. crashReporter.setUploadToServer(false)
  289. assert.equal(crashReporter.getUploadToServer(), false)
  290. })
  291. it('sets uploadToServer true when called with true', function () {
  292. if (process.platform !== 'darwin') {
  293. // FIXME(alexeykuzmin): Skip the test.
  294. // this.skip()
  295. return
  296. }
  297. crashReporter.start({
  298. companyName: 'Umbrella Corporation',
  299. submitURL: 'http://127.0.0.1/crashes',
  300. uploadToServer: false
  301. })
  302. crashReporter.setUploadToServer(true)
  303. assert.equal(crashReporter.getUploadToServer(), true)
  304. })
  305. })
  306. describe('Parameters', () => {
  307. it('returns all of the current parameters', () => {
  308. crashReporter.start({
  309. companyName: 'Umbrella Corporation',
  310. submitURL: 'http://127.0.0.1/crashes'
  311. })
  312. const parameters = crashReporter.getParameters()
  313. assert(typeof parameters === 'object')
  314. })
  315. it('adds a parameter to current parameters', function () {
  316. if (process.platform !== 'darwin') {
  317. // FIXME(alexeykuzmin): Skip the test.
  318. // this.skip()
  319. return
  320. }
  321. crashReporter.start({
  322. companyName: 'Umbrella Corporation',
  323. submitURL: 'http://127.0.0.1/crashes'
  324. })
  325. crashReporter.addExtraParameter('hello', 'world')
  326. assert('hello' in crashReporter.getParameters())
  327. })
  328. it('removes a parameter from current parameters', function () {
  329. if (process.platform !== 'darwin') {
  330. // FIXME(alexeykuzmin): Skip the test.
  331. // this.skip()
  332. return
  333. }
  334. crashReporter.start({
  335. companyName: 'Umbrella Corporation',
  336. submitURL: 'http://127.0.0.1/crashes'
  337. })
  338. crashReporter.addExtraParameter('hello', 'world')
  339. assert('hello' in crashReporter.getParameters())
  340. crashReporter.removeExtraParameter('hello')
  341. assert(!('hello' in crashReporter.getParameters()))
  342. })
  343. })
  344. })
  345. const waitForCrashReport = () => {
  346. return new Promise((resolve, reject) => {
  347. let times = 0
  348. const checkForReport = () => {
  349. if (crashReporter.getLastCrashReport() != null) {
  350. resolve()
  351. } else if (times >= 10) {
  352. reject(new Error('No crash report available'))
  353. } else {
  354. times++
  355. setTimeout(checkForReport, 100)
  356. }
  357. }
  358. checkForReport()
  359. })
  360. }
  361. const startServer = ({callback, processType, done}) => {
  362. let called = false
  363. let server = http.createServer((req, res) => {
  364. const form = new multiparty.Form()
  365. form.parse(req, (error, fields) => {
  366. if (error) throw error
  367. if (called) return
  368. called = true
  369. assert.equal(fields.prod, 'Electron')
  370. assert.equal(fields.ver, process.versions.electron)
  371. assert.equal(fields.process_type, processType)
  372. assert.equal(fields.platform, process.platform)
  373. assert.equal(fields.extra1, 'extra1')
  374. assert.equal(fields.extra2, 'extra2')
  375. assert.equal(fields.extra3, undefined)
  376. assert.equal(fields._productName, 'Zombies')
  377. assert.equal(fields._companyName, 'Umbrella Corporation')
  378. assert.equal(fields._version, app.getVersion())
  379. const reportId = 'abc-123-def-456-abc-789-abc-123-abcd'
  380. res.end(reportId, () => {
  381. waitForCrashReport().then(() => {
  382. assert.equal(crashReporter.getLastCrashReport().id, reportId)
  383. assert.notEqual(crashReporter.getUploadedReports().length, 0)
  384. assert.equal(crashReporter.getUploadedReports()[0].id, reportId)
  385. req.socket.destroy()
  386. done()
  387. }, done)
  388. })
  389. })
  390. })
  391. const activeConnections = new Set()
  392. server.on('connection', (connection) => {
  393. activeConnections.add(connection)
  394. connection.once('close', () => {
  395. activeConnections.delete(connection)
  396. })
  397. })
  398. let {port} = remote.process
  399. server.listen(port, '127.0.0.1', () => {
  400. port = server.address().port
  401. remote.process.port = port
  402. if (process.platform === 'darwin') {
  403. crashReporter.start({
  404. companyName: 'Umbrella Corporation',
  405. submitURL: 'http://127.0.0.1:' + port
  406. })
  407. }
  408. callback(port)
  409. })
  410. return function stopServer (done) {
  411. for (const connection of activeConnections) {
  412. connection.destroy()
  413. }
  414. server.close(() => {
  415. done()
  416. })
  417. }
  418. }
  419. const stopCrashService = () => {
  420. const {crashServicePid} = remote.process
  421. if (crashServicePid) {
  422. remote.process.crashServicePid = 0
  423. try {
  424. process.kill(crashServicePid)
  425. } catch (error) {
  426. if (error.code !== 'ESRCH') {
  427. throw error
  428. }
  429. }
  430. }
  431. }