runner.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. var http = require('http')
  2. var constant = require('./constants')
  3. var helper = require('./helper')
  4. var cfg = require('./config')
  5. var logger = require('./logger')
  6. var log = logger.create('runner')
  7. var parseExitCode = function (buffer, defaultCode, failOnEmptyTestSuite) {
  8. var tailPos = buffer.length - Buffer.byteLength(constant.EXIT_CODE) - 2
  9. if (tailPos < 0) {
  10. return {exitCode: defaultCode, buffer: buffer}
  11. }
  12. // tail buffer which might contain the message
  13. var tail = buffer.slice(tailPos)
  14. var tailStr = tail.toString()
  15. if (tailStr.substr(0, tailStr.length - 2) === constant.EXIT_CODE) {
  16. var emptyInt = parseInt(tailStr.substr(-2, 1), 10)
  17. var exitCode = parseInt(tailStr.substr(-1), 10)
  18. if (failOnEmptyTestSuite === false && emptyInt === 0) {
  19. log.warn('Test suite was empty.')
  20. exitCode = 0
  21. }
  22. return {exitCode: exitCode, buffer: buffer.slice(0, tailPos)}
  23. }
  24. return {exitCode: defaultCode, buffer: buffer}
  25. }
  26. // TODO(vojta): read config file (port, host, urlRoot)
  27. exports.run = function (config, done) {
  28. config = config || {}
  29. logger.setupFromConfig(config)
  30. done = helper.isFunction(done) ? done : process.exit
  31. config = cfg.parseConfig(config.configFile, config)
  32. var exitCode = 1
  33. var options = {
  34. hostname: config.hostname,
  35. path: config.urlRoot + 'run',
  36. port: config.port,
  37. method: 'POST',
  38. headers: {
  39. 'Content-Type': 'application/json'
  40. }
  41. }
  42. var request = http.request(options, function (response) {
  43. response.on('data', function (buffer) {
  44. var parsedResult = parseExitCode(buffer, exitCode, config.failOnEmptyTestSuite)
  45. exitCode = parsedResult.exitCode
  46. process.stdout.write(parsedResult.buffer)
  47. })
  48. response.on('end', function () {
  49. done(exitCode)
  50. })
  51. })
  52. request.on('error', function (e) {
  53. if (e.code === 'ECONNREFUSED') {
  54. log.error('There is no server listening on port %d', options.port)
  55. done(1, e.code)
  56. } else {
  57. throw e
  58. }
  59. })
  60. request.end(JSON.stringify({
  61. args: config.clientArgs,
  62. removedFiles: config.removedFiles,
  63. changedFiles: config.changedFiles,
  64. addedFiles: config.addedFiles,
  65. refresh: config.refresh,
  66. colors: config.colors
  67. }))
  68. }