Skip to content

Commit

Permalink
chore: switch from tap to node:test and Borp (#39)
Browse files Browse the repository at this point in the history
To do this, I:

- Uninstalled `tap` and replaced it with `borp`
- Used `c8` for test coverage
  - This changed the way coverage was detected around the `??=`
    operator, so I had to write an additional unit test
- Wrote a [jscodeshift] codemod (below)
- Dropped Node 16 support, which `node:test` requires
- Made a few small manual tweaks

Here's the jscodeshift transformer:

```typescript
import type {
  Transform,
  Expression,
  FunctionExpression,
  ArrowFunctionExpression,
} from 'jscodeshift'

const isFunctionExpression = (
  expression: Readonly<Expression>
): expression is FunctionExpression | ArrowFunctionExpression =>
  expression.type === 'FunctionExpression' ||
  expression.type === 'ArrowFunctionExpression'

const transform: Transform = (fileInfo, api) => {
  const { j } = api
  const root = j(fileInfo.source)

  // Update imports

  {
    const commonJsImport = (varName: string, moduleName: string) =>
      j.variableDeclaration('const', [
        j.variableDeclarator(
          j.identifier(varName),
          j.callExpression(j.identifier('require'), [
            j.stringLiteral(moduleName),
          ])
        ),
      ])

    const tapImport = root.find(j.VariableDeclaration, {
      declarations: [
        {
          init: {
            callee: { name: 'require' },
            arguments: [
              {
                value: 'tap',
              },
            ],
          },
        },
      ],
    })

    tapImport.insertBefore(commonJsImport('test', 'node:test'))
    tapImport.insertBefore(commonJsImport('assert', 'node:assert/strict'))

    tapImport.remove()
  }

  // Drop args from test callback

  root
    .find(j.CallExpression, { callee: { name: 'test' } })
    .forEach((callExpression) => {
      for (const arg of callExpression.value.arguments) {
        if (!isFunctionExpression(arg)) continue
        arg.params = []
      }
    })

  // Drop t.pass

  root
    .find(j.ExpressionStatement, {
      expression: {
        callee: {
          type: 'MemberExpression',
          object: { name: 't' },
          property: { name: 'pass' },
        },
      },
    })
    .remove()

  // Simple replacements of various calls

  {
    const toReplace: Map<string, string> = new Map([
      ['comment', 'console.log'],
      ['equal', 'assert.equal'],
      ['fail', 'assert.fail'],
      ['not', 'assert.notEqual'],
      ['ok', 'assert.ok'],
      ['same', 'assert.deepEqual'],
    ])
    for (const [tMethod, memberExpressionString] of toReplace) {
      const [newObj, newProp] = memberExpressionString.split('.')
      root
        .find(j.MemberExpression, {
          object: { name: 't' },
          property: { name: tMethod },
        })
        .forEach((memberExpression) => {
          memberExpression.value.object = j.identifier(newObj)
          memberExpression.value.property = j.identifier(newProp)
        })
    }
  }

  // Replace `t.notOk(x)` with `assert.equal(x, false)`.
  // Doesn't always work, but works how we use it.

  root
    .find(j.CallExpression, {
      callee: {
        type: 'MemberExpression',
        object: { name: 't' },
        property: { name: 'notOk' },
      },
    })
    .forEach((callExpression) => {
      callExpression.value.callee = j.memberExpression(
        j.identifier('assert'),
        j.identifier('equal')
      )
      callExpression.value.arguments = [
        callExpression.value.arguments[0],
        j.booleanLiteral(false),
        ...callExpression.value.arguments.slice(1),
      ]
    })

  // All done!

  return root.toSource()
}

export default transform
```

[jscodeshift]: https://github.com/facebook/jscodeshift
  • Loading branch information
EvanHahn committed Mar 12, 2024
1 parent 7cd3aaf commit 9b81ec1
Show file tree
Hide file tree
Showing 12 changed files with 4,274 additions and 10,079 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jobs:

strategy:
matrix:
node-version: [16.17.1, 18.17.1, 20.x]
node-version: [18.17.1, 20.x]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/

steps:
Expand Down
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ class MultiCoreIndexer extends TypedEmitter {
/** @param {Entry<T>[]} entries */
async #handleEntries(entries) {
this.#emitState()
/* istanbul ignore if - not sure this is necessary, but better safe than sorry */
/* c8 ignore next - not sure this is necessary, but better safe than sorry */
if (!entries.length) return
await this.#batch(entries)
for (const { key, index } of entries) {
Expand Down
16 changes: 8 additions & 8 deletions lib/bitfield.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
const BigSparseArray = require('big-sparse-array')
const b4a = require('b4a')

/* istanbul ignore next */
/* c8 ignore start */
class FixedBitfield {
/**
* @param {number} index
Expand Down Expand Up @@ -41,8 +41,9 @@ class FixedBitfield {
return true
}
}
/* c8 ignore stop */

/* istanbul ignore next */
/* c8 ignore start */
class Bitfield {
/**
*
Expand Down Expand Up @@ -177,6 +178,7 @@ class Bitfield {
})
}
}
/* c8 ignore stop */

module.exports = Bitfield

Expand All @@ -185,11 +187,9 @@ module.exports = Bitfield
* @param {number} size
*/
function ensureSize(uint32, size) {
/* istanbul ignore else */
if (uint32.length === size) return uint32
else {
const a = new Uint32Array(1024)
a.set(uint32, 0)
return a
}
/* c8 ignore next 3 */
const a = new Uint32Array(1024)
a.set(uint32, 0)
return a
}
8 changes: 4 additions & 4 deletions lib/core-index-stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ class CoreIndexStream extends Readable {
this.#createStorage = async () => {
await this.#core.ready()
const { discoveryKey } = this.#core
/* istanbul ignore next: just to keep TS happy - after core.ready() this is set */
/* c8 ignore next: just to keep TS happy - after core.ready() this is set */
if (!discoveryKey) throw new Error('Missing discovery key')
return createStorage(getStorageName(discoveryKey))
}
Expand Down Expand Up @@ -155,15 +155,15 @@ class CoreIndexStream extends Readable {
this.#downloaded.delete(index)
didPush =
(await this.#pushEntry(index)) ||
/* istanbul ignore next - TODO: Test when hypercore-next supports a core.clear() method */
/* c8 ignore next - TODO: Test when hypercore-next supports a core.clear() method */
didPush
// This is for back-pressure, for which there is not a good test yet.
// The faster streamx state machine in https://github.com/mafintosh/streamx/pull/77
// caused this stream's read buffer to never fill with the current tests,
// so that this line is currently uncovered by tests.
// TODO: Add a test similar to 'Appends from a replicated core are indexed' in core-index-stream.test.js
// but pipe to a slow stream, to test back-pressure, which should result in coverage of this line.
/* istanbul ignore next */
/* c8 ignore next */
if (!this.#readBufferAvailable) break
}
}
Expand All @@ -188,7 +188,7 @@ class CoreIndexStream extends Readable {
if (block === null) return false
this.#inProgressBitfield?.set(index, true)
this.#inProgress++
/* istanbul ignore next: this should always be set at this point */
/* c8 ignore next: this should always be set at this point */
if (!this.#core.key) throw new Error('Missing core key')
const entry = { key: this.#core.key, block, index }
this.#readBufferAvailable = this.push(entry)
Expand Down
6 changes: 3 additions & 3 deletions lib/multi-core-index-stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ class MultiCoreIndexStream extends Readable {
*/
setIndexed(streamId, index) {
const stream = this.#streamsById.get(streamId)
/* istanbul ignore next: this should always be true */
/* c8 ignore next: this should always be true */
if (!stream) return
stream.setIndexed(index)
}
Expand All @@ -92,7 +92,7 @@ class MultiCoreIndexStream extends Readable {
.ready()
.then(() => {
const coreKey = stream.core.key
/* istanbul ignore next: this is set after ready */
/* c8 ignore next: this is set after ready */
if (!coreKey) return
this.#streamsById.set(coreKey.toString('hex'), stream)
})
Expand Down Expand Up @@ -201,5 +201,5 @@ class MultiCoreIndexStream extends Readable {

exports.MultiCoreIndexStream = MultiCoreIndexStream

/* istanbul ignore next: TODO add test for adding broken cores */
/* c8 ignore next: TODO add test for adding broken cores */
function noop() {}
Loading

0 comments on commit 9b81ec1

Please sign in to comment.