all files / tap-parser/ index.js

100% Statements 370/370
99.6% Branches 247/248
100% Functions 26/26
100% Lines 369/369
4 statements, 2 branches Ignored     
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                                                2053× 7483× 7483× 1990×   63×     1127× 1127× 1127× 41× 41×     41×     1086× 1086× 1041×   45×     1127× 1127× 1127× 1127×   1127× 1127× 1127× 1127× 1127×     1127× 1127× 1041×   86×   1127× 946×   1127×     210×     210×   204× 204×   204× 204× 204× 204× 204× 204× 204× 204× 204× 204× 204× 204× 204× 204× 204× 204×   204× 204× 204× 204× 204× 204×   204× 204×   204×     44× 44× 44× 22×       44×       1127×   1127× 1127× 239× 239× 239× 19×   18× 19×       1127× 1127× 1126× 187× 1126× 1121×       1127×         185×         185×       194×       191×     189× 189×   189× 189× 189× 189×           189× 113×   189×     1662× 1662×           335×   27× 308×   306×       27× 27×   27× 27×       26× 26×     667×   667× 122×   667×     667×     664× 664× 3257× 3257×   3248× 3248×     664× 664×     201×       201×     201×   201×   201×   201× 10× 10×     191× 11× 180×     201×     201×     201×           201× 60×   201×   201× 11×   201× 10×   201× 189× 189× 10× 10×           201×     201× 55×   146×     201×   201×       72× 69×                         1635× 426×   1635×     1635× 76× 76×       1635× 1635×   1635× 508×   1127× 1127×   1127× 1127× 1075×   52× 52× 43× 43×       1127× 21×   1127× 24×   1127× 1127×     76× 76× 76×           76× 61×   76×           76× 76× 76× 76× 76×         76× 76× 35× 35×     41× 15× 15× 15×   26× 26× 26×     41×     630× 426×   204×       3289×       3289× 218× 72× 146×   145×         3144× 3058×       3144× 3144× 1077× 1077×       2067× 14× 14× 14×         2053× 2053× 63× 63×     1990× 546× 546×             1444×       1444×     1444×       1436×     1432×     1423× 72× 72× 72×     1351× 194× 194× 194×         1157×                     1127× 1127×             30×     30×           1077× 530× 530× 530×                       547× 336× 335× 335×                   212× 33× 33×             179× 140×     76× 76×         103×     97×    
// Transforms a stream of TAP into a stream of result objects
// and string comments.  Emits "results" event with summary.
var Writable = require('stream').Writable
/* istanbul ignore if */
Iif (!Writable) {
  try {
    Writable = require('readable-stream').Writable
  } catch (er) {
    throw new Error('Please install "readable-stream" to use this module ' +
                    'with Node.js v0.8 and before')
  }
}
 
var yaml = require('js-yaml')
var util = require('util')
var assert = require('assert')
 
util.inherits(Parser, Writable)
 
module.exports = Parser
 
// every line outside of a yaml block is one of these things, or
// a comment, or garbage.
var lineTypes = {
  testPoint: /^(not )?ok(?: ([0-9]+))?(?:(?: -)?( .*))?\n$/,
  pragma: /^pragma ([+-])([a-z]+)\n$/,
  bailout: /^bail out!(.*)\n$/i,
  version: /^TAP version ([0-9]+)\n$/i,
  plan: /^([0-9]+)\.\.([0-9]+)(?:\s+(?:#\s*(.*)))?\n$/,
  subtest: /^# Subtest(?:: (.*))?\n$/,
  subtestIndent: /^    # Subtest(?:: (.*))?\n$/,
  comment: /^\s*#.*\n$/
}
 
var lineTypeNames = Object.keys(lineTypes)
 
function lineType (line) {
  for (var t in lineTypes) {
    var match = line.match(lineTypes[t])
    if (match)
      return [t, match]
  }
  return null
}
 
function parseDirective (line) {
  line = line.trim()
  var time = line.match(/^time=((?:[1-9][0-9]*|0)(?:\.[0-9]+)?)(ms|s)$/i)
  if (time) {
    var n = +time[1]
    if (time[2] === 's') {
      // JS does weird things with floats.  Round it off a bit.
      n *= 1000000
      n = Math.round(n)
      n /= 1000
    }
    return [ 'time', n ]
  }
 
  var type = line.match(/^(todo|skip)\b/i)
  if (!type)
    return false
 
  return [ type[1].toLowerCase(), line.substr(type[1].length).trim() || true ]
}
 
function Result (parsed, count) {
  var ok = !parsed[1]
  var id = +(parsed[2] || count + 1)
  this.ok = ok
  this.id = id
 
  var rest = parsed[3] || ''
  var name
  rest = rest.replace(/([^\\]|^)((?:\\\\)*)#/g, '$1\n$2').split('\n')
  name = rest.shift()
  rest = rest.filter(function (r) { return r.trim() }).join('#')
 
  // now, let's see if there's a directive in there.
  var dir = parseDirective(rest.trim())
  if (!dir)
    name += rest ? '#' + rest : ''
  else
    this[dir[0]] = dir[1]
 
  if (name)
    this.name = name.trim()
 
  return this
}
 
function Parser (options, onComplete) {
  if (typeof options === 'function') {
    onComplete = options
    options = {}
  }
 
  if (!(this instanceof Parser))
    return new Parser(options, onComplete)
 
  options = options || {}
  if (onComplete)
    this.on('complete', onComplete)
 
  this.sawValidTap = false
  this.failures = []
  this.level = options.level || 0
  Writable.call(this)
  this.buffer = ''
  this.bailedOut = false
  this.planStart = -1
  this.planEnd = -1
  this.planComment = ''
  this.yamlish = ''
  this.yind = ''
  this.child = null
  this.current = null
  this.maybeSubtest = null
  this.commentQueue = []
  this.buffered = options.buffered || null
 
  this.count = 0
  this.pass = 0
  this.fail = 0
  this.todo = 0
  this.skip = 0
  this.ok = true
 
  this.strict = false
  this.pragmas = { strict: false }
 
  this.postPlan = false
}
 
Parser.prototype.tapError = function (error) {
  this.ok = false
  this.fail ++
  if (typeof error === 'string') {
    error = {
      tapError: error
    }
  }
  this.failures.push(error)
}
 
Parser.prototype.parseTestPoint = function (testPoint) {
  // TODO dry the double-parse, pass the parsed data to Result ctor
  this.emitResult()
 
  var res = new Result(testPoint, this.count)
  if (this.planStart !== -1) {
    var lessThanStart = +res.id < this.planStart
    var greaterThanEnd = +res.id > this.planEnd
    if (lessThanStart || greaterThanEnd) {
      if (lessThanStart)
        res.tapError = 'id less than plan start'
      else
        res.tapError = 'id greater than plan end'
      this.tapError(res)
    }
  }
 
  this.sawValidTap = true
  if (res.id) {
    if (!this.first || res.id < this.first)
      this.first = res.id
    if (!this.last || res.id > this.last)
      this.last = res.id
  }
 
  // hold onto it, because we might get yamlish diagnostics
  this.current = res
}
 
// TODO: nonTap should get a buffer like comments, so that
// it can be ordered properly with the result data, yamlish, etc.
Parser.prototype.nonTap = function (data) {
  if (this.strict) {
    this.tapError({
      tapError: 'Non-TAP data encountered in strict mode',
      data: data
    })
  }
  this.emit('extra', data)
}
 
Parser.prototype.plan = function (start, end, comment, line) {
  // not allowed to have more than one plan
  if (this.planStart !== -1) {
    this.nonTap(line)
    return
  }
 
  // can't put a plan in a child.
  if (this.child || this.yind) {
    this.nonTap(line)
    return
  }
 
  this.sawValidTap = true
  this.emitResult()
 
  this.planStart = start
  this.planEnd = end
  var p = { start: start, end: end }
  if (comment)
    this.planComment = p.comment = comment
 
  // This means that the plan is coming at the END of all the tests
  // Plans MUST be either at the beginning or the very end.  We treat
  // plans like '1..0' the same, since they indicate that no tests
  // will be coming.
  if (this.count !== 0 || this.planEnd === 0)
    this.postPlan = true
 
  this.emit('plan', p)
}
 
Parser.prototype.resetYamlish = function () {
  this.yind = ''
  this.yamlish = ''
}
 
// that moment when you realize it's not what you thought it was
Parser.prototype.yamlGarbage = function () {
  var yamlGarbage = this.yind + '---\n' + this.yamlish
  this.emitResult()
  this.nonTap(yamlGarbage)
}
 
Parser.prototype.yamlishLine = function (line) {
  if (line === this.yind + '...\n') {
    // end the yaml block
    this.processYamlish()
  } else if (lineTypes.comment.test(line)) {
    this.emitComment(line)
  } else {
    this.yamlish += line
  }
}
 
Parser.prototype.processYamlish = function () {
  var yamlish = this.yamlish
  this.resetYamlish()
 
  try {
    var diags = yaml.safeLoad(yamlish)
  } catch (er) {
    this.nonTap(yamlish)
    return
  }
 
  this.current.diag = diags
  this.emitResult()
}
 
Parser.prototype.write = function (chunk, encoding, cb) {
  if (typeof encoding === 'string' && encoding !== 'utf8')
    chunk = new Buffer(chunk, encoding)
 
  if (Buffer.isBuffer(chunk))
    chunk += ''
 
  if (typeof encoding === 'function') {
    cb = encoding
    encoding = null
  }
 
  if (this.bailedOut) {
    if (cb)
      process.nextTick(cb)
    return true
  }
 
  this.buffer += chunk
  do {
    var match = this.buffer.match(/^.*\r?\n/)
    if (!match || this.bailedOut)
      break
 
    this.buffer = this.buffer.substr(match[0].length)
    this._parse(match[0])
  } while (this.buffer.length)
 
  if (cb)
    process.nextTick(cb)
  return true
}
 
Parser.prototype.end = function (chunk, encoding, cb) {
  if (chunk) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }
    this.write(chunk, encoding)
  }
 
  if (this.buffer)
    this.write('\n')
 
  // if we have yamlish, means we didn't finish with a ...
  if (this.yamlish)
    this.nonTap(this.yamlish)
 
  this.emitResult()
 
  var skipAll
 
  if (this.planEnd === 0 && this.planStart === 1) {
    skipAll = true
    if (this.count === 0) {
      this.ok = true
    } else {
      this.tapError('Plan of 1..0, but test points encountered')
    }
  } else if (!this.bailedOut && this.planStart === -1) {
    this.tapError('no plan')
  } else if (this.ok && this.count !== (this.planEnd - this.planStart + 1)) {
    this.tapError('incorrect number of tests')
  }
 
  if (this.ok && !skipAll && this.first !== this.planStart) {
    this.tapError('first test id does not match plan start')
  }
 
  if (this.ok && !skipAll && this.last !== this.planEnd) {
    this.tapError('last test id does not match plan end')
  }
 
  var final = {
    ok: this.ok,
    count: this.count,
    pass: this.pass
  }
 
  if (this.fail)
    final.fail = this.fail
 
  if (this.bailedOut)
    final.bailout = this.bailedOut
 
  if (this.todo)
    final.todo = this.todo
 
  if (this.skip)
    final.skip = this.skip
 
  if (this.planStart !== -1) {
    final.plan = { start: this.planStart, end: this.planEnd }
    if (skipAll) {
      final.plan.skipAll = true
      if (this.planComment)
        final.plan.skipReason = this.planComment
    }
  }
 
  // We didn't get any actual tap, so just treat this like a
  // 1..0 test, because it was probably just console.log junk
  if (!this.sawValidTap) {
    final.plan = { start: 1, end: 0 }
    final.ok = true
  }
 
  if (this.failures.length) {
    final.failures = this.failures
  } else {
    final.failures = []
  }
 
  this.emit('complete', final)
 
  Writable.prototype.end.call(this, null, null, cb)
}
 
Parser.prototype.version = function (version, line) {
  // If version is specified, must be at the very beginning.
  if (version >= 13 && this.planStart === -1 && this.count === 0)
    this.emit('version', version)
  else
    this.nonTap(line)
}
 
Parser.prototype.pragma = function (key, value, line) {
  // can't put a pragma in a child or yaml block
  if (this.child) {
    this.nonTap(line)
    return
  }
 
  this.emitResult()
  // only the 'strict' pragma is currently relevant
  if (key === 'strict') {
    this.strict = value
  }
  this.pragmas[key] = value
  this.emit('pragma', key, value)
}
 
Parser.prototype.bailout = function (reason) {
  this.sawValidTap = true
  this.emitResult()
  this.bailedOut = reason || true
  this.ok = false
  this.emit('bailout', reason)
}
 
Parser.prototype.clearCommentQueue = function () {
  for (var c = 0; c < this.commentQueue.length; c++) {
    this.emit('comment', this.commentQueue[c])
  }
  this.commentQueue.length = 0
}
 
Parser.prototype.endChild = function () {
  if (this.child) {
    this.child.end()
    this.child = null
  }
}
 
Parser.prototype.emitResult = function () {
  this.endChild()
  this.resetYamlish()
 
  if (!this.current)
    return this.clearCommentQueue()
 
  var res = this.current
  this.current = null
 
  this.count++
  if (res.ok) {
    this.pass++
  } else {
    this.fail++
    if (!res.todo && !res.skip) {
      this.ok = false
      this.failures.push(res)
    }
  }
 
  if (res.skip)
    this.skip++
 
  if (res.todo)
    this.todo++
 
  this.emit('assert', res)
  this.clearCommentQueue()
}
 
Parser.prototype.startChild = function (line) {
  var maybeBuffered = this.current && this.current.name && this.current.name.substr(-1) === '{'
  var unindentStream = !maybeBuffered  && this.maybeChild
  var indentStream = !maybeBuffered && !unindentStream &&
    lineTypes.subtestIndent.test(line)
 
  // If we have any other result waiting in the wings, we need to emit
  // that now.  A buffered test emits its test point at the *end* of
  // the child subtest block, so as to match streamed test semantics.
  if (!maybeBuffered)
    this.emitResult()
 
  this.child = new Parser({
    parent: this,
    level: this.level + 1,
    buffered: maybeBuffered
  })
 
  this.emit('child', this.child)
  this.child.on('bailout', this.bailout.bind(this))
  var self = this
  this.child.on('complete', function (results) {
    if (this.sawValidTap && !results.ok)
      self.ok = false
  })
 
  // if it's a buffered subtest or a non-indented Subtest directive,
  // then we need to synthetically emit the comment on the child.
  line = line.substr(4)
  if (indentStream) {
    this.child.emitComment(line)
    return
  }
 
  if (maybeBuffered) {
    var n = this.current.name.trim().replace(/{$/, '').trim()
    var c = '# Subtest: ' + n + '\n'
    this.child.emitComment(c)
  } else {
    var mc = this.maybeChild
    this.maybeChild = null
    this.child.emitComment(mc)
  }
 
  this.child._parse(line)
}
 
Parser.prototype.emitComment = function (line) {
  if (this.current || this.commentQueue.length)
    this.commentQueue.push(line)
  else
    this.emit('comment', line)
}
 
Parser.prototype._parse = function (line) {
  // normalize line endings
  line = line.replace(/\r\n$/, '\n')
 
  // sometimes empty lines get trimmed, but are still part of
  // a subtest or a yaml block.  Otherwise, nothing to parse!
  if (line === '\n') {
    if (this.child)
      line = '    ' + line
    else if (this.yind)
      line = this.yind + line
    else
      return
  }
 
  // this is a line we are processing, so emit it, but don't
  // emit all the whitespace, because that's just annoyingly noisy.
  if (line.trim())
    this.emit('line', line)
 
  // check to see if the line is indented.
  // if it is, then it's either a subtest, yaml, or garbage.
  var indent = line.match(/^[ \t]*/)[0]
  if (indent) {
    this.parseIndent(line, indent)
    return
  }
 
  // buffered subtests must end with a }
  if (this.child && this.child.buffered && line === '}\n') {
    this.current.name = this.current.name.replace(/{$/, '').trim()
    this.emitResult()
    return
  }
 
  // now we know it's not indented, so if it's either valid tap
  // or garbage.  Get the type of line.
  var type = lineType(line)
  if (!type) {
    this.nonTap(line)
    return
  }
 
  if (type[0] === 'comment') {
    this.emitComment(line)
    return
  }
 
  // if we have any yamlish, it's garbage now.  We tolerate non-TAP and
  // comments in the midst of yaml (though, perhaps, that's questionable
  // behavior), but any actual TAP means that the yaml block was just
  // not valid.
  if (this.yind)
    this.yamlGarbage()
 
  // If it's anything other than a comment or garbage, then any
  // maybeChild is just an unsatisfied promise.
  this.maybeChild = null
 
  // nothing but comments can come after a trailing plan
  if (this.postPlan) {
    this.nonTap(line)
    return
  }
 
  // ok, now it's maybe a thing
  if (type[0] === 'bailout') {
    this.bailout(type[1][1].trim())
    return
  }
 
  if (type[0] === 'pragma') {
    var pragma = type[1]
    this.pragma(pragma[2], pragma[1] === '+', line)
    return
  }
 
  if (type[0] === 'version') {
    var version = type[1]
    this.version(parseInt(version[1], 10), line)
    return
  }
 
  if (type[0] === 'plan') {
    var plan = type[1]
    this.plan(+plan[1], +plan[2], (plan[3] || '').trim(), line)
    return
  }
 
 
  // streamed subtests will end when this test point is emitted
  if (type[0] === 'testPoint') {
    // note: it's weird, but possible, to have a testpoint ending in
    // { before a streamed subtest which ends with a test point
    // instead of a }.  In this case, the parser gets confused, but
    // also, even beginning to handle that means doing a much more
    // involved multi-line parse.  By that point, the subtest block
    // has already been emitted as a 'child' event, so it's too late
    // to really do the optimal thing.  The only way around would be
    // to buffer up everything and do a multi-line parse.  This is
    // rare and weird, and a multi-line parse would be a bigger
    // rewrite, so I'm allowing it as it currently is.
    this.parseTestPoint(type[1])
    return
  }
 
  // We already detected nontap up above, so the only case left
  // should be a `# Subtest:` comment.  Ignore for coverage, but
  // include the error here just for good measure.
  /* istanbul ignore else */
  Eif (type[0] === 'subtest') {
    // this is potentially a subtest.  Not indented.
    // hold until later.
    this.maybeChild = line
  } else {
    throw new Error('Unhandled case: ' + type[0])
  }
}
 
Parser.prototype.parseIndent = function (line, indent) {
  // still belongs to the child, so pass it along.
  if (this.child && line.substr(0, 4) === '    ') {
    line = line.substr(4)
    this.child.write(line)
    return
  }
 
  // one of:
  // - continuing yaml block
  // - starting yaml block
  // - ending yaml block
  // - body of a new child subtest that was previously introduced
  // - An indented subtest directive
  // - A comment, or garbage
 
  // continuing/ending yaml block
  if (this.yind) {
    if (line.indexOf(this.yind) === 0) {
      this.yamlishLine(line)
      return
    } else {
      // oops!  that was not actually yamlish, I guess.
      // this is a case where the indent is shortened mid-yamlish block
      // treat existing yaml as garbage, continue parsing this line
      this.yamlGarbage()
    }
  }
 
 
  // start a yaml block under a test point
  if (this.current && !this.yind && line === indent + '---\n') {
    this.yind = indent
    return
  }
 
  // at this point, not yamlish, and not an existing child test.
  // We may have already seen an unindented Subtest directive, or
  // a test point that ended in { indicating a buffered subtest
  // Child tests are always indented 4 spaces.
  if (line.substr(0, 4) === '    ') {
    if (this.maybeChild ||
        this.current && this.current.name && this.current.name.substr(-1) === '{' ||
        lineTypes.subtestIndent.test(line)) {
      this.startChild(line)
      return
    }
  }
 
  // at this point, it's either a non-subtest comment, or garbage.
  if (lineTypes.comment.test(line)) {
    this.emitComment(line)
    return
  }
 
  this.nonTap(line)
}