b79b6c43df483242e09c1dddec30f2d0b5803019.svn-base 46.3 KB
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 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
'use strict'
// We need TWO queues (work and subtest) and one jobs pool
//
// The pool stores buffered subtests being run in parallel.
//
// When new subtests are created, they get put in the work queue and also
// in the subtests queue if they are buffered and jobs>0.  When we put a
// test in the subtest queue, we also process it.
//
// Processing the subtest queue means moving tests into the jobs pool until
// the jobs pool length is at this.jobs
//
// Any output functions get put in the work queue if its length > 0 (ie,
// no cutting the line)
//
// Processing the work queue means walking until we run out of things, or
// encounter an unfinished test.  When we encounter ANY kind of test, we
// block until its output is completed, dumping it all into the parser.

const {format, same, strict, match, hasStrict} = require('tcompare')
const formatSnapshotDefault = obj => format(obj, { sort: true })
const Base = require('./base.js')
const Spawn = require('./spawn.js')
const Stdin = require('./stdin.js')
const Deferred = require('trivial-deferred')
const Pool = require('yapool')
const TestPoint = require('./point.js')
const parseTestArgs = require('./parse-test-args.js')
const loop = require('function-loop')
const path = require('path')
const fs = require('fs')
const rimraf = require('rimraf')
const Fixture = require('./fixture.js')
const cleanYamlObject = require('./clean-yaml-object.js')

const extraFromError = require('./extra-from-error.js')
const stack = require('./stack.js')
const synonyms = require('./synonyms.js')
const assert = require('assert')
const util = require('util')
const ownOr = require('own-or')
const ownOrEnv = require('own-or-env')
const bindObj = require('bind-obj-methods')
const cwd = process.cwd()

// A sigil object for implicit end() calls that should not
// trigger an error if the user then calls t.end()
const IMPLICIT = Symbol('implicit t.end()')

// Sigil to put in the queue to signal the end of all things
const EOF = Symbol('EOF')

const _currentAssert = Symbol('_currentAssert')
const _end = Symbol('_end')
const _snapshot = Symbol('_snapshot')
const _getSnapshot = Symbol('_getSnapshot')
const _beforeEnd = Symbol('_beforeEnd')
const _emits = Symbol('_emits')
const _nextChildId = Symbol('_nextChildId')
const _expectUncaught = Symbol('_expectUncaught')
const _createdFixture = Symbol('_createdFixture')
const Snapshot = require('./snapshot.js')

const hasOwn = (obj, key) =>
  Object.prototype.hasOwnProperty.call(obj, key)

const isRegExp = re =>
  Object.prototype.toString.call(re) === '[object RegExp]'

class Waiter {
  constructor (promise, cb) {
    this.cb = cb
    this.ready = false
    this.value = null
    this.resolved = false
    this.rejected = false
    this.done = false
    this.finishing = false
    this.expectReject = false
    this.promise = new Promise(res => this.resolve = res)
    promise.then(value => {
      this.resolved = true
      this.value = value
      this.done = true
      this.finish()
    }).catch(er => this.reject(er))
  }
  reject (er) {
    this.value = er
    this.rejected = true
    this.done = true
    this.finish()
  }
  abort (er) {
    /* istanbul ignore else - an excess of caution, should be impossible */
    if (!this.done) {
      this.ready = true
      this.finishing = false
      this.done = true
      this.value = er
      // make it clear that this is a problem by doing
      // the opposite of what was requested.
      this.rejected = !this.expectReject
      return this.finish()
    }
  }
  finish () {
    if (this.ready && this.done && !this.finishing) {
      this.finishing = true
      this.cb(this)
      this.resolve()
    }
  }
}

class Test extends Base {
  constructor (options) {
    options = options || {}
    super(options)
    this[_nextChildId] = 1
    this.pushedEnd = false
    this.jobs = ownOr(options, 'jobs', 1)

    this.doingStdinOnly = false
    this.onTeardown = []
    this[_createdFixture] = false
    this.subtests = []
    this.pool = new Pool()
    this.queue = ['TAP version 13\n']

    // snapshots are keyed off of the main file that loads the
    // root test object. Typically, this is the TAP object.
    // To do this, we climb the ladder and only save in the teardown
    // of that root (parentless) test object.  This allows handling
    // cases where the same test name can be used multiple times
    // in a single test file, which would otherwise clobber snapshots.
    this.writeSnapshot = ownOrEnv(
      options, 'snapshot', 'TAP_SNAPSHOT', true)

    if (this.parent && this.parent.cleanSnapshot)
      this.cleanSnapshot = this.parent.cleanSnapshot

    this.formatSnapshot = this.parent && this.parent.formatSnapshot

    this.noparallel = false
    if (options.cb)
      this.cb = (...args) => this.hook.runInAsyncScope(options.cb, this, ...args)

    this.occupied = false
    this[_currentAssert] = null
    this[_beforeEnd] = []
    this.count = 0
    this.n = 0
    this.ended = false
    this.explicitEnded = false
    this.multiEndThrew = false
    this.assertAt = null
    this.assertStack = null
    this.planEnd = -1
    this.onBeforeEach = []
    this.onAfterEach = []
    this.ranAfterEach = false

    this[_expectUncaught] = []

    // bind all methods to this object, so we can pass t.end as a callback
    // and do `const test = require('tap').test` like people do.
    const bound = Object.create(null)
    bindObj(this, this, bound)
    bindObj(this, Object.getPrototypeOf(this), bound)
    bindObj(this, Test.prototype, bound)
  }

  spawn (cmd, args, options, name) {
    if (typeof args === 'string')
      args = [ args ]

    args = args || []

    if (typeof options === 'string') {
      name = options
      options = {}
    }

    options = options || {}
    options.name = ownOr(options, 'name', name)
    options.command = cmd
    options.args = args

    return this.sub(Spawn, options, Test.prototype.spawn)
  }

