Code coverage report for lib/test.js

Statements: 40.91% (189 / 462)      Branches: 26.46% (77 / 291)      Functions: 46.51% (20 / 43)      Lines: 40.91% (189 / 462)      Ignored: none     

All files » lib/ » test.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 7091   1 1 1   1 1 1 1 1 1 1 1   1 53     1 1   1     1 1 1 1 1 1 1 1   1 1 1 1   1 1 1 1 1 1   1 1   1 1 1 1   1                                   1   1     1           1                       1                                                                       1                                           1                                                       1                                                                                                                               1             1 27 27 689 689 689 689 1754     27 27         1   53     53   53         53 53 27 27 27     27           53   53 53 53 53 53     53               53 27   53 26 26     27     27 27 27 27 27   27   27 689     27   27 27     27 27 27     27 27 27 27 27 27 27   27   27 27 27 27 27     27       27 27 21         1                                                                                                                                           1 27     27     27 27 26 26 26   27     1       1 27     27     27     27     27   27 27                                     27     27 27 27             27         27 27       27         27 27 27         27   27 27   27   27   27 27     27         27             27     27     27     27       1                                                 1                     1       1 27   27 27     1                                           1 14     14     14     14     14 27 27 27 27   27       27 27     27       1                             1 1808     1808 1 1     1808     1                     1  
module.exports = Test
 
var Readable = require('stream').Readable
var util = require('util')
util.inherits(Test, Readable)
 
var yaml = require('js-yaml')
var domain = require('domain')
var stack = require('./stack.js')
var tapAsserts = require('./assert.js')
var assert = require('assert')
var spawn = require('child_process').spawn
var Parser = require('tap-parser')
var path = require('path')
 
function hasOwn (obj, key) {
  return Object.prototype.hasOwnProperty.call(obj, key)
}
 
function Test (options) {
  options = options || {}
 
  Iif (!(this instanceof Test))
    return new Test(options)
 
  this._name = ''
  this._ok = true
  this._pass = 0
  this._fail = 0
  this._skip = 0
  this._todo = 0
  this._count = 0
  this._bailedOut = false
 
  this._passes = []
  this._fails = []
  this._skips = []
  this._todos = []
 
  this._plan = -1
  this._queue = []
  this._currentChild = null
  this._ending = false
  this._ended = false
  this._planFinished = false
 
  this._parent = null
  this._printedVersion = false
 
  this._domain = domain.create()
  this._domain.add(this)
  this._domain.owner = this
  this._domain.on('error', domainError)
 
  Iif (options.timeout !== Infinity && !isNaN(options.timeout) && options.timeout > 0) {
    var timeout = options.timeout || 30000
    var self = this
    var timerAt = stack.at(Test.prototype.test)
    if (!timerAt.file)
      timerAt = stack.at(Test)
    this._timer = setTimeout(function () {
      self._queue = self._queue.filter(function (q) {
        return q[0] !== 'end'
      })
      self._plan = -1
      self.fail('timeout!', { at: timerAt })
      self.endAll()
    }, timeout)
    if (this._timer.unref)
      this._timer.unref()
  }
 
  this._startTime = process.hrtime()
 
  Readable.apply(this, options)
}
 
function domainError (er) {
  delete er.domain
  delete er.domainThrown
  this.owner.threw(er)
}
 
Test.prototype.endAll = function () {
  var child = this._currentChild
  if (child) {
    child.endAll()
    child.end()
    child.emit('end')
    child._bailedOut = true
  }
 
  this.end()
}
 
Test.prototype._extraFromError = function (er, extra) {
  extra = extra || {}
 
  var message = er.message
  var addName = true
 
  if (!message && er.stack) {
    message = er.stack.split('\n')[0]
    addName = false
  }
 
  er.message = ''
  var st = er.stack
  if (st) {
    extra.stack = st.split('\n').slice(1).map(function (line) {
      return line.trim().replace(/^at /, '')
    })
    // parse out the 'at' bit from the first line.
    extra.at = stack.parseLine(extra.stack[0])
  }
  er.message = message
 
  if (addName && er.name)
    message = er.name + ': ' + message
 
  Object.keys(er).forEach(function (k) {
    if (k === 'message')
      return
    extra[k] = er[k]
  })
 
  extra.message = message
 
  return extra
}
 
Test.prototype.threw = function threw (er, extra, proxy) {
  this._ok = false
  this._threw = this._threw || er
 
  if (!extra)
    extra = this._extraFromError(er)
 
  // If we've already ended, then try to pass this up the chain
  // Presumably, eventually the root harness will catch it and
  // deal with it, since that only ends on process exit.
  if (this._ended) {
    if (this._parent)
      return this._parent.threw(er, extra, true)
    else
      throw er
  }
 
  this.fail(extra.message || er.message, extra)
  if (!proxy)
    this.end()
}
 
