launchTestController.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /**
  2. * Controller for the test launching page (the waiting page, after the user submited a test on the index page)
  3. */
  4. var async = require('async');
  5. var fs = require ('fs');
  6. var strReplace = require('../lib/strReplace');
  7. var launchTestController = function(req, res, testQueue, googleAnalyticsId) {
  8. 'use strict';
  9. var resultsPath = 'results/' + testId;
  10. var phantomasResultsPath = resultsPath + '/results.json';
  11. var url = req.body.url;
  12. var options = {};
  13. if (req.body.timeout) {
  14. options.timeout = req.body.timeout;
  15. }
  16. async.waterfall([
  17. function htmlTemplate(callback) {
  18. fs.readFile('./app/node_views/launchTest.html', {encoding: 'utf8'}, callback);
  19. },
  20. function sendResponse(html, callback) {
  21. html = strReplace(html, '%%TEST_URL%%', url);
  22. html = strReplace(html, '%%TEST_ID%%', testId);
  23. html = strReplace(html, '%%GA_ID%%', googleAnalyticsId);
  24. res.setHeader('Content-Type', 'text/html');
  25. res.send(html);
  26. callback();
  27. },
  28. function createFolder(callback) {
  29. // Create results folder
  30. fs.mkdir(resultsPath, callback);
  31. },
  32. function executePhantomas(callback) {
  33. console.log('Adding test ' + testId + ' on ' + url + ' to the queue');
  34. var task = {
  35. testId: testId,
  36. url: url,
  37. options: options
  38. };
  39. testQueue.push(task, callback);
  40. },
  41. function writeResults(json, resultsObject, callback) {
  42. console.log('Saving Phantomas results file to ' + phantomasResultsPath);
  43. fs.writeFile(phantomasResultsPath, JSON.stringify(json, null, 4), callback);
  44. }
  45. ], function(err) {
  46. if (err) {
  47. console.log('An error occured in the phantomas test: ', err);
  48. fs.writeFile(phantomasResultsPath, JSON.stringify({url: url, error: err}, null, 4), function(err) {
  49. if (err) {
  50. console.log('Could not even write an error message on file ' + phantomasResultsPath);
  51. console.log(err);
  52. }
  53. });
  54. testQueue.testFailed(testId);
  55. } else {
  56. testQueue.testComplete(testId);
  57. }
  58. });
  59. };
  60. module.exports = launchTestController;