  sub (Class, extra, caller) {
    if (this.bailedOut)
      return

    if (this.doingStdinOnly)
      throw new Error('cannot run subtests in stdinOnly mode')

    if (this.results || this.ended) {
      const er = new Error('cannot create subtest after parent test end')
      Error.captureStackTrace(er, caller)
      this.threw(er)
      return Promise.resolve(this)
    }

    extra.childId = this[_nextChildId]++

    if (!extra.skip && this.grep.length) {
      const m = this.grep[0].test(extra.name)
      const match = this.grepInvert ? !m : m
      if (!match) {
        const p = 'filter' + (this.grepInvert ? ' out' : '') + ': '
        extra.skip = p + this.grep[0]
      }
    }

    if (extra.only && !this.runOnly)
      this.comment('%j has `only` set but all tests run', extra.name)

    if (this.runOnly && !extra.only)
      extra.skip = 'filter: only'

    if (extra.todo || extra.skip) {
      this.pass(extra.name, extra)
      return Promise.resolve(this)
    }

    if (!extra.grep) {
      extra.grep = this.grep.slice(1)
      extra.grepInvert = this.grepInvert
    }

    extra.indent = '    '
    if (this.jobs > 1 && process.env.TAP_BUFFER === undefined)
      extra.buffered = ownOr(extra, 'buffered', true)
    else
      extra.buffered = ownOrEnv(extra, 'buffered', 'TAP_BUFFER', true)

    extra.bail = ownOr(extra, 'bail', this.bail)
    extra.parent = this
    extra.stack = stack.captureString(80, caller)
    extra.context = this.context
    const t = new Class(extra)

    this.queue.push(t)
    this.subtests.push(t)
    this.emit('subtestAdd', t)

    const d = new Deferred()
    t.deferred = d
    this.process()
    return d.promise
  }

  todo (name, extra, cb) {
    extra = parseTestArgs(name, extra, cb)
    extra.todo = extra.todo || true
    return this.sub(Test, extra, Test.prototype.todo)
  }

  skip (name, extra, cb) {
    extra = parseTestArgs(name, extra, cb)
    extra.skip = extra.skip || true
    return this.sub(Test, extra, Test.prototype.skip)
  }

  only (name, extra, cb) {
    extra = parseTestArgs(name, extra, cb)
    extra.only = true
    return this.sub(Test, extra, Test.prototype.only)
  }

  test (name, extra, cb) {
    extra = parseTestArgs(name, extra, cb)
    return this.sub(Test, extra, Test.prototype.test)
  }

  stdinOnly (extra) {
    const stream = extra && extra.tapStream || process.stdin
    if (this.queue.length !== 1 ||
        this.queue[0] !== 'TAP version 13\n' ||
        this.processing ||
        this.results ||
        this.occupied ||
        this.pool.length ||
        this.subtests.length)
      throw new Error('Cannot use stdinOnly on a test in progress')

    this.doingStdinOnly = true
    this.queue.length = 0
    this.parser.on('child', p => {
      // pretend to be a rooted parser, so it gets counts.
      p.root = p
      const t = new Base({
        name: p.name,
        parent: this,
        parser: p,
        root: p,
        bail: p.bail,
        strict: p.strict,
        omitVersion: p.omitVersion,
        preserveWhitespace: p.preserveWhitespace,
        childId: this[_nextChildId]++,
      })
      this.emit('subtestAdd', t)
      this.emit('subtestStart', t)
      this.emit('subtestProcess', t)
      p.on('complete', () => {
        t.time = p.time
        this.emit('subtestEnd', t)
      })
    })
    stream.pause()
    stream.pipe(this.parser)
    stream.resume()
  }

  stdin (name, extra) {
    /* istanbul ignore next */
    extra = parseTestArgs(name, extra, false, '/dev/stdin')
    return this.sub(Stdin, extra, Test.prototype.stdin)
  }

  bailout (message) {
    if (this.parent && (this.results || this.ended))
      this.parent.bailout(message)
    else {
      this.process()
      message = message ? ' ' + ('' + message).trim() : ''
      message = message.replace(/[\r\n]/g, ' ')
      this.parser.write('Bail out!' + message + '\n')
    }
    this.end(IMPLICIT)
    this.process()
  }

  comment (...args) {
    const body = util.format(...args)
    const message = '# ' + body.split(/\r?\n/).join('\n# ') + '\n'

    if (this.results)
      this.write(message)
    else
      this.queue.push(message)
    this.process()
  }

  timeout (options) {
    options = options || {}
    options.expired = options.expired || this.name
    if (this.occupied && this.occupied.timeout)
      this.occupied.timeout(options)
    else
      Base.prototype.timeout.call(this, options)
    this.end(IMPLICIT)
  }

  main (cb) {
    this.setTimeout(this.options.timeout)
    this.debug('MAIN pre', this)

    const end = () => {
      this.debug(' > implicit end for promise')
      this.end(IMPLICIT)
      done()
    }

    const done = (er) => {
      if (er)
        this.threw(er)

      if (this.results || this.bailedOut)
        cb()
      else
        this.ondone = cb
    }

    // This bit of overly clever line-noise wraps the call to user-code
    // in a try-catch. We can't rely on the domain for this yet, because
    // the 'end' event can trigger a throw after the domain is unhooked,
    // but before this is no longer the official "active test"
    const ret = (() => {
      try {
        return this.cb(this)
      } catch (er) {
        if (!er || typeof er !== 'object')
          er = { error: er }
        er.tapCaught = 'testFunctionThrow'
        this.threw(er)
      }
    })()

    if (ret && ret.then) {
      this.promise = ret
      ret.tapAbortPromise = done
      ret.then(end, er => {
        if (!er || typeof er !== 'object')
          er = { error: er }
        er.tapCaught = 'returnedPromiseRejection'
        done(er)
      })
    } else
      done()

    this.debug('MAIN post', this)
  }