Test.prototype.plan = function (n, comment) {
  if (this._bailedOut)
    return
 
  if (this._currentChild) {
    this._queue.push(['plan', n, comment])
    return
  }
 
  if (this._plan !== -1)
    throw new Error('Cannot set plan more than once')
 
  if (typeof n !== 'number' || n < 0)
    throw new Error('plan must be a number')
 
  // Cannot get any tests after a trailing plan, or a plan of 0
  var ending = false
  if (this._count !== 0 || n === 0)
    ending = true
 
  this._plan = n
  comment = comment ? ' # ' + comment.trim() : ''
  this.push('1..' + n + comment + '\n')
 
  if (ending)
    this.end()
}
 
Test.prototype.test = function test (name, extra, cb) {
  if (this._bailedOut)
    return
 
  if (typeof name === 'function') {
    cb = name
    name = ''
    extra = {}
  } else if (typeof extra === 'function') {
    cb = extra
    extra = {}
  }
 
  if (!cb) {
    extra = extra || {}
    extra.todo = true
  } else if (typeof cb !== 'function')
    throw new Error('test() requires a callback')
 
  if (extra.skip || extra.todo)
    return this.pass(name, extra)
 
  // will want this captured now in case child fails.
  if (!hasOwn(extra, 'at'))
    extra.at = stack.at(test)
 
  if (this._currentChild) {
    this._queue.push(['test', name, extra, cb])
    return
  }
 
  var child = new Test(extra)
 
  child._name = name
  child._parent = this
  this._currentChild = child
  var self = this
  childStream(self, child)
  var results
  child.on('complete', function (res) {
    results = res
  })
  child.on('end', function () {
    extra.results = results
    self._currentChild = null
    name += ' # time=' + results.time + 'ms'
    self.ok(child._ok, name, extra)
    self._processQueue()
  })
  child.on('bailout', function (message) {
    self.bailout(message)
  })
 
  // still need try/catch for synchronous errors
  self._level = child
  child.comment('Subtest: ' + name)
  try {
    child._domain.bind(cb)(child)
  } catch (er) {
    child.threw(er)
  }
  self._level = self
}
 
Test.prototype.current = function () {
  var t = this
  while (t._level && t !== t._level)
    t = t._level
  return t
}
 
function childStream (self, child) {
  var linebuf = ''
  child.on('data', function (c) {
    linebuf += c
    var lines = linebuf.split('\n')
    linebuf = lines.pop()
    lines.forEach(function (line) {
      self.push('    ' + line + '\n')
    })
  })
  child.on('end', function () {
    Iif (linebuf)
      self.push('    ' + linebuf + '\n')
  })
}
 
Test.prototype.spawn = function spawnTest (cmd, args, options, name, extra) {
 
  Iif (typeof args === 'string')
    args = [ args ]
 
  args = args || []
 
  Iif (typeof options === 'string') {
    name = options
    options = {}
  }
 
  options = options || {}
  if (!name) {
    Eif (cmd === process.execPath) {
      name = args.map(function (a) {
        Iif (a.indexOf(process.cwd()) === 0)
          return './' + a.substr(process.cwd().length + 1)
        else
          return a
      }).join(' ')
    } else
      name = cmd + ' ' + args.join(' ')
  }
 
  extra = extra || {}
 
  assert.equal(typeof cmd, 'string')
  assert(Array.isArray(args))
  assert.equal(options && typeof options, 'object')
  assert.equal(typeof name, 'string')
  assert.equal(extra && typeof extra, 'object')
 
  // stdout must be a pipe
  Iif (options.stdio) {
    if (typeof options.stdio === 'string')
      options.stdio = [ options.stdio, 'pipe', options.stdio ]
    else
      options.stdio[1] = 'pipe'
  }
 
  // will want this captured now in case child fails, before enqueue
  if (!hasOwn(extra, 'at'))
    extra.at = stack.at(spawnTest)
 
  if (this._currentChild) {
    this._queue.push(['spawn', cmd, args, options, name, extra])
    return
  }
 
  Iif (extra.skip)
    return this.pass(name, extra)
 
  var start = process.hrtime()
  var child = spawn(cmd, args, options)
  var parser = new Parser()
  var self = this
  this._currentChild = child
 
  childStream(self, child.stdout)
 
  child.stdout.on('data', function (c) {
    parser.write(c)
  })
 
  child.stdout.emit('data', '# Subtest: ' + name + '\n')
 
  child.stdout.on('end', function () {
    parser.end()
  })
 
  var results
  parser.on('complete', function (res) {
    results = res
  })
 
  child.on('close', function onclose (code, signal) {
    self._currentChild = null
    extra.results = results
    var dur = process.hrtime(start)
    var time = Math.round(dur[0] * 1e6 + dur[1] / 1e3) / 1e3
    name += ' # time=' + time + 'ms'
    Iif (code)
      extra.exitCode = code
    Iif (signal)
      extra.signal = signal
    extra.command = cmd
    extra.arguments = args
    extra.options = options
    self.ok(results.ok, name, extra)
    self._processQueue()
  })
 
  parser.on('bailout', function (message) {
    self.bailout(message)
  })
 
  Eif (child.stderr) {
    child.stderr.on('data', function (c) {
      process.stderr.write(c)
    })
  }
}
 
Test.prototype.end = function end () {
  if (this._bailedOut)
    return
 
  if (this._ended || this._ending)
    return
 
  if (this._currentChild) {
    this._queue.push(['end'])
    return
  }
 
  clearTimeout(this._timer)
  // Emiting the missing tests can trigger a call to end()
  // guard against that with the 'ending' flag
  this._ending = true
  while (this._count < this._plan) {
    this.fail('missing test', { at: false })
  }
 
  if (this._plan === -1)
    this.plan(this._count)
 
  var final = {
    plan: { start: 1, end: this._plan },
    count: this._count,
    pass: this._pass,
    ok: this._ok
  }
 
  if (this._fail)
    final.fail = this._fail
 
  if (this._bailedOut)
    final.bailout = true
 
  if (this._todo)
    final.todo = this._todo
 
  if (this._skip)
    final.skip = this._skip
 
  this._ended = true
 
  // This is nice, but too noisy.
  // TODO: prove-style commenting at the end.
  // this.comment(final)
  if (!this._ok) {
    // comment a bit at the end so we know what happened.
    if (this._plan !== this._count)
      this.comment('actual test count(%d) != plan(%d)',
                   this._count, this._plan)
 
    if (this._fail > 0)
      this.comment('failed %d of %d tests', this._fail, this._count)
    if (this._todo > 0)
      this.comment('todo: %d', this._todo)
    if (this._skip > 0)
      this.comment('skip: %d', this._skip)
  }
 
  var dur = process.hrtime(this._startTime)
  final.time = Math.round(dur[0] * 1e6 + dur[1] / 1e3) / 1e3
  if (!this._parent)
    this.comment('time=%sms', final.time)
 
  this.emit('complete', final)
  this.push(null)
}
 
Test.prototype._processQueue = function () {
  Iif (this._bailedOut)
    return
 
  Iif (this._processingQueue)
    return
 
  this._processingQueue = true
  while (this._queue.length && !this._currentChild) {
    var q = this._queue.shift()
    var m = q.shift()
    this[m].apply(this, q)
  }
  this._processingQueue = false
}
 
Test.prototype._read = function (n, cb) {}
 
 
 
Test.prototype.printResult = function printResult (ok, message, extra) {
  Iif (this._bailedOut)
    return
 
  Iif (typeof ok !== 'boolean')
    throw new TypeError('boolean `ok` required')
 
  Iif (typeof message !== 'string')
    throw new TypeError('string `message` required')
 
  Iif (extra && typeof extra !== 'object')
    throw new TypeError('optional `extra` arg must be object')
 
  extra = extra || {}
 
  var n = this._count + 1
  Iif (this._plan !== -1 && n > this._plan) {
    // Don't over-report failures.
    // it's already had problems, just ignore this.
    if (!this._ok)
      return
 
    var er = new Error('test count exceeds plan')
    Error.captureStackTrace(er, this._currentAssert || printResult)
    var c = this
    var name = this._name
    while (c = c._parent) {
      name += ' < ' + (c._name || '(unnamed test)')
    }
    er.test = name
    er.count = n
    er.plan = this._plan
    throw er
  }
 
  Iif (this._ended)
    throw new Error('test after end() was called')
 
  var fn = this._currentAssert
  this._currentAssert = null
  Iif (!ok && !extra.skip && !hasOwn(extra, 'at')) {
    assert.equal(typeof fn, 'function')
    extra.at = stack.at(fn)
    if (!extra.todo)
      extra.stack = stack.captureString(80, fn).split('\n')
  }
 
  Iif (this._currentChild) {
    this._queue.push(['printResult', ok, message, extra])
    return
  }
 
  var res = { ok: ok, message: message, extra: extra }
  Iif (extra.todo) {
    this._todo++
    this._todos.push(res)
  }
  Iif (extra.skip) {
    this._skip++
    this._skips.push(res)
  }
 
  Eif (ok) {
    this._pass++
    this._passes.push(res)
  } else {
    this._fail++
    this._fails.push(res)
  }
  this._count++
 
  Eif (message)
    message = ' - ' + message
 
  message = message.replace(/[\n\r]/g, ' ').replace(/\t/g, '  ')
 
  this.push(util.format('%s %d%s', ok ? 'ok' : 'not ok', n, message))
 
  var ending = false
  Iif (n === this._plan)
    ending = true
 
  Iif (extra.skip) {
    this._skip++
    this.push(' # SKIP')
    if (typeof extra.skip === 'string')
      this.push(' ' + extra.skip)
  } else Iif (extra.todo) {
    this._todo++
    this.push(' # TODO')
    if (typeof extra.todo === 'string')
      this.push(' ' + extra.todo)
  }
 
  Iif (!ok && !extra.todo && !extra.skip)
    this._ok = false
 
  this.push('\n')
 
  // If we're skipping, no need for diags.
  Iif (!ok && !extra.skip)
    this.writeDiags(extra)
 
  Iif (ending)
    this.end()
}
 
function cleanYamlObj(object, isRoot) {
  if (object === undefined)
    return null
 
  if (typeof object === 'function')
    return object.toString()
 
  if (object && typeof object === 'object') {
    var set = Array.isArray(object) ? [] : {}
    var keys = Object.getOwnPropertyNames(object)
    return keys.reduce(function (set, k) {
      if (isRoot && (k === 'todo' || k === 'skip'))
        return set
 
      if (isRoot && k === 'at' && !object[k])
        return set
 
      set[k] = cleanYamlObj(object[k], false)
      return set
    }, set)
  }
 
  return object
}
 
Test.prototype.writeDiags = function (extra) {
  // some objects are not suitable for yaml.
  var obj = cleanYamlObj(extra, true)
 
  if (Object.keys(obj).length) {
    var y = '  ' + yaml.safeDump(obj).split('\n').join('\n  ')
    y = '  ---\n' + y + '...\n'
    this.push(y)
  }
}
 
Test.prototype.passing = function () {
  return this._ok
}
 
Test.prototype.pass = function pass (message, extra) {
  Iif (!this._currentAssert)
    this._currentAssert = pass
  this.printResult(true, message || '', extra)
  return true
}
 
Test.prototype.fail = function fail (message, extra) {
  if (!this._currentAssert)
    this._currentAssert = fail
 
  if (message && typeof message === 'object') {
    extra = message
    message = ''
  } else {
    if (!message)
      message = ''
    if (!extra)
      extra = {}
  }
 
  var ret = true
  if (!extra.todo && !extra.skip)
    this._ok = ret = false
 
  this.printResult(false, message, extra)
  return ret
}
 
Test.prototype.addAssert = function (name, length, fn) {
  Iif (!name)
    throw new TypeError('name is required for addAssert')
 
  Iif (!(typeof length === 'number' && length >= 0))
    throw new TypeError('number of args required')
 
  Iif (typeof fn !== 'function')
    throw new TypeError('function required for addAssert')
 
  Iif (Test.prototype[name] || this[name])
    throw new TypeError('attempt to re-define `' + name + '` assert')
 
  this[name] = function ASSERT () {
    this._currentAssert = ASSERT
    var args = new Array(length + 2)
    for (var i = 0; i < length; i ++) {
      args[i] = arguments[i]
    }
    Iif (typeof arguments[length] === 'object') {
      args[length] = ''
      args[length + 1] = arguments[length]
    } else {
      args[length] = arguments[length] || ''
      args[length + 1] = arguments[length + 1] || {}
    }
 
    return fn.apply(this, args)
  }
}
 
Test.prototype.comment = function () {
  if (this._bailedOut)
    return
 
  if (this._currentChild) {
    this._queue.push(['comment', message])
    return
  }
 
  var message = util.format.apply(util, arguments)
  message = '# ' + message.split(/\r?\n/).join('\n# ')
 
  this.push(message + '\n')
}
 
Test.prototype.push = function (c, e) {
  Iif (this._bailedOut)
    return true
 
  if (!this._printedVersion && !this._parent) {
    this._printedVersion = true
    Readable.prototype.push.call(this, 'TAP version 13\n')
  }
 
  return Readable.prototype.push.call(this, c, e)
}
 
Test.prototype.bailout = function (message) {
  message = message ? ' # ' + message.trim() : ''
  message = message.replace(/^( #)+ /, ' # ')
  this.push('Bail out!' + message + '\n')
  this._bailedOut = true
  this._ok = false
  this.emit('bailout', message)
  this.push(null)
}
 
// Add all the asserts
tapAsserts.decorate(Test.prototype)