  process () {
    if (this.processing)
      return this.debug(' < already processing')

    this.debug('\nPROCESSING(%s)', this.name, this.queue.length)
    this.processing = true

    while (!this.occupied) {
      const p = this.queue.shift()
      if (!p)
        break
      if (p instanceof Base) {
        this.processSubtest(p)
      } else if (p === EOF) {
        this.debug(' > EOF', this.name)
        // I AM BECOME EOF, DESTROYER OF STREAMS
        if (this.writeSnapshot)
          this[_getSnapshot]().save()
        this.parser.end()
      } else if (p instanceof TestPoint) {
        this.debug(' > TESTPOINT')
        this.parser.write(p.ok + (++this.n) + p.message)
      } else if (typeof p === 'string') {
        this.debug(' > STRING')
        this.parser.write(p)
      } else if (p instanceof Waiter) {
        p.ready = true
        this.occupied = p
        p.finish()
      } else {
        /* istanbul ignore else */
        if (Array.isArray(p)) {
          this.debug(' > METHOD')
          const m = p.shift()
          const ret = this[m].apply(this, p)
          if (ret && typeof ret.then === 'function') {
            // returned promise
            ret.then(() => {
              this.processing = false
              this.process()
            }, er => {
              this.processing = false
              this.threw(er)
            })
            return
          }
        } else {
          throw new Error('weird thing got in the queue')
        }
      }
    }

    while (!this.noparallel && this.pool.length < this.jobs) {
      const p = this.subtests.shift()
      if (!p)
        break

      if (!p.buffered) {
        this.noparallel = true
        break
      }

      this.debug('start subtest', p)
      this.emit('subtestStart', p)
      this.pool.add(p)
      if (this.bailedOut)
        this.onbufferedend(p)
      else
        this.runBeforeEach(p, () =>
          p.runMain(() => this.onbufferedend(p)))
    }

    this.debug('done processing', this.queue, this.occupied)
    this.processing = false

    // just in case any tests ended, and we have sync stuff still
    // waiting around in the queue to be processed
    if (!this.occupied && this.queue.length)
      this.process()

    this.maybeAutoend()
  }

  processSubtest (p) {
    this.debug(' > subtest')
    this.occupied = p
    if (!p.buffered) {
      this.emit('subtestStart', p)
      this.debug(' > subtest indented')
      p.pipe(this.parser, { end: false })
      this.runBeforeEach(p, () =>
        this.writeSubComment(p, () =>
          p.runMain(() => this.onindentedend(p))))
    } else if (p.readyToProcess) {
      this.emit('subtestProcess', p)
      this.debug(' > subtest buffered, finished')
      // finished!  do the thing!
      this.occupied = null
      if (!p.passing() || !p.silent) {
        this.queue.unshift(['emitSubTeardown', p])
        this.printResult(p.passing(), p.name, p.options, true)
      }
    } else {
      this.occupied = p
      this.debug(' > subtest buffered, unfinished', p)
      // unfinished buffered test.
      // nothing to do yet, just leave it there.
      this.queue.unshift(p)
    }
  }

  emitSubTeardown (p) {
    // if it's not a thing that CAN have teardowns, nothing to do here
    if (!p.onTeardown)
      return

    const otd = p.onTeardown
    p.onTeardown = []
    const threw = er => {
      if (!er || typeof er !== 'object')
        er = { error: er }
      er.tapCaught = 'teardown'
      delete p.options.time
      p.threw(er)
    }
    for (let i = 0; i < otd.length; i++) {
      const fn = otd[i]
      try {
        const ret = fn.call(p)
        if (ret && typeof ret.then === 'function') {
          p.onTeardown = otd.slice(i + 1)
          this.queue.unshift(['emitSubTeardown', p])
          return ret.then(() => this.emitSubTeardown(p), er => {
            if (!er || typeof er !== 'object')
              er = { error: er }
            er.tapCaught = 'teardown'
            throw er
          })
        }
      } catch (er) {
        threw(er)
      }
    }

    // ok we're done, just delete the fixture if it created one.
    // do this AFTER all user-generated teardowns, and asynchronously so
    // that we can do the fancy backoff dance for Win32's weirdo fs.
    if (p[_createdFixture])
      return new Promise((res, rej) => {
        rimraf(p[_createdFixture], er =>
          er ? /* istanbul ignore next - rimraf never fails lol */ rej(er)
          : res())
      }).then(() => p.emit('teardown'))
    else
      p.emit('teardown')
  }

  writeSubComment (p, cb) {
    const comment = '# Subtest' +
      (p.name ? ': ' + p.name : '') +
      '\n'
    this.parser.write(comment)
    cb()
  }

  onbufferedend (p) {
    delete p.ondone
    p.results = p.results || {}
    p.readyToProcess = true
    const to = p.options.timeout
    const dur = (to && p.passing()) ? Date.now() - p.start : null
    if (dur && dur > to)
      p.timeout()
    else
      p.setTimeout(false)
    this.debug('%s.onbufferedend', this.name, p.name, p.results.bailout)
    this.pool.remove(p)
    p.options.tapChildBuffer = p.output || ''
    p.options.stack = ''
    if (p.time)
      p.options.time = p.time
    if (this.occupied === p)
      this.occupied = null
    p.deferred.resolve(this)
    this.emit('subtestEnd', p)
    this.process()
  }

  onindentedend (p) {
    this.emit('subtestProcess', p)
    delete p.ondone
    this.debug('onindentedend', p)
    this.noparallel = false
    const sti = this.subtests.indexOf(p)
    if (sti !== -1)
      this.subtests.splice(sti, 1)
    p.readyToProcess = true
    p.options.time = p.time
    const to = p.options.timeout
    const dur = (to && p.passing()) ? Date.now() - p.start : null
    if (dur && dur > to)
      p.timeout()
    else
      p.setTimeout(false)
    this.debug('onindentedend %s(%s)', this.name, p.name)
    this.occupied = null
    this.debug('OIE(%s) b>shift into queue', this.name, this.queue)
    p.options.stack = ''

    this.queue.unshift(['emitSubTeardown', p])
    this.printResult(p.passing(), p.name, p.options, true)

    this.debug('OIE(%s) shifted into queue', this.name, this.queue)
    p.deferred.resolve(this)
    this.emit('subtestEnd', p)
    this.process()
  }

  addAssert (name, length, fn) {
    if (!name)
      throw new TypeError('name is required for addAssert')

    if (!(typeof length === 'number' && length >= 0))
      throw new TypeError('number of args required')

    if (typeof fn !== 'function')
      throw new TypeError('function required for addAssert')

    if (Test.prototype[name] || this[name])
      throw new TypeError('attempt to re-define `' + name + '` assert')

    const ASSERT = function (...args) {
      this.currentAssert = ASSERT
      if (typeof args[length] === 'object') {
        args[length + 1] = args[length]
        args[length] = ''
      } else {
        args[length] = args[length] || ''
        args[length + 1] = args[length + 1] || {}
      }

      return fn.apply(this, args)
    }
    this[name] = ASSERT
  }

  printResult (ok, message, extra, front) {
    if (this.doingStdinOnly)
      throw new Error('cannot print results in stdinOnly mode')
    const n = this.count + 1
    this.currentAssert = Test.prototype.printResult
    const fn = this[_currentAssert]
    this[_currentAssert] = null

    if (this.planEnd !== -1 && n > this.planEnd) {
      if (!this.passing())
        return

      const failMessage = this.explicitEnded
          ? 'test after end() was called'
          : 'test count exceeds plan'

      const er = new Error(failMessage)
      Error.captureStackTrace(er, fn)
      er.test = this.name
      er.plan = this.planEnd
      this.threw(er)
      return
    }

    extra = extra || {}

    if (extra.expectFail)
      ok = !ok

    if (this.assertAt) {
      extra.at = this.assertAt
      this.assertAt = null
    }

    if (this.assertStack) {
      extra.stack = this.assertStack
      this.assertStack = null
    }

    if (hasOwn(extra, 'stack') && !hasOwn(extra, 'at'))
      extra.at = stack.parseLine(extra.stack.split('\n')[0])

    if (!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)
    }

    const diagnostic =
      typeof extra.diagnostic === 'boolean' ? extra.diagnostic
      : process.env.TAP_DIAG === '0' ? false
      : process.env.TAP_DIAG === '1' ? true
      : extra.skip ? false
      : !ok

    if (diagnostic)
      extra.diagnostic = true

    this.count = n
    message = message + ''
    const res = { ok, message, extra }

    const output = new TestPoint(ok, message, extra)
    // when we jump the queue, skip an extra line
    if (front)
      output.message = output.message.trimRight() + '\n\n'

    if (this.occupied && this.occupied instanceof Waiter &&
        this.occupied.finishing)
      front = true

    if (front) {
      this.emit('result', res)
      this.parser.write(output.ok + (++this.n) + output.message)
      if (this.bail && !ok && !extra.skip && !extra.todo)
        this.parser.write('Bail out! ' + message + '\n')
    } else {
      this.queue.push(['emit', 'result', res], output)
      if (this.bail && !ok && !extra.skip && !extra.todo)
        this.queue.push('Bail out! ' + message + '\n')
    }

    if (this.planEnd === this.count)
      this.end(IMPLICIT)

    this.process()
  }

  pragma (set) {
    const p = Object.keys(set).reduce((acc, i) =>
      acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n', '')
    this.queue.push(p)
    this.process()
  }

  plan (n, comment) {
    if (this.bailedOut)
      return

    if (this.planEnd !== -1) {
      throw new Error('Cannot set plan more than once')
    }

    if (typeof n !== 'number' || n < 0) {
      throw new TypeError('plan must be a number')
    }

    // Cannot get any tests after a trailing plan, or a plan of 0
    const ending = this.count !== 0 || n === 0

    if (n === 0 && comment && !this.options.skip)
      this.options.skip = comment

    this.planEnd = n
    comment = comment ? ' # ' + comment.trim() : ''
    this.queue.push('1..' + n + comment + '\n')

    if (ending)
      this.end(IMPLICIT)
    else
      this.process()
  }

  end (implicit) {
    if (this.doingStdinOnly && implicit !== IMPLICIT)
      throw new Error('cannot explicitly end while in stdinOnly mode')
    this.debug('END implicit=%j', implicit === IMPLICIT)
    if (this.ended && implicit === IMPLICIT)
      return

    if (this[_beforeEnd].length) {
      for (let b = 0; b < this[_beforeEnd].length; b++) {
        const m = this[_beforeEnd][b].shift()
        this[m].apply(this, this[_beforeEnd][b])
      }
      this[_beforeEnd].length = 0
    }

    // beyond here we have to be actually done with things, or else
    // the semantic checks on counts and such will be off.
    if (!queueEmpty(this) || this.occupied) {
      if (!this.pushedEnd)
        this.queue.push(['end', implicit])
      this.pushedEnd = true
      return this.process()
    }

    if (!this.ranAfterEach && this.parent) {
      this.ranAfterEach = true
      this.parent.runAfterEach(this, () => this[_end](implicit))
      return
    } else
      this[_end](implicit)
  }

  [_end] (implicit) {
    this.ended = true

    if (implicit !== IMPLICIT && !this.multiEndThrew) {
      if (this.explicitEnded) {
        this.multiEndThrew = true
        const er = new Error('test end() method called more than once')
        Error.captureStackTrace(er, this[_currentAssert] ||
          Test.prototype[_end])
        er.test = this.name
        this.threw(er)
        return
      }
      this.explicitEnded = true
    }

    if (this.planEnd === -1) {
      this.debug('END(%s) implicit plan', this.name, this.count)
      this.plan(this.count)
    }

    this.queue.push(EOF)

    if (this[_expectUncaught].length) {
      const wanted = this[_expectUncaught]
      this[_expectUncaught] = []
      const diag = {
        wanted: wanted.map(a => a.filter(e => e != null)),
        test: this.name,
        at: null,
        stack: null,
      }
      const msg = 'test end without expected uncaught exceptions'
      this.queue.push(['threw', Object.assign(new Error(msg), diag)])
    }
    this.process()
  }

  threw (er, extra, proxy) {
    // this can only happen if a beforeEach function raises an error
    if (this.parent && !this.started) {
      this.cb = () => {
        this.threw(er)
        this.end()
      }
      return
    }

    if (!er || typeof er !== 'object')
      er = { error: er }

    if (this[_expectUncaught].length && er.tapCaught === 'uncaughtException') {
      const [wanted, message, extra] = this[_expectUncaught].shift()
      const actual = isRegExp(wanted) ? er.message : er
      return wanted
        ? this.match(actual, wanted, message, extra)
        : this.pass(message, extra)
    }

    if (this.name && !proxy)
      er.test = this.name
    if (!proxy)
      extra = extraFromError(er, extra, this.options)
    Base.prototype.threw.call(this, er, extra, proxy)

    if (!this.results) {
      this.fail(extra.message || er.message, extra)
      if (!proxy)
        this.end(IMPLICIT)
    }
    // threw while waiting for a promise to resolve.
    // probably it's not ever gonna.
    if (this.occupied && this.occupied instanceof Waiter)
      this.occupied.abort(Object.assign(
        new Error('error thrown while awaiting Promise'),
        { thrown: er }
      ))

    this.process()
  }

  runBeforeEach (who, cb) {
    if (this.parent)
      this.parent.runBeforeEach(who, () => {
        loop(who, this.onBeforeEach, cb, er => {
          who.threw(er)
          cb()
        })
      })
    else
      loop(who, this.onBeforeEach, cb, er => {
        who.threw(er)
        cb()
      })
  }

  runAfterEach (who, cb) {
    loop(who, this.onAfterEach, () => {
      if (this.parent)
        this.parent.runAfterEach(who, cb)
      else
        cb()
    }, who.threw)
  }

  beforeEach (fn) {
    this.onBeforeEach.push(function (done) {
      return fn.call(this, done, this)
    })
  }

  afterEach (fn) {
    this.onAfterEach.push(function (done) {
      return fn.call(this, done, this)
    })
  }

  teardown (fn) {
    this.onTeardown.push(fn)
  }

  shouldAutoend () {
    const should = (
      this.options.autoend &&
      !this.ended &&
      !this.occupied &&
      queueEmpty(this) &&
      !this.pool.length &&
      !this.subtests.length &&
      this.planEnd === -1
    )
    return should
  }

  autoend (value) {
    // set to false to NOT trigger autoend
    if (value === false) {
      this.options.autoend = false
      clearTimeout(this.autoendTimer)
    } else {
      this.options.autoend = true
      this.maybeAutoend()
    }
  }

  maybeAutoend () {
    if (this.shouldAutoend()) {
      clearTimeout(this.autoendTimer)
      this.autoendTimer = setTimeout(() => {
        if (this.shouldAutoend()) {
          clearTimeout(this.autoendTimer)
          this.autoendTimer = setTimeout(() => {
            if (this.shouldAutoend())
              this.end(IMPLICIT)
          })
        }
      })
    }
  }

  onbail (message) {
    super.onbail(message)
    this.end(IMPLICIT)
    if (!this.parent)
      this.endAll()
  }

  endAll (sub) {
    // in the case of the root TAP test object, we might sometimes
    // call endAll on a bailing-out test, as the process is ending
    // In that case, we WILL have a this.occupied and a full queue
    // These cases are very rare to encounter in other Test objs tho
    this.processing = true
    if (this.occupied) {
      const p = this.occupied
      if (p instanceof Waiter)
        p.abort(new Error('test unfinished'))
      else if (p.endAll)
        p.endAll(true)
      else
        p.parser.abort('test unfinished')
    } else if (sub) {
      this.process()
      if (queueEmpty(this)) {
        const options = Object.assign({}, this.options)
        this.options.at = null
        this.options.stack = ''
        options.test = this.name
        this.fail('test unfinished', options)
      }
    }

    if (this.promise && this.promise.tapAbortPromise)
      this.promise.tapAbortPromise()

    if (this.occupied) {
      this.queue.unshift(this.occupied)
      this.occupied = null
    }

    endAllQueue(this.queue)
    this.processing = false
    this.process()
    this.parser.end()
  }

  get currentAssert () {
    return this[_currentAssert]
  }

  set currentAssert (fn) {
    if (!this[_currentAssert])
      this[_currentAssert] = fn
  }

  pass (message, extra) {
    this.currentAssert = Test.prototype.pass

    if (message && typeof message === 'object')
      extra = message, message = ''

    if (!extra)
      extra = {}

    this.printResult(true, message || '(unnamed test)', extra)
    return true
  }

  fail (message, extra) {
    this.currentAssert = Test.prototype.fail

    if (message && typeof message === 'object')
      extra = message, message = ''

    if (!extra)
      extra = {}

    this.printResult(false, message || '(unnamed test)', extra)
    return !!(extra.todo || extra.skip)
  }

  ok (obj, message, extra) {
    this.currentAssert = Test.prototype.ok

    if (message && typeof message === 'object')
      extra = message, message = ''

    if (!extra)
      extra = {}
    message = message || 'expect truthy value'
    return obj ? this.pass(message, extra) : this.fail(message, extra)
  }

  notOk (obj, message, extra) {
    this.currentAssert = Test.prototype.notOk

    if (message && typeof message === 'object')
      extra = message, message = ''

    if (!extra)
      extra = {}
    message = message || 'expect falsey value'
    return this.ok(!obj, message, extra)
  }

  emits (emitter, event, message, extra) {
    this.currentAssert = Test.prototype.emits

    if (message && typeof message === 'object')
      extra = message, message = ''

    if (!message)
      message = `expect ${event} event to be emitted`

    if (!extra)
      extra = {}

    const handler = () => handler.emitted = true
    handler.emitted = false
    emitter.once(event, handler)
    extra.at = stack.at(Test.prototype.emits)
    extra.stack = stack.captureString(80, Test.prototype.emits)
    this[_beforeEnd].push([_emits, emitter, event, handler, message, extra])
  }

  [_emits] (emitter, event, handler, message, extra) {
    if (handler.emitted)
      return this.pass(message, extra)
    else {
      emitter.removeListener(event, handler)
      return this.fail(message, extra)
    }
  }

  error (er, message, extra) {
    this.currentAssert = Test.prototype.error

    if (message && typeof message === 'object')
      extra = message, message = ''

    if (!extra)
      extra = {}

    if (!er) {
      return this.pass(message || 'should not error', extra)
    }

    if (!(er instanceof Error)) {
      extra.found = er
      return this.fail(message || 'non-Error error encountered', extra)
    }

    message = message || er.message
    extra.origin = cleanYamlObject(extraFromError(er))
    extra.found = er
    return this.fail(message, extra)
  }

  equal (found, wanted, message, extra) {
    this.currentAssert = Test.prototype.equal

    if (message && typeof message === 'object')
      extra = message, message = ''

    if (!extra)
      extra = {}

    message = message || 'should be equal'
    if (found === wanted) {
      return this.pass(message, extra)
    }

    const objects = found &&
      wanted &&
      typeof found === 'object' &&
      typeof wanted === 'object'
    if (objects) {
      const s = strict(found, wanted)
      if (!s.match)
        extra.diff = s.diff
      else {
        extra.found = found
        extra.wanted = wanted
        extra.note = 'object identities differ'
      }
    } else {
      extra.found = found
      extra.wanted = wanted
    }

    extra.compare = '==='

    return this.fail(message, extra)
  }

  not (found, wanted, message, extra) {
    this.currentAssert = Test.prototype.not

    if (message && typeof message === 'object')
      extra = message, message = ''

    if (!extra)
      extra = {}

    message = message || 'should not be equal'
    if (found !== wanted) {
      return this.pass(message, extra)
    }

    extra.found = found
    extra.doNotWant = wanted
    extra.compare = '!=='

    return this.fail(message, extra)
  }

  same (found, wanted, message, extra) {
    this.currentAssert = Test.prototype.same

    if (message && typeof message === 'object')
      extra = message, message = ''

    if (!extra)
      extra = {}

    message = message || 'should be equivalent'
    const s = same(found, wanted)
    if (!s.match)
      extra.diff = s.diff
    else {
      extra.found = found
      extra.wanted = wanted
    }
    return this.ok(s.match, message, extra)
  }

  notSame (found, wanted, message, extra) {
    this.currentAssert = Test.prototype.notSame

    if (message && typeof message === 'object')
      extra = message, message = ''

    if (!extra)
      extra = {}

    message = message || 'should not be equivalent'
    extra.found = found
    extra.doNotWant = wanted
    const s = same(found, wanted)
    return this.notOk(s.match, message, extra)
  }

  strictSame (found, wanted, message, extra) {
    this.currentAssert = Test.prototype.strictSame

    if (message && typeof message === 'object')
      extra = message, message = ''

    if (!extra)
      extra = {}

    message = message || 'should be equivalent strictly'
    const s = strict(found, wanted)
    if (!s.match)
      extra.diff = s.diff
    else {
      extra.found = found
      extra.wanted = wanted
    }

    return this.ok(s.match, message, extra)
  }

  strictNotSame (found, wanted, message, extra) {
    this.currentAssert = Test.prototype.strictNotSame

    if (message && typeof message === 'object')
      extra = message, message = ''

    if (!extra)
      extra = {}

    message = message || 'should not be equivalent strictly'
    extra.found = found
    extra.doNotWant = wanted
    const s = strict(found, wanted)
    return this.notOk(s.match, message, extra)
  }

  get fullname () {
    const main = process.argv.slice(1).join(' ').trim()
    return (this.parent ? this.parent.fullname
      : main.indexOf(cwd) === 0 ? main.substr(cwd.length + 1)
      : path.basename(main)).replace(/\\/g, '/') +
      ' ' + (this.name || '').trim()
  }

  get testdirName () {
    const re = /[^a-z0-9]+/ig
    if (!this.parent) {
      const main = (require.main ||
        /* istanbul ignore next: only tested in node -p, where
           NYC cannot easily reach */ { filename: 'TAP' }).filename
      const dir = path.dirname(main)
      const base = (path.basename(main).replace(/\.[^.]+$/, '')
        + ' ' + process.argv.slice(2).join(' ')).trim()
      return dir + '/' + base.replace(re, '-')
    }

    return this.parent.testdirName + '-' +
      (this.name || 'unnamed test').replace(re, '-')
  }

  testdir (fixture) {
    const dir = this.testdirName
    rimraf.sync(dir)
    if (!this.saveFixture)
      this[_createdFixture] = dir
    Fixture.make(dir, fixture || {})
    return dir
  }

  fixture (type, content) {
    return new Fixture(type, content)
  }

  matchSnapshot (found, message, extra) {
    this.currentAssert = Test.prototype.matchSnapshot

    if (message && typeof message === 'object')
      extra = message, message = null

    if (!extra)
      extra = {}

    if (!message)
      message = 'must match snapshot'

    // use notOk because snap doesn't return a truthy value
    const m = this.fullname + ' > ' + message
    if (typeof found !== 'string') {
      found = (this.formatSnapshot || formatSnapshotDefault)(found)
      if (typeof found !== 'string')
        found = formatSnapshotDefault(found)
    }

    found = this.cleanSnapshot(found)

    return this.writeSnapshot
      ? this.notOk(this[_getSnapshot]().snap(found, m),
        message, extra)
      : this.equal(found, this[_getSnapshot]().read(m),
        message, extra)
  }

  [_getSnapshot] () {
    if (this[_snapshot])
      return this[_snapshot]

    if (this.parent) {
      const parentSnapshot = this.parent[_getSnapshot]()
      // very rare for the parent to not have one.
      /* istanbul ignore else */
      if (parentSnapshot)
        return this[_snapshot] = parentSnapshot
    }

    return this[_snapshot] = new Snapshot(this)
  }

  cleanSnapshot (string) {
    return string
  }

  hasStrict (found, wanted, message, extra) {
    this.currentAssert = Test.prototype.hasStrict

    if (message && typeof message === 'object')
      extra = message, message = ''

    if (!extra)
      extra = {}

    message = message || 'should contain all provided fields strictly'
    const s = hasStrict(found, wanted)
    if (!s.match)
      extra.diff = s.diff
    else {
      extra.found = found
      extra.pattern = wanted
    }
    return this.ok(s.match, message, extra)
  }

  match (found, wanted, message, extra) {
    this.currentAssert = Test.prototype.match

    if (message && typeof message === 'object')
      extra = message, message = ''

    if (!extra)
      extra = {}

    message = message || 'should match pattern provided'
    const s = match(found, wanted)
    if (!s.match)
      extra.diff = s.diff
    else
      extra.found = found
    extra.pattern = wanted
    return this.ok(s.match, message, extra)
  }

  notMatch (found, wanted, message, extra) {
    this.currentAssert = Test.prototype.notMatch

    if (message && typeof message === 'object')
      extra = message, message = ''

    if (!extra)
      extra = {}

    message = message || 'should not match pattern provided'
    extra.found = found
    extra.pattern = wanted
    const s = match(found, wanted)
    return this.notOk(s.match, message, extra)
  }

  type (obj, klass, message, extra) {
    this.currentAssert = Test.prototype.type

    if (message && typeof message === 'object')
      extra = message, message = ''

    if (!extra)
      extra = {}

    const name = typeof klass === 'function' ?
      klass.name || '(anonymous constructor)'
      : klass

    message = message || 'type is ' + name

    // simplest case, it literally is the same thing
    if (obj === klass) {
      return this.pass(message, extra)
    }

    const tof = typeof obj
    const type = (!obj && tof === 'object') ? 'null'
      // treat as object, but not Object
      // t.type(() => {}, Function)
      : (tof === 'function' &&
        typeof klass === 'function' &&
        klass !== Object) ? 'object'
      : tof

    if (type === 'object' && klass !== 'object') {
      if (typeof klass === 'function') {
        extra.found = Object.getPrototypeOf(obj).constructor.name
        extra.wanted = name
        return this.ok(obj instanceof klass, message, extra)
      }

      // check prototype chain for name
      // at this point, we already know klass is not a function
      // if the klass specified is an obj in the proto chain, pass
      // if the name specified is the name of a ctor in the chain, pass
      for (let p = obj; p; p = Object.getPrototypeOf(p)) {
        const ctor = p.constructor && p.constructor.name
        if (p === klass || ctor === name) {
          return this.pass(message, extra)
        }
      }
    }

    return this.equal(type, name, message, extra)
  }

  expectUncaughtException (...args) {
    let [_, ...rest] = this.throwsArgs('expect uncaughtException', ...args)
    this[_expectUncaught].push(rest)
  }

  throwsArgs (defaultMessage, ...args) {
    let fn, wanted, message, extra
    for (let i = 0; i < args.length; i++) {
      const arg = args[i]
      if (typeof arg === 'function') {
        if (arg === Error || arg.prototype instanceof Error) {
          wanted = arg
        } else if (!fn) {
          fn = arg
        }
      } else if (typeof arg === 'string' && arg) {
        message = arg
      } else if (typeof arg === 'object') {
        if (!wanted) {
          wanted = arg
        } else {
          extra = arg
        }
      }
    }

    if (!extra)
      extra = {}

    if (!message)
      message = fn && fn.name || defaultMessage

    if (wanted) {
      if (wanted instanceof Error) {
        const w = {
          message: wanted.message
        }
        if (wanted.name) {
          w.name = wanted.name
        }

        // intentionally copying non-local properties, since this
        // is an Error object, and those are funky.
        for (let i in wanted) {
          w[i] = wanted[i]
        }
        wanted = w

        message += ': ' + (wanted.name || 'Error') + ' ' + wanted.message
        extra.wanted = wanted
      }
    }

    return [fn, wanted, message, extra]
  }

  throws (...args) {
    this.currentAssert = Test.prototype.throws

    const [fn, wanted, message, extra] =
      this.throwsArgs('expected to throw', ...args)

    if (typeof fn !== 'function') {
      extra.todo = extra.todo || true
      return this.pass(message, extra)
    }

    try {
      fn()
      return this.fail(message, extra)
    } catch (er) {
      // 'name' is a getter.
      if (er.name) {
        Object.defineProperty(er, 'name', {
          value: er.name + '',
          enumerable: true,
          configurable: true,
          writable: true
        })
      }

      const actual = isRegExp(wanted) ? er.message : er
      return wanted
        ? this.match(actual, wanted, message, extra) && er
        : this.pass(message, extra) && er
    }
  }

  doesNotThrow (fn, message, extra) {
    this.currentAssert = Test.prototype.doesNotThrow

    if (message && typeof message === 'object')
      extra = message, message = ''

    if (!extra)
      extra = {}

    if (typeof fn === 'string') {
      const x = fn
      fn = message
      message = x
    }

    if (!message) {
      message = fn && fn.name || 'expected to not throw'
    }

    if (typeof fn !== 'function') {
      extra.todo = extra.todo || true
      return this.pass(message, extra)
    }

    try {
      fn()
      return this.pass(message, extra)
    } catch (er) {
      const e = extraFromError(er, extra)
      e.message = er.message
      return this.fail(message, e)
    }
  }

  waitOn (promise, cb, expectReject) {
    const w = new Waiter(promise, w => {
      assert.equal(this.occupied, w)
      cb(w)
      this.occupied = null
      this.process()
    })
    w.expectReject = !!expectReject
    this.queue.push(w)
    this.process()
    return w.promise
  }

  // like throws, but rejects a returned promise instead
  // also, can pass in a promise instead of a function
  rejects (...args) {
    this.currentAssert = Test.prototype.rejects

    let fn, wanted, extra, promise, message
    for (let i = 0; i < args.length; i++) {
      const arg = args[i]
      if (typeof arg === 'function') {
        if (arg === Error || arg.prototype instanceof Error) {
          wanted = arg
        } else if (!fn) {
          fn = arg
        }
      } else if (typeof arg === 'string' && arg) {
        message = arg
      } else if (arg && typeof arg.then === 'function' && !promise) {
        promise = arg
      } else if (typeof arg === 'object') {
        if (!wanted) {
          wanted = arg
        } else {
          extra = arg
        }
      }
    }

    if (!extra)
      extra = {}

    if (!message)
      message = fn && fn.name || 'expect rejected Promise'

    if (wanted) {
      if (wanted instanceof Error) {
        const w = {
          message: wanted.message
        }
        if (wanted.name)
          w.name = wanted.name

        // intentionally copying non-local properties, since this
        // is an Error object, and those are funky.
        for (let i in wanted) {
          w[i] = wanted[i]
        }
        wanted = w

        message += ': ' + (wanted.name || 'Error') + ' ' + wanted.message
        extra.wanted = wanted
      }
    }

    if (!promise && typeof fn !== 'function') {
      extra.todo = extra.todo || true
      this.pass(message, extra)
      return Promise.resolve(this)
    }

    if (!promise)
      promise = fn()

    if (!promise || typeof promise.then !== 'function') {
      this.fail(message, extra)
      return Promise.resolve(this)
    }

    extra.at = stack.at(this.currentAssert)
    return this.waitOn(promise, w => {
      if (!w.rejected) {
        extra.found = w.value
        return this.fail(message, extra)
      }

      const er = w.value
      // 'name' is a getter.
      if (er && er.name) {
        Object.defineProperty(er, 'name', {
          value: er.name + '',
          enumerable: true,
          configurable: true,
          writable: true
        })
      }

      const actual = isRegExp(wanted) && er ? er.message : er
      return wanted ? this.match(actual, wanted, message, extra)
        : this.pass(message, extra)
    }, true)
  }

  resolves (promise, message, extra) {
    this.currentAssert = Test.prototype.resolves

    if (message && typeof message === 'object')
      extra = message, message = ''

    if (!extra)
      extra = {}

    if (!message)
      message = 'expect resolving Promise'

    if (typeof promise === 'function')
      promise = promise()

    extra.at = stack.at(this.currentAssert)

    if (!promise || typeof promise.then !== 'function') {
      this.fail(message, extra)
      return Promise.resolve(this)
    }

    return this.waitOn(promise, w => {
      extra.found = w.value
      this.ok(w.resolved, message, extra)
    })
  }

  resolveMatch (promise, wanted, message, extra) {
    this.currentAssert = Test.prototype.resolveMatch

    if (message && typeof message === 'object')
      extra = message, message = ''

    if (!extra)
      extra = {}

    if (!message)
      message = 'expect resolving Promise'

    extra.at = stack.at(this.currentAssert)

    if (typeof promise === 'function')
      promise = promise()

    if (!promise || typeof promise.then !== 'function') {
      this.fail(message, extra)
      return Promise.resolve(this)
    }

    return this.waitOn(promise, w => {
      extra.found = w.value
      return w.rejected ? this.fail(message, extra)
        : this.match(w.value, wanted, message, extra)
    })
  }

  resolveMatchSnapshot (promise, message, extra) {
    this.currentAssert = Test.prototype.resolveMatch

    if (message && typeof message === 'object')
      extra = message, message = ''

    if (!extra)
      extra = {}

    if (!message)
      message = 'expect resolving Promise'

    extra.at = stack.at(this.currentAssert)

    if (typeof promise === 'function')
      promise = promise()

    if (!promise || typeof promise.then !== 'function') {
      this.fail(message, extra)
      return Promise.resolve(this)
    }

    return this.waitOn(promise, w => {
      extra.found = w.value
      return w.rejected ? this.fail(message, extra)
        : this.matchSnapshot(w.value, message, extra)
    })
  }
}

const endAllQueue = queue => {
  queue.forEach((p, i) => {
    if ((p instanceof Base) && !p.readyToProcess)
      queue[i] = new TestPoint(false,
        'child test left in queue:' +
        ' t.' + p.constructor.name.toLowerCase() + ' ' + p.name,
        p.options)
  })
  queue.push(['end', IMPLICIT])
}

const queueEmpty = t =>
  t.queue.length === 0 ||
    t.queue.length === 1 && t.queue[0] === 'TAP version 13\n'

Test.prototype.done = Test.prototype.end
Test.prototype.tearDown = Test.prototype.teardown

Object.keys(synonyms)
  .filter(c => Test.prototype[c])
  .forEach(c => synonyms[c].forEach(s =>
    Object.defineProperty(Test.prototype, s, {
      value: Test.prototype[c],
      enumerable: false,
      configurable: true,
      writable: true
    })))

module.exports = Test