diff --git a/test/dispatcher.js b/test/dispatcher.js index fbb56e94bc1..f2148a0b5c1 100644 --- a/test/dispatcher.js +++ b/test/dispatcher.js @@ -1,6 +1,5 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { test } = require('node:test') const Dispatcher = require('../lib/dispatcher/dispatcher') @@ -8,32 +7,32 @@ const Dispatcher = require('../lib/dispatcher/dispatcher') class PoorImplementation extends Dispatcher {} test('dispatcher implementation', (t) => { - t = tspl(t, { plan: 6 }) + t.plan(6) const dispatcher = new Dispatcher() - t.throws(() => dispatcher.dispatch(), Error, 'throws on unimplemented dispatch') - t.throws(() => dispatcher.close(), Error, 'throws on unimplemented close') - t.throws(() => dispatcher.destroy(), Error, 'throws on unimplemented destroy') + t.assert.throws(() => dispatcher.dispatch(), Error, 'throws on unimplemented dispatch') + t.assert.throws(() => dispatcher.close(), Error, 'throws on unimplemented close') + t.assert.throws(() => dispatcher.destroy(), Error, 'throws on unimplemented destroy') const poorImplementation = new PoorImplementation() - t.throws(() => poorImplementation.dispatch(), Error, 'throws on unimplemented dispatch') - t.throws(() => poorImplementation.close(), Error, 'throws on unimplemented close') - t.throws(() => poorImplementation.destroy(), Error, 'throws on unimplemented destroy') + t.assert.throws(() => poorImplementation.dispatch(), Error, 'throws on unimplemented dispatch') + t.assert.throws(() => poorImplementation.close(), Error, 'throws on unimplemented close') + t.assert.throws(() => poorImplementation.destroy(), Error, 'throws on unimplemented destroy') }) test('dispatcher.compose', (t) => { - t = tspl(t, { plan: 7 }) + t.plan(7) const dispatcher = new Dispatcher() const interceptor = () => (opts, handler) => {} // Should return a new dispatcher - t.ok(dispatcher.compose(interceptor) !== dispatcher) - t.throws(() => dispatcher.dispatch({}), Error, 'invalid interceptor') - t.throws(() => dispatcher.dispatch(() => null), Error, 'invalid interceptor') - t.throws(() => dispatcher.dispatch(dispatch => dispatch, () => () => {}, Error, 'invalid interceptor')) + t.assert.ok(dispatcher.compose(interceptor) !== dispatcher) + t.assert.throws(() => dispatcher.dispatch({}), Error, 'invalid interceptor') + t.assert.throws(() => dispatcher.dispatch(() => null), Error, 'invalid interceptor') + t.assert.throws(() => dispatcher.dispatch(dispatch => dispatch, () => () => {}, Error, 'invalid interceptor')) const composed = dispatcher.compose(interceptor) - t.equal(typeof composed.dispatch, 'function', 'returns an object with a dispatch method') - t.equal(typeof composed.close, 'function', 'returns an object with a close method') - t.equal(typeof composed.destroy, 'function', 'returns an object with a destroy method') + t.assert.strictEqual(typeof composed.dispatch, 'function', 'returns an object with a dispatch method') + t.assert.strictEqual(typeof composed.close, 'function', 'returns an object with a close method') + t.assert.strictEqual(typeof composed.destroy, 'function', 'returns an object with a destroy method') }) diff --git a/test/errors.js b/test/errors.js index e34b406a905..f76f0425165 100644 --- a/test/errors.js +++ b/test/errors.js @@ -1,6 +1,5 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { describe, test } = require('node:test') const errors = require('../lib/core/errors') @@ -38,28 +37,28 @@ scenarios.forEach(scenario => { const errorWithProvidedMessage = () => new scenario.ErrorClass(SAMPLE_MESSAGE) test('should use default message', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const error = errorWithDefaultMessage() - t.strictEqual(error.message, scenario.defaultMessage) + t.assert.strictEqual(error.message, scenario.defaultMessage) }) test('should use provided message', t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const error = errorWithProvidedMessage() - t.strictEqual(error.message, SAMPLE_MESSAGE) + t.assert.strictEqual(error.message, SAMPLE_MESSAGE) }) test('should have proper fields', t => { - t = tspl(t, { plan: 6 }) + t.plan(6) const errorInstances = [errorWithDefaultMessage(), errorWithProvidedMessage()] errorInstances.forEach(error => { - t.strictEqual(error.name, scenario.name) - t.strictEqual(error.code, scenario.code) - t.ok(error.stack) + t.assert.strictEqual(error.name, scenario.name) + t.assert.strictEqual(error.code, scenario.code) + t.assert.ok(error.stack) }) }) }) @@ -67,11 +66,11 @@ scenarios.forEach(scenario => { describe('Default HTTPParseError Codes', () => { test('code and data should be undefined when not set', t => { - t = tspl(t, { plan: 2 }) + t.plan(2) const error = new errors.HTTPParserError('HTTPParserError') - t.strictEqual(error.code, undefined) - t.strictEqual(error.data, undefined) + t.assert.strictEqual(error.code, undefined) + t.assert.strictEqual(error.data, undefined) }) }) diff --git a/test/examples.js b/test/examples.js index 055f082b3fd..38c8e2e7d7e 100644 --- a/test/examples.js +++ b/test/examples.js @@ -1,13 +1,12 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { createServer } = require('node:http') const { test, after } = require('node:test') const { once } = require('node:events') const examples = require('../docs/examples/request.js') test('request examples', async (t) => { - t = tspl(t, { plan: 7 }) + t.plan(7) let lastReq const exampleServer = createServer({ joinDuplicateHeaders: true }, (req, res) => { @@ -48,21 +47,19 @@ test('request examples', async (t) => { ]) await examples.getRequest(exampleServer.address().port) - t.strictEqual(lastReq.method, 'GET') + t.assert.strictEqual(lastReq.method, 'GET') await examples.postJSONRequest(exampleServer.address().port) - t.strictEqual(lastReq.method, 'POST') - t.strictEqual(lastReq.headers['content-type'], 'application/json') + t.assert.strictEqual(lastReq.method, 'POST') + t.assert.strictEqual(lastReq.headers['content-type'], 'application/json') await examples.postFormRequest(exampleServer.address().port) - t.strictEqual(lastReq.method, 'POST') - t.strictEqual(lastReq.headers['content-type'], 'application/x-www-form-urlencoded') + t.assert.strictEqual(lastReq.method, 'POST') + t.assert.strictEqual(lastReq.headers['content-type'], 'application/x-www-form-urlencoded') await examples.deleteRequest(exampleServer.address().port) - t.strictEqual(lastReq.method, 'DELETE') + t.assert.strictEqual(lastReq.method, 'DELETE') await examples.deleteRequest(errorServer.address().port) - t.strictEqual(lastReq.method, 'DELETE') - - await t.completed + t.assert.strictEqual(lastReq.method, 'DELETE') }) diff --git a/test/fixed-queue.js b/test/fixed-queue.js index 3cb1b392ff4..e7503cfe425 100644 --- a/test/fixed-queue.js +++ b/test/fixed-queue.js @@ -1,39 +1,38 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { test } = require('node:test') const FixedQueue = require('../lib/dispatcher/fixed-queue') test('fixed queue 1', (t) => { - t = tspl(t, { plan: 5 }) + t.plan(5) const queue = new FixedQueue() - t.strictEqual(queue.head, queue.tail) - t.ok(queue.isEmpty()) + t.assert.strictEqual(queue.head, queue.tail) + t.assert.ok(queue.isEmpty()) queue.push('a') - t.ok(!queue.isEmpty()) - t.strictEqual(queue.shift(), 'a') - t.strictEqual(queue.shift(), null) + t.assert.ok(!queue.isEmpty()) + t.assert.strictEqual(queue.shift(), 'a') + t.assert.strictEqual(queue.shift(), null) }) test('fixed queue 2', (t) => { - t = tspl(t, { plan: 7 + 2047 }) + t.plan(7 + 2047) const queue = new FixedQueue() for (let i = 0; i < 2047; i++) { queue.push('a') } - t.ok(queue.head.isFull()) + t.assert.ok(queue.head.isFull()) queue.push('a') - t.ok(!queue.head.isFull()) + t.assert.ok(!queue.head.isFull()) - t.notEqual(queue.head, queue.tail) + t.assert.notEqual(queue.head, queue.tail) for (let i = 0; i < 2047; i++) { - t.strictEqual(queue.shift(), 'a') + t.assert.strictEqual(queue.shift(), 'a') } - t.strictEqual(queue.head, queue.tail) - t.ok(!queue.isEmpty()) - t.strictEqual(queue.shift(), 'a') - t.ok(queue.isEmpty()) + t.assert.strictEqual(queue.head, queue.tail) + t.assert.ok(!queue.isEmpty()) + t.assert.strictEqual(queue.shift(), 'a') + t.assert.ok(queue.isEmpty()) }) diff --git a/test/install.js b/test/install.js index 69f3a7617f5..1c24c669560 100644 --- a/test/install.js +++ b/test/install.js @@ -1,11 +1,10 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') const undici = require('../index') const { installedExports } = require('../lib/global') -test('install() should overwrite only specified elements in globalThis', () => { +test('install() should overwrite only specified elements in globalThis', (t) => { const exportsToCheck = new Set(installedExports) // Use a Proxy to verify that only the expected globals are set @@ -26,24 +25,24 @@ test('install() should overwrite only specified elements in globalThis', () => { undici.install() - assert.strictEqual(exportsToCheck.size, 0, `Some expected globals were not set: ${[...exportsToCheck].join(', ')}`) + t.assert.strictEqual(exportsToCheck.size, 0, `Some expected globals were not set: ${[...exportsToCheck].join(', ')}`) // Verify that the installed globals match the exports from undici for (const name of installedExports) { - assert.strictEqual(globalThis[name], undici[name]) + t.assert.strictEqual(globalThis[name], undici[name]) } // Test that the installed classes are functional const headers = new globalThis.Headers([['content-type', 'application/json']]) - assert.strictEqual(headers.get('content-type'), 'application/json') + t.assert.strictEqual(headers.get('content-type'), 'application/json') const request = new globalThis.Request('https://example.com') - assert.strictEqual(request.url, 'https://example.com/') + t.assert.strictEqual(request.url, 'https://example.com/') const response = new globalThis.Response('test body') - assert.strictEqual(response.status, 200) + t.assert.strictEqual(response.status, 200) const formData = new globalThis.FormData() formData.append('key', 'value') - assert.strictEqual(formData.get('key'), 'value') + t.assert.strictEqual(formData.get('key'), 'value') }) diff --git a/test/invalid-headers.js b/test/invalid-headers.js index 5d49fcbf23f..e5ee783314b 100644 --- a/test/invalid-headers.js +++ b/test/invalid-headers.js @@ -1,11 +1,10 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { test, after } = require('node:test') const { Client, errors } = require('..') test('invalid headers', (t) => { - t = tspl(t, { plan: 10 }) + t.plan(10) const client = new Client('http://localhost:3000') after(() => client.close()) @@ -16,7 +15,7 @@ test('invalid headers', (t) => { 'content-length': 'asd' } }, (err, data) => { - t.ok(err instanceof errors.InvalidArgumentError) + t.assert.ok(err instanceof errors.InvalidArgumentError) }) client.request({ @@ -24,7 +23,7 @@ test('invalid headers', (t) => { method: 'GET', headers: 1 }, (err, data) => { - t.ok(err instanceof errors.InvalidArgumentError) + t.assert.ok(err instanceof errors.InvalidArgumentError) }) client.request({ @@ -34,7 +33,7 @@ test('invalid headers', (t) => { 'transfer-encoding': 'chunked' } }, (err, data) => { - t.ok(err instanceof errors.InvalidArgumentError) + t.assert.ok(err instanceof errors.InvalidArgumentError) }) client.request({ @@ -44,7 +43,7 @@ test('invalid headers', (t) => { upgrade: 'asd' } }, (err, data) => { - t.ok(err instanceof errors.InvalidArgumentError) + t.assert.ok(err instanceof errors.InvalidArgumentError) }) client.request({ @@ -54,7 +53,7 @@ test('invalid headers', (t) => { connection: 'asd' } }, (err, data) => { - t.ok(err instanceof errors.InvalidArgumentError) + t.assert.ok(err instanceof errors.InvalidArgumentError) }) client.request({ @@ -64,7 +63,7 @@ test('invalid headers', (t) => { 'keep-alive': 'timeout=5' } }, (err, data) => { - t.ok(err instanceof errors.InvalidArgumentError) + t.assert.ok(err instanceof errors.InvalidArgumentError) }) client.request({ @@ -74,7 +73,7 @@ test('invalid headers', (t) => { foo: {} } }, (err, data) => { - t.ok(err instanceof errors.InvalidArgumentError) + t.assert.ok(err instanceof errors.InvalidArgumentError) }) client.request({ @@ -84,7 +83,7 @@ test('invalid headers', (t) => { expect: '100-continue' } }, (err, data) => { - t.ok(err instanceof errors.NotSupportedError) + t.assert.ok(err instanceof errors.NotSupportedError) }) client.request({ @@ -94,7 +93,7 @@ test('invalid headers', (t) => { Expect: '100-continue' } }, (err, data) => { - t.ok(err instanceof errors.NotSupportedError) + t.assert.ok(err instanceof errors.NotSupportedError) }) client.request({ @@ -104,6 +103,6 @@ test('invalid headers', (t) => { expect: 'asd' } }, (err, data) => { - t.ok(err instanceof errors.NotSupportedError) + t.assert.ok(err instanceof errors.NotSupportedError) }) }) diff --git a/test/proxy-agent.js b/test/proxy-agent.js index b2636c7d3f8..e99e6f5e07f 100644 --- a/test/proxy-agent.js +++ b/test/proxy-agent.js @@ -1,6 +1,5 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { test, after } = require('node:test') const { request, fetch, setGlobalDispatcher, getGlobalDispatcher } = require('..') const { InvalidArgumentError, SecureProxyConnectionError } = require('../lib/core/errors') @@ -96,14 +95,14 @@ const certs = (() => { })() test('should throw error when no uri is provided', (t) => { - t = tspl(t, { plan: 2 }) - t.throws(() => new ProxyAgent(), InvalidArgumentError) - t.throws(() => new ProxyAgent({}), InvalidArgumentError) + t.plan(2) + t.assert.throws(() => new ProxyAgent(), InvalidArgumentError) + t.assert.throws(() => new ProxyAgent({}), InvalidArgumentError) }) test('using auth in combination with token should throw', (t) => { - t = tspl(t, { plan: 1 }) - t.throws(() => new ProxyAgent({ + t.plan(1) + t.assert.throws(() => new ProxyAgent({ auth: 'foo', token: 'Bearer bar', uri: 'http://example.com' @@ -113,14 +112,14 @@ test('using auth in combination with token should throw', (t) => { }) test('should accept string, URL and object as options', (t) => { - t = tspl(t, { plan: 3 }) - t.doesNotThrow(() => new ProxyAgent('http://example.com')) - t.doesNotThrow(() => new ProxyAgent(new URL('http://example.com'))) - t.doesNotThrow(() => new ProxyAgent({ uri: 'http://example.com' })) + t.plan(3) + t.assert.doesNotThrow(() => new ProxyAgent('http://example.com')) + t.assert.doesNotThrow(() => new ProxyAgent(new URL('http://example.com'))) + t.assert.doesNotThrow(() => new ProxyAgent({ uri: 'http://example.com' })) }) test('use proxy-agent to connect through proxy (keep alive)', async (t) => { - t = tspl(t, { plan: 6 }) + t.plan(6) const server = await buildServer() const proxy = await buildProxy() delete proxy.authenticate @@ -134,12 +133,12 @@ test('use proxy-agent to connect through proxy (keep alive)', async (t) => { const parsedOrigin = new URL(serverUrl) proxy.on('connect', (msg) => { - t.strictEqual(msg.headers['proxy-connection'], 'keep-alive') + t.assert.strictEqual(msg.headers['proxy-connection'], 'keep-alive') }) server.on('request', (req, res) => { - t.strictEqual(req.url, '/') - t.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') + t.assert.strictEqual(req.url, '/') + t.assert.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') res.setHeader('content-type', 'application/json') res.end(JSON.stringify({ hello: 'world' })) }) @@ -151,9 +150,9 @@ test('use proxy-agent to connect through proxy (keep alive)', async (t) => { } = await request(serverUrl, { dispatcher: proxyAgent }) const json = await body.json() - t.strictEqual(statusCode, 200) - t.deepStrictEqual(json, { hello: 'world' }) - t.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') + t.assert.strictEqual(statusCode, 200) + t.assert.deepStrictEqual(json, { hello: 'world' }) + t.assert.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') server.close() proxy.close() @@ -161,7 +160,7 @@ test('use proxy-agent to connect through proxy (keep alive)', async (t) => { }) test('use proxy-agent to connect through proxy', async (t) => { - t = tspl(t, { plan: 6 }) + t.plan(6) const server = await buildServer() const proxy = await buildProxy() delete proxy.authenticate @@ -172,12 +171,12 @@ test('use proxy-agent to connect through proxy', async (t) => { const parsedOrigin = new URL(serverUrl) proxy.on('connect', () => { - t.ok(true, 'should connect to proxy') + t.assert.ok(true, 'should connect to proxy') }) server.on('request', (req, res) => { - t.strictEqual(req.url, '/') - t.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') + t.assert.strictEqual(req.url, '/') + t.assert.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') res.setHeader('content-type', 'application/json') res.end(JSON.stringify({ hello: 'world' })) }) @@ -189,9 +188,9 @@ test('use proxy-agent to connect through proxy', async (t) => { } = await request(serverUrl, { dispatcher: proxyAgent }) const json = await body.json() - t.strictEqual(statusCode, 200) - t.deepStrictEqual(json, { hello: 'world' }) - t.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') + t.assert.strictEqual(statusCode, 200) + t.assert.deepStrictEqual(json, { hello: 'world' }) + t.assert.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') server.close() proxy.close() @@ -199,7 +198,7 @@ test('use proxy-agent to connect through proxy', async (t) => { }) test('use proxy agent to connect through proxy using Pool', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await buildServer() const proxy = await buildProxy() let resolveFirstConnect @@ -207,7 +206,7 @@ test('use proxy agent to connect through proxy using Pool', async (t) => { proxy.authenticate = async function (req) { if (++connectCount === 2) { - t.ok(true, 'second connect should arrive while first is still inflight') + t.assert.ok(true, 'second connect should arrive while first is still inflight') resolveFirstConnect() return true } else { @@ -230,15 +229,15 @@ test('use proxy agent to connect through proxy using Pool', async (t) => { const proxyAgent = new ProxyAgent({ auth: Buffer.from('user:pass').toString('base64'), uri: proxyUrl, clientFactory }) const firstRequest = request(`${serverUrl}`, { dispatcher: proxyAgent }) const secondRequest = await request(`${serverUrl}`, { dispatcher: proxyAgent }) - t.strictEqual((await firstRequest).statusCode, 200) - t.strictEqual(secondRequest.statusCode, 200) + t.assert.strictEqual((await firstRequest).statusCode, 200) + t.assert.strictEqual(secondRequest.statusCode, 200) server.close() proxy.close() proxyAgent.close() }) test('use proxy-agent to connect through proxy using path with params', async (t) => { - t = tspl(t, { plan: 5 }) + t.plan(5) const server = await buildServer() const proxy = await buildProxy() @@ -248,11 +247,11 @@ test('use proxy-agent to connect through proxy using path with params', async (t const parsedOrigin = new URL(serverUrl) proxy.on('connect', () => { - t.fail('proxy tunnel should not be established') + t.assert.fail('proxy tunnel should not be established') }) server.on('request', (req, res) => { - t.strictEqual(req.url, '/hello?foo=bar') - t.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') + t.assert.strictEqual(req.url, '/hello?foo=bar') + t.assert.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') res.setHeader('content-type', 'application/json') res.end(JSON.stringify({ hello: 'world' })) }) @@ -264,9 +263,9 @@ test('use proxy-agent to connect through proxy using path with params', async (t } = await request(serverUrl + '/hello?foo=bar', { dispatcher: proxyAgent }) const json = await body.json() - t.strictEqual(statusCode, 200) - t.deepStrictEqual(json, { hello: 'world' }) - t.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') + t.assert.strictEqual(statusCode, 200) + t.assert.deepStrictEqual(json, { hello: 'world' }) + t.assert.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') server.close() proxy.close() @@ -274,7 +273,7 @@ test('use proxy-agent to connect through proxy using path with params', async (t }) test('use proxy-agent to connect through proxy using path with params with tunneling enabled', async (t) => { - t = tspl(t, { plan: 6 }) + t.plan(6) const server = await buildServer() const proxy = await buildProxy() @@ -284,11 +283,11 @@ test('use proxy-agent to connect through proxy using path with params with tunne const parsedOrigin = new URL(serverUrl) proxy.on('connect', () => { - t.ok(true, 'should call proxy') + t.assert.ok(true, 'should call proxy') }) server.on('request', (req, res) => { - t.strictEqual(req.url, '/hello?foo=bar') - t.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') + t.assert.strictEqual(req.url, '/hello?foo=bar') + t.assert.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') res.setHeader('content-type', 'application/json') res.end(JSON.stringify({ hello: 'world' })) }) @@ -300,9 +299,9 @@ test('use proxy-agent to connect through proxy using path with params with tunne } = await request(serverUrl + '/hello?foo=bar', { dispatcher: proxyAgent }) const json = await body.json() - t.strictEqual(statusCode, 200) - t.deepStrictEqual(json, { hello: 'world' }) - t.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') + t.assert.strictEqual(statusCode, 200) + t.assert.deepStrictEqual(json, { hello: 'world' }) + t.assert.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') server.close() proxy.close() @@ -310,7 +309,7 @@ test('use proxy-agent to connect through proxy using path with params with tunne }) test('use proxy-agent to connect through proxy with basic auth in URL', async (t) => { - t = tspl(t, { plan: 6 }) + t.plan(6) const server = await buildServer() const proxy = await buildProxy() @@ -320,16 +319,16 @@ test('use proxy-agent to connect through proxy with basic auth in URL', async (t const parsedOrigin = new URL(serverUrl) proxy.authenticate = function (req, fn) { - t.ok(true, 'authentication should be called') + t.assert.ok(true, 'authentication should be called') return req.headers['proxy-authorization'] === `Basic ${Buffer.from('user:pass').toString('base64')}` } proxy.on('connect', () => { - t.fail('proxy tunnel should not be established') + t.assert.fail('proxy tunnel should not be established') }) server.on('request', (req, res) => { - t.strictEqual(req.url, '/hello?foo=bar') - t.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') + t.assert.strictEqual(req.url, '/hello?foo=bar') + t.assert.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') res.setHeader('content-type', 'application/json') res.end(JSON.stringify({ hello: 'world' })) }) @@ -341,9 +340,9 @@ test('use proxy-agent to connect through proxy with basic auth in URL', async (t } = await request(serverUrl + '/hello?foo=bar', { dispatcher: proxyAgent }) const json = await body.json() - t.strictEqual(statusCode, 200) - t.deepStrictEqual(json, { hello: 'world' }) - t.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') + t.assert.strictEqual(statusCode, 200) + t.assert.deepStrictEqual(json, { hello: 'world' }) + t.assert.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') server.close() proxy.close() @@ -351,7 +350,7 @@ test('use proxy-agent to connect through proxy with basic auth in URL', async (t }) test('use proxy-agent to connect through proxy with basic auth in URL with tunneling enabled', async (t) => { - t = tspl(t, { plan: 7 }) + t.plan(7) const server = await buildServer() const proxy = await buildProxy() @@ -361,16 +360,16 @@ test('use proxy-agent to connect through proxy with basic auth in URL with tunne const parsedOrigin = new URL(serverUrl) proxy.authenticate = function (req, fn) { - t.ok(true, 'authentication should be called') + t.assert.ok(true, 'authentication should be called') return req.headers['proxy-authorization'] === `Basic ${Buffer.from('user:pass').toString('base64')}` } proxy.on('connect', () => { - t.ok(true, 'proxy should be called') + t.assert.ok(true, 'proxy should be called') }) server.on('request', (req, res) => { - t.strictEqual(req.url, '/hello?foo=bar') - t.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') + t.assert.strictEqual(req.url, '/hello?foo=bar') + t.assert.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') res.setHeader('content-type', 'application/json') res.end(JSON.stringify({ hello: 'world' })) }) @@ -382,9 +381,9 @@ test('use proxy-agent to connect through proxy with basic auth in URL with tunne } = await request(serverUrl + '/hello?foo=bar', { dispatcher: proxyAgent }) const json = await body.json() - t.strictEqual(statusCode, 200) - t.deepStrictEqual(json, { hello: 'world' }) - t.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') + t.assert.strictEqual(statusCode, 200) + t.assert.deepStrictEqual(json, { hello: 'world' }) + t.assert.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') server.close() proxy.close() @@ -392,7 +391,7 @@ test('use proxy-agent to connect through proxy with basic auth in URL with tunne }) test('use proxy-agent with auth', async (t) => { - t = tspl(t, { plan: 6 }) + t.plan(6) const server = await buildServer() const proxy = await buildProxy() @@ -406,16 +405,16 @@ test('use proxy-agent with auth', async (t) => { const parsedOrigin = new URL(serverUrl) proxy.authenticate = function (req) { - t.ok(true, 'authentication should be called') + t.assert.ok(true, 'authentication should be called') return req.headers['proxy-authorization'] === `Basic ${Buffer.from('user:pass').toString('base64')}` } proxy.on('connect', () => { - t.fail('proxy tunnel should not be established') + t.assert.fail('proxy tunnel should not be established') }) server.on('request', (req, res) => { - t.strictEqual(req.url, '/hello?foo=bar') - t.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') + t.assert.strictEqual(req.url, '/hello?foo=bar') + t.assert.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') res.setHeader('content-type', 'application/json') res.end(JSON.stringify({ hello: 'world' })) }) @@ -427,9 +426,9 @@ test('use proxy-agent with auth', async (t) => { } = await request(serverUrl + '/hello?foo=bar', { dispatcher: proxyAgent }) const json = await body.json() - t.strictEqual(statusCode, 200) - t.deepStrictEqual(json, { hello: 'world' }) - t.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') + t.assert.strictEqual(statusCode, 200) + t.assert.deepStrictEqual(json, { hello: 'world' }) + t.assert.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') server.close() proxy.close() @@ -437,7 +436,7 @@ test('use proxy-agent with auth', async (t) => { }) test('use proxy-agent with auth with tunneling enabled', async (t) => { - t = tspl(t, { plan: 7 }) + t.plan(7) const server = await buildServer() const proxy = await buildProxy() @@ -451,16 +450,16 @@ test('use proxy-agent with auth with tunneling enabled', async (t) => { const parsedOrigin = new URL(serverUrl) proxy.authenticate = function (req) { - t.ok(true, 'authentication should be called') + t.assert.ok(true, 'authentication should be called') return req.headers['proxy-authorization'] === `Basic ${Buffer.from('user:pass').toString('base64')}` } proxy.on('connect', () => { - t.ok(true, 'proxy should be called') + t.assert.ok(true, 'proxy should be called') }) server.on('request', (req, res) => { - t.strictEqual(req.url, '/hello?foo=bar') - t.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') + t.assert.strictEqual(req.url, '/hello?foo=bar') + t.assert.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') res.setHeader('content-type', 'application/json') res.end(JSON.stringify({ hello: 'world' })) }) @@ -472,9 +471,9 @@ test('use proxy-agent with auth with tunneling enabled', async (t) => { } = await request(serverUrl + '/hello?foo=bar', { dispatcher: proxyAgent }) const json = await body.json() - t.strictEqual(statusCode, 200) - t.deepStrictEqual(json, { hello: 'world' }) - t.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') + t.assert.strictEqual(statusCode, 200) + t.assert.deepStrictEqual(json, { hello: 'world' }) + t.assert.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') server.close() proxy.close() @@ -482,7 +481,7 @@ test('use proxy-agent with auth with tunneling enabled', async (t) => { }) test('use proxy-agent with token', async (t) => { - t = tspl(t, { plan: 6 }) + t.plan(6) const server = await buildServer() const proxy = await buildProxy() @@ -496,16 +495,16 @@ test('use proxy-agent with token', async (t) => { const parsedOrigin = new URL(serverUrl) proxy.authenticate = function (req) { - t.ok(true, 'authentication should be called') + t.assert.ok(true, 'authentication should be called') return req.headers['proxy-authorization'] === `Bearer ${Buffer.from('user:pass').toString('base64')}` } proxy.on('connect', () => { - t.fail('proxy tunnel should not be established') + t.assert.fail('proxy tunnel should not be established') }) server.on('request', (req, res) => { - t.strictEqual(req.url, '/hello?foo=bar') - t.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') + t.assert.strictEqual(req.url, '/hello?foo=bar') + t.assert.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') res.setHeader('content-type', 'application/json') res.end(JSON.stringify({ hello: 'world' })) }) @@ -517,9 +516,9 @@ test('use proxy-agent with token', async (t) => { } = await request(serverUrl + '/hello?foo=bar', { dispatcher: proxyAgent }) const json = await body.json() - t.strictEqual(statusCode, 200) - t.deepStrictEqual(json, { hello: 'world' }) - t.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') + t.assert.strictEqual(statusCode, 200) + t.assert.deepStrictEqual(json, { hello: 'world' }) + t.assert.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') server.close() proxy.close() @@ -527,7 +526,7 @@ test('use proxy-agent with token', async (t) => { }) test('use proxy-agent with token with tunneling enabled', async (t) => { - t = tspl(t, { plan: 7 }) + t.plan(7) const server = await buildServer() const proxy = await buildProxy() @@ -541,16 +540,16 @@ test('use proxy-agent with token with tunneling enabled', async (t) => { const parsedOrigin = new URL(serverUrl) proxy.authenticate = function (req) { - t.ok(true, 'authentication should be called') + t.assert.ok(true, 'authentication should be called') return req.headers['proxy-authorization'] === `Bearer ${Buffer.from('user:pass').toString('base64')}` } proxy.on('connect', () => { - t.ok(true, 'proxy should be called') + t.assert.ok(true, 'proxy should be called') }) server.on('request', (req, res) => { - t.strictEqual(req.url, '/hello?foo=bar') - t.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') + t.assert.strictEqual(req.url, '/hello?foo=bar') + t.assert.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') res.setHeader('content-type', 'application/json') res.end(JSON.stringify({ hello: 'world' })) }) @@ -562,9 +561,9 @@ test('use proxy-agent with token with tunneling enabled', async (t) => { } = await request(serverUrl + '/hello?foo=bar', { dispatcher: proxyAgent }) const json = await body.json() - t.strictEqual(statusCode, 200) - t.deepStrictEqual(json, { hello: 'world' }) - t.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') + t.assert.strictEqual(statusCode, 200) + t.assert.deepStrictEqual(json, { hello: 'world' }) + t.assert.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') server.close() proxy.close() @@ -572,7 +571,7 @@ test('use proxy-agent with token with tunneling enabled', async (t) => { }) test('use proxy-agent with custom headers', async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const server = await buildServer() const proxy = await buildProxy() @@ -587,11 +586,11 @@ test('use proxy-agent with custom headers', async (t) => { }) proxy.on('connect', (req) => { - t.fail('proxy tunnel should not be established') + t.assert.fail('proxy tunnel should not be established') }) server.on('request', (req, res) => { - t.strictEqual(req.headers['user-agent'], 'BarBaz/1.0.0') + t.assert.strictEqual(req.headers['user-agent'], 'BarBaz/1.0.0') res.end() }) @@ -606,7 +605,7 @@ test('use proxy-agent with custom headers', async (t) => { }) test('use proxy-agent with custom headers with tunneling enabled', async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const server = await buildServer() const proxy = await buildProxy() @@ -621,11 +620,11 @@ test('use proxy-agent with custom headers with tunneling enabled', async (t) => }) proxy.on('connect', (req) => { - t.strictEqual(req.headers['user-agent'], 'Foobar/1.0.0') + t.assert.strictEqual(req.headers['user-agent'], 'Foobar/1.0.0') }) server.on('request', (req, res) => { - t.strictEqual(req.headers['user-agent'], 'BarBaz/1.0.0') + t.assert.strictEqual(req.headers['user-agent'], 'BarBaz/1.0.0') res.end() }) @@ -640,7 +639,7 @@ test('use proxy-agent with custom headers with tunneling enabled', async (t) => }) test('sending proxy-authorization in request headers should throw', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await buildServer() const proxy = await buildProxy() @@ -652,7 +651,7 @@ test('sending proxy-authorization in request headers should throw', async (t) => res.end(JSON.stringify({ hello: 'world' })) }) - await t.rejects( + await t.assert.rejects( request( serverUrl + '/hello?foo=bar', { @@ -665,7 +664,7 @@ test('sending proxy-authorization in request headers should throw', async (t) => 'Proxy-Authorization should be sent in ProxyAgent' ) - await t.rejects( + await t.assert.rejects( request( serverUrl + '/hello?foo=bar', { @@ -678,7 +677,7 @@ test('sending proxy-authorization in request headers should throw', async (t) => 'Proxy-Authorization should be sent in ProxyAgent' ) - await t.rejects( + await t.assert.rejects( request( serverUrl + '/hello?foo=bar', { @@ -697,7 +696,7 @@ test('sending proxy-authorization in request headers should throw', async (t) => }) test('use proxy-agent with setGlobalDispatcher', async (t) => { - t = tspl(t, { plan: 5 }) + t.plan(5) const defaultDispatcher = getGlobalDispatcher() const server = await buildServer() @@ -713,11 +712,11 @@ test('use proxy-agent with setGlobalDispatcher', async (t) => { proxy.on('connect', () => { // proxyTunnel must be set to true in order to tunnel into the endpoint for HTTP->HTTP proxy connections - t.fail(true, 'connect to proxy should unreachable by default for HTTP->HTTP proxy connections') + t.assert.fail(true, 'connect to proxy should unreachable by default for HTTP->HTTP proxy connections') }) server.on('request', (req, res) => { - t.strictEqual(req.url, '/hello?foo=bar') - t.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') + t.assert.strictEqual(req.url, '/hello?foo=bar') + t.assert.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') res.setHeader('content-type', 'application/json') res.end(JSON.stringify({ hello: 'world' })) }) @@ -729,9 +728,9 @@ test('use proxy-agent with setGlobalDispatcher', async (t) => { } = await request(serverUrl + '/hello?foo=bar') const json = await body.json() - t.strictEqual(statusCode, 200) - t.deepStrictEqual(json, { hello: 'world' }) - t.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') + t.assert.strictEqual(statusCode, 200) + t.assert.deepStrictEqual(json, { hello: 'world' }) + t.assert.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') server.close() proxy.close() @@ -739,7 +738,7 @@ test('use proxy-agent with setGlobalDispatcher', async (t) => { }) test('use proxy-agent with setGlobalDispatcher with tunneling enabled', async (t) => { - t = tspl(t, { plan: 6 }) + t.plan(6) const defaultDispatcher = getGlobalDispatcher() const server = await buildServer() @@ -754,11 +753,11 @@ test('use proxy-agent with setGlobalDispatcher with tunneling enabled', async (t after(() => setGlobalDispatcher(defaultDispatcher)) proxy.on('connect', () => { - t.ok(true, 'should call proxy') + t.assert.ok(true, 'should call proxy') }) server.on('request', (req, res) => { - t.strictEqual(req.url, '/hello?foo=bar') - t.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') + t.assert.strictEqual(req.url, '/hello?foo=bar') + t.assert.strictEqual(req.headers.host, parsedOrigin.host, 'should not use proxyUrl as host') res.setHeader('content-type', 'application/json') res.end(JSON.stringify({ hello: 'world' })) }) @@ -770,9 +769,9 @@ test('use proxy-agent with setGlobalDispatcher with tunneling enabled', async (t } = await request(serverUrl + '/hello?foo=bar') const json = await body.json() - t.strictEqual(statusCode, 200) - t.deepStrictEqual(json, { hello: 'world' }) - t.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') + t.assert.strictEqual(statusCode, 200) + t.assert.deepStrictEqual(json, { hello: 'world' }) + t.assert.strictEqual(headers.connection, 'keep-alive', 'should remain the connection open') server.close() proxy.close() @@ -780,7 +779,7 @@ test('use proxy-agent with setGlobalDispatcher with tunneling enabled', async (t }) test('ProxyAgent correctly sends headers when using fetch - #1355, #1623', async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const defaultDispatcher = getGlobalDispatcher() const server = await buildServer() @@ -807,7 +806,7 @@ test('ProxyAgent correctly sends headers when using fetch - #1355, #1623', async proxy.on('connect', (req, res) => { // proxyTunnel must be set to true in order to tunnel into the endpoint for HTTP->HTTP proxy connections - t.fail(true, 'connect to proxy should unreachable by default for HTTP->HTTP proxy connections') + t.assert.fail(true, 'connect to proxy should unreachable by default for HTTP->HTTP proxy connections') }) server.on('request', (req, res) => { @@ -815,7 +814,7 @@ test('ProxyAgent correctly sends headers when using fetch - #1355, #1623', async for (const header of ['via', 'x-forwarded-for']) { delete req.headers[header] } - t.deepStrictEqual(req.headers, expectedHeaders) + t.assert.deepStrictEqual(req.headers, expectedHeaders) res.end('goodbye') }) @@ -826,11 +825,10 @@ test('ProxyAgent correctly sends headers when using fetch - #1355, #1623', async server.close() proxy.close() proxyAgent.close() - t.end() }) test('ProxyAgent correctly sends headers when using fetch - #1355, #1623 (with proxy tunneling enabled)', async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const defaultDispatcher = getGlobalDispatcher() const server = await buildServer() @@ -862,11 +860,11 @@ test('ProxyAgent correctly sends headers when using fetch - #1355, #1623 (with p } proxy.on('connect', (req, res) => { - t.deepStrictEqual(req.headers, expectedProxyHeaders) + t.assert.deepStrictEqual(req.headers, expectedProxyHeaders) }) server.on('request', (req, res) => { - t.deepStrictEqual(req.headers, expectedHeaders) + t.assert.deepStrictEqual(req.headers, expectedHeaders) res.end('goodbye') }) @@ -877,11 +875,10 @@ test('ProxyAgent correctly sends headers when using fetch - #1355, #1623 (with p server.close() proxy.close() proxyAgent.close() - t.end() }) test('should throw when proxy does not return 200', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await buildServer() const proxy = await buildProxy() @@ -891,31 +888,30 @@ test('should throw when proxy does not return 200', async (t) => { proxy.on('connect', () => { // proxyTunnel must be set to true in order to tunnel into the endpoint for HTTP->HTTP proxy connections - t.fail(true, 'connect to proxy should unreachable by default for HTTP->HTTP proxy connections') + t.assert.fail(true, 'connect to proxy should unreachable by default for HTTP->HTTP proxy connections') }) proxy.authenticate = function (_req) { - t.ok(true, 'should call authenticate') + t.assert.ok(true, 'should call authenticate') return false } const proxyAgent = new ProxyAgent({ uri: proxyUrl, proxyTunnel: false }) try { await request(serverUrl, { dispatcher: proxyAgent }) - t.fail() + t.assert.fail() } catch (e) { - t.ok(true, 'pass') - t.ok(e) + t.assert.ok(true, 'pass') + t.assert.ok(e) } server.close() proxy.close() proxyAgent.close() - await t.completed }) test('should throw when proxy does not return 200 with tunneling enabled', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await buildServer() const proxy = await buildProxy() @@ -924,27 +920,26 @@ test('should throw when proxy does not return 200 with tunneling enabled', async const proxyUrl = `http://localhost:${proxy.address().port}` proxy.authenticate = function (_req) { - t.ok(true, 'should call authenticate') + t.assert.ok(true, 'should call authenticate') return false } const proxyAgent = new ProxyAgent({ uri: proxyUrl, proxyTunnel: true }) try { await request(serverUrl, { dispatcher: proxyAgent }) - t.fail() + t.assert.fail() } catch (e) { - t.ok(true, 'pass') - t.ok(e) + t.assert.ok(true, 'pass') + t.assert.ok(e) } server.close() proxy.close() proxyAgent.close() - await t.completed }) test('pass ProxyAgent proxy status code error when using fetch - #2161', async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const server = await buildServer() const proxy = await buildProxy() @@ -952,7 +947,7 @@ test('pass ProxyAgent proxy status code error when using fetch - #2161', async ( const proxyUrl = `http://localhost:${proxy.address().port}` proxy.authenticate = function (_req) { - t.ok(true, 'should call authenticate') + t.assert.ok(true, 'should call authenticate') return false } @@ -960,18 +955,16 @@ test('pass ProxyAgent proxy status code error when using fetch - #2161', async ( try { await fetch(serverUrl, { dispatcher: proxyAgent }) } catch (e) { - t.ok('cause' in e) + t.assert.ok('cause' in e) } server.close() proxy.close() proxyAgent.close() - - await t.completed }) test('Proxy via HTTP to HTTPS endpoint', async (t) => { - t = tspl(t, { plan: 4 }) + t.plan(4) const server = await buildSSLServer() const proxy = await buildProxy() @@ -989,29 +982,29 @@ test('Proxy via HTTP to HTTPS endpoint', async (t) => { }) server.on('request', function (req, res) { - t.ok(req.connection.encrypted) + t.assert.ok(req.connection.encrypted) res.end(JSON.stringify(req.headers)) }) server.on('secureConnection', () => { - t.ok(true, 'server should be connected secured') + t.assert.ok(true, 'server should be connected secured') }) proxy.on('secureConnection', () => { - t.fail('proxy over http should not call secureConnection') + t.assert.fail('proxy over http should not call secureConnection') }) proxy.on('connect', function () { - t.ok(true, 'proxy should be connected') + t.assert.ok(true, 'proxy should be connected') }) proxy.on('request', function () { - t.fail('proxy should never receive requests') + t.assert.fail('proxy should never receive requests') }) const data = await request(serverUrl, { dispatcher: proxyAgent }) const json = await data.body.json() - t.deepStrictEqual(json, { + t.assert.deepStrictEqual(json, { host: `localhost:${server.address().port}`, connection: 'keep-alive' }) @@ -1022,7 +1015,7 @@ test('Proxy via HTTP to HTTPS endpoint', async (t) => { }) test('Proxy via HTTPS to HTTPS endpoint', async (t) => { - t = tspl(t, { plan: 5 }) + t.plan(5) const server = await buildSSLServer() const proxy = await buildSSLProxy() @@ -1045,29 +1038,29 @@ test('Proxy via HTTPS to HTTPS endpoint', async (t) => { }) server.on('request', function (req, res) { - t.ok(req.connection.encrypted) + t.assert.ok(req.connection.encrypted) res.end(JSON.stringify(req.headers)) }) server.on('secureConnection', () => { - t.ok(true, 'server should be connected secured') + t.assert.ok(true, 'server should be connected secured') }) proxy.on('secureConnection', () => { - t.ok(true, 'proxy over http should call secureConnection') + t.assert.ok(true, 'proxy over http should call secureConnection') }) proxy.on('connect', function () { - t.ok(true, 'proxy should be connected') + t.assert.ok(true, 'proxy should be connected') }) proxy.on('request', function () { - t.fail('proxy should never receive requests') + t.assert.fail('proxy should never receive requests') }) const data = await request(serverUrl, { dispatcher: proxyAgent }) const json = await data.body.json() - t.deepStrictEqual(json, { + t.assert.deepStrictEqual(json, { host: `localhost:${server.address().port}`, connection: 'keep-alive' }) @@ -1078,7 +1071,7 @@ test('Proxy via HTTPS to HTTPS endpoint', async (t) => { }) test('Proxy via HTTPS to HTTP endpoint with tunneling enabled', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await buildServer() const proxy = await buildSSLProxy() @@ -1096,25 +1089,25 @@ test('Proxy via HTTPS to HTTP endpoint with tunneling enabled', async (t) => { }) server.on('request', function (req, res) { - t.ok(!req.connection.encrypted) + t.assert.ok(!req.connection.encrypted) res.end(JSON.stringify(req.headers)) }) server.on('secureConnection', () => { - t.fail('server is http') + t.assert.fail('server is http') }) proxy.on('secureConnection', () => { - t.ok(true, 'proxy over http should call secureConnection') + t.assert.ok(true, 'proxy over http should call secureConnection') }) proxy.on('request', function () { - t.fail('proxy should never receive requests') + t.assert.fail('proxy should never receive requests') }) const data = await request(serverUrl, { dispatcher: proxyAgent }) const json = await data.body.json() - t.deepStrictEqual(json, { + t.assert.deepStrictEqual(json, { host: `localhost:${server.address().port}`, connection: 'keep-alive' }) @@ -1125,7 +1118,7 @@ test('Proxy via HTTPS to HTTP endpoint with tunneling enabled', async (t) => { }) test('Proxy via HTTP to HTTP endpoint with tunneling enabled', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await buildServer() const proxy = await buildProxy() @@ -1134,29 +1127,29 @@ test('Proxy via HTTP to HTTP endpoint with tunneling enabled', async (t) => { const proxyAgent = new ProxyAgent({ uri: proxyUrl, proxyTunnel: true }) server.on('request', function (req, res) { - t.ok(!req.connection.encrypted) + t.assert.ok(!req.connection.encrypted) res.end(JSON.stringify(req.headers)) }) server.on('secureConnection', () => { - t.fail('server is http') + t.assert.fail('server is http') }) proxy.on('secureConnection', () => { - t.fail('proxy is http') + t.assert.fail('proxy is http') }) proxy.on('connect', () => { - t.ok(true, 'connect to proxy') + t.assert.ok(true, 'connect to proxy') }) proxy.on('request', function () { - t.fail('proxy should never receive requests') + t.assert.fail('proxy should never receive requests') }) const data = await request(serverUrl, { dispatcher: proxyAgent }) const json = await data.body.json() - t.deepStrictEqual(json, { + t.assert.deepStrictEqual(json, { host: `localhost:${server.address().port}`, connection: 'keep-alive' }) @@ -1167,7 +1160,7 @@ test('Proxy via HTTP to HTTP endpoint with tunneling enabled', async (t) => { }) test('Proxy via HTTP to HTTP endpoint with tunneling disabled', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await buildServer() const proxy = await buildProxy() @@ -1176,26 +1169,26 @@ test('Proxy via HTTP to HTTP endpoint with tunneling disabled', async (t) => { const proxyAgent = new ProxyAgent({ uri: proxyUrl, proxyTunnel: false }) server.on('request', function (req, res) { - t.ok(!req.connection.encrypted) + t.assert.ok(!req.connection.encrypted) const headers = { host: req.headers.host, connection: req.headers.connection } res.end(JSON.stringify(headers)) }) server.on('secureConnection', () => { - t.fail('server is http') + t.assert.fail('server is http') }) proxy.on('secureConnection', () => { - t.fail('proxy is http') + t.assert.fail('proxy is http') }) proxy.on('connect', () => { - t.fail(true, 'connect to proxy should unreachable if proxyTunnel is false') + t.assert.fail(true, 'connect to proxy should unreachable if proxyTunnel is false') }) proxy.on('request', function (req) { const bits = { method: req.method, url: req.url } - t.deepStrictEqual(bits, { + t.assert.deepStrictEqual(bits, { method: 'GET', url: `${serverUrl}/` }) @@ -1203,7 +1196,7 @@ test('Proxy via HTTP to HTTP endpoint with tunneling disabled', async (t) => { const data = await request(serverUrl, { dispatcher: proxyAgent }) const json = await data.body.json() - t.deepStrictEqual(json, { + t.assert.deepStrictEqual(json, { host: `localhost:${server.address().port}`, connection: 'keep-alive' }) @@ -1214,7 +1207,7 @@ test('Proxy via HTTP to HTTP endpoint with tunneling disabled', async (t) => { }) test('Proxy via HTTPS to HTTP fails on wrong SNI', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await buildServer() const proxy = await buildSSLProxy() @@ -1230,33 +1223,33 @@ test('Proxy via HTTPS to HTTP fails on wrong SNI', async (t) => { }) server.on('request', function (req, res) { - t.ok(!req.connection.encrypted) + t.assert.ok(!req.connection.encrypted) res.end(JSON.stringify(req.headers)) }) server.on('secureConnection', () => { - t.fail('server is http') + t.assert.fail('server is http') }) proxy.on('secureConnection', () => { - t.fail('proxy is http') + t.assert.fail('proxy is http') }) proxy.on('connect', () => { - t.ok(true, 'connect to proxy') + t.assert.ok(true, 'connect to proxy') }) proxy.on('request', function () { - t.fail('proxy should never receive requests') + t.assert.fail('proxy should never receive requests') }) try { await request(serverUrl, { dispatcher: proxyAgent }) throw new Error('should fail') } catch (e) { - t.ok(e instanceof SecureProxyConnectionError) - t.ok(e.cause instanceof Error) - t.ok(e.cause.code === 'ERR_TLS_CERT_ALTNAME_INVALID') + t.assert.ok(e instanceof SecureProxyConnectionError) + t.assert.ok(e.cause instanceof Error) + t.assert.ok(e.cause.code === 'ERR_TLS_CERT_ALTNAME_INVALID') } server.close() @@ -1265,7 +1258,7 @@ test('Proxy via HTTPS to HTTP fails on wrong SNI', async (t) => { }) test('ProxyAgent keeps customized host in request headers - #3019', async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const server = await buildServer() const proxy = await buildProxy() @@ -1275,11 +1268,11 @@ test('ProxyAgent keeps customized host in request headers - #3019', async (t) => const customHost = 'example.com' proxy.on('connect', (req) => { - t.strictEqual(req.headers.host, `localhost:${server.address().port}`) + t.assert.strictEqual(req.headers.host, `localhost:${server.address().port}`) }) server.on('request', (req, res) => { - t.strictEqual(req.headers.host, customHost) + t.assert.strictEqual(req.headers.host, customHost) res.end() }) @@ -1294,7 +1287,7 @@ test('ProxyAgent keeps customized host in request headers - #3019', async (t) => }) test('ProxyAgent handles multiple concurrent HTTP requests via HTTP proxy', async (t) => { - t = tspl(t, { plan: 20 }) + t.plan(20) // Start target HTTP server const server = createServer((req, res) => { setTimeout(() => { @@ -1319,16 +1312,16 @@ test('ProxyAgent handles multiple concurrent HTTP requests via HTTP proxy', asyn requests.push( request(`http://localhost:${targetPort}/test${i}`, { dispatcher: proxyAgent }) .then(async res => { - t.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.statusCode, 200) const json = await res.body.json() - t.deepStrictEqual(json, { url: `/test${i}` }) + t.assert.deepStrictEqual(json, { url: `/test${i}` }) }) ) } try { await Promise.all(requests) } catch (err) { - t.fail(err) + t.assert.fail(err) } server.close() proxy.close() diff --git a/test/proxy.js b/test/proxy.js index 86cae7bfc93..ec8c1b2906a 100644 --- a/test/proxy.js +++ b/test/proxy.js @@ -1,13 +1,12 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { test } = require('node:test') const { Client, Pool } = require('..') const { createServer } = require('node:http') const { createProxy } = require('proxy') test('connect through proxy', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await buildServer() const proxy = await buildProxy() @@ -16,7 +15,7 @@ test('connect through proxy', async (t) => { const proxyUrl = `http://localhost:${proxy.address().port}` server.on('request', (req, res) => { - t.strictEqual(req.url, '/hello?foo=bar') + t.assert.strictEqual(req.url, '/hello?foo=bar') res.setHeader('content-type', 'application/json') res.end(JSON.stringify({ hello: 'world' })) }) @@ -33,8 +32,8 @@ test('connect through proxy', async (t) => { for await (const chunk of response.body) { data += chunk } - t.strictEqual(response.statusCode, 200) - t.deepStrictEqual(JSON.parse(data), { hello: 'world' }) + t.assert.strictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(JSON.parse(data), { hello: 'world' }) server.close() proxy.close() @@ -42,7 +41,7 @@ test('connect through proxy', async (t) => { }) test('connect through proxy with auth', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await buildServer() const proxy = await buildProxy() @@ -55,7 +54,7 @@ test('connect through proxy with auth', async (t) => { } server.on('request', (req, res) => { - t.strictEqual(req.url, '/hello?foo=bar') + t.assert.strictEqual(req.url, '/hello?foo=bar') res.setHeader('content-type', 'application/json') res.end(JSON.stringify({ hello: 'world' })) }) @@ -75,8 +74,8 @@ test('connect through proxy with auth', async (t) => { for await (const chunk of response.body) { data += chunk } - t.strictEqual(response.statusCode, 200) - t.deepStrictEqual(JSON.parse(data), { hello: 'world' }) + t.assert.strictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(JSON.parse(data), { hello: 'world' }) server.close() proxy.close() @@ -84,7 +83,7 @@ test('connect through proxy with auth', async (t) => { }) test('connect through proxy with auth but invalid credentials', async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const server = await buildServer() const proxy = await buildProxy() @@ -97,7 +96,7 @@ test('connect through proxy with auth but invalid credentials', async (t) => { } server.on('request', (req, res) => { - t.fail('should not be called') + t.assert.fail('should not be called') }) const client = new Client(proxyUrl) @@ -110,7 +109,7 @@ test('connect through proxy with auth but invalid credentials', async (t) => { } }) - t.strictEqual(response.statusCode, 407) + t.assert.strictEqual(response.statusCode, 407) server.close() proxy.close() @@ -118,7 +117,7 @@ test('connect through proxy with auth but invalid credentials', async (t) => { }) test('connect through proxy (with pool)', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await buildServer() const proxy = await buildProxy() @@ -127,7 +126,7 @@ test('connect through proxy (with pool)', async (t) => { const proxyUrl = `http://localhost:${proxy.address().port}` server.on('request', (req, res) => { - t.strictEqual(req.url, '/hello?foo=bar') + t.assert.strictEqual(req.url, '/hello?foo=bar') res.setHeader('content-type', 'application/json') res.end(JSON.stringify({ hello: 'world' })) }) @@ -144,8 +143,8 @@ test('connect through proxy (with pool)', async (t) => { for await (const chunk of response.body) { data += chunk } - t.strictEqual(response.statusCode, 200) - t.deepStrictEqual(JSON.parse(data), { hello: 'world' }) + t.assert.strictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(JSON.parse(data), { hello: 'world' }) server.close() proxy.close() diff --git a/test/readable.js b/test/readable.js index e6a6ed0dccd..4af5818e6f8 100644 --- a/test/readable.js +++ b/test/readable.js @@ -1,12 +1,11 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { test, describe } = require('node:test') const { Readable } = require('../lib/api/readable') describe('Readable', () => { test('avoid body reordering', async function (t) { - t = tspl(t, { plan: 1 }) + t.plan(1) function resume () { } @@ -23,11 +22,11 @@ describe('Readable', () => { const text = await r.text() - t.strictEqual(text, 'helloworld') + t.assert.strictEqual(text, 'helloworld') }) test('destroy timing text', async function (t) { - t = tspl(t, { plan: 1 }) + t.plan(1) function resume () { } @@ -37,11 +36,11 @@ describe('Readable', () => { const r = new Readable({ resume, abort }) r.destroy(new Error('kaboom')) - await t.rejects(r.text(), new Error('kaboom')) + await t.assert.rejects(r.text(), new Error('kaboom')) }) test('destroy timing promise', async function (t) { - t = tspl(t, { plan: 1 }) + t.plan(1) function resume () { } @@ -54,14 +53,14 @@ describe('Readable', () => { }) await new Promise(resolve => { r.on('error', err => { - t.ok(err) + t.assert.ok(err) resolve(null) }) }) }) test('.arrayBuffer()', async function (t) { - t = tspl(t, { plan: 1 }) + t.plan(1) function resume () { } @@ -80,11 +79,11 @@ describe('Readable', () => { const expected = new ArrayBuffer(11) const view = new Uint8Array(expected) view.set(Buffer.from('hello world')) - t.deepStrictEqual(arrayBuffer, expected) + t.assert.deepStrictEqual(arrayBuffer, expected) }) test('.bytes()', async function (t) { - t = tspl(t, { plan: 1 }) + t.plan(1) function resume () { } @@ -101,11 +100,11 @@ describe('Readable', () => { const bytes = await r.bytes() - t.deepStrictEqual(bytes, new TextEncoder().encode('hello world')) + t.assert.deepStrictEqual(bytes, new TextEncoder().encode('hello world')) }) test('.json()', async function (t) { - t = tspl(t, { plan: 1 }) + t.plan(1) function resume () { } @@ -121,11 +120,11 @@ describe('Readable', () => { const obj = await r.json() - t.deepStrictEqual(obj, { hello: 'world' }) + t.assert.deepStrictEqual(obj, { hello: 'world' }) }) test('.text()', async function (t) { - t = tspl(t, { plan: 1 }) + t.plan(1) function resume () { } @@ -141,11 +140,11 @@ describe('Readable', () => { const text = await r.text() - t.strictEqual(text, 'hello world') + t.assert.strictEqual(text, 'hello world') }) test('ignore BOM', async function (t) { - t = tspl(t, { plan: 1 }) + t.plan(1) function resume () { } @@ -162,11 +161,11 @@ describe('Readable', () => { const text = await r.text() - t.strictEqual(text, 'hello world') + t.assert.strictEqual(text, 'hello world') }) test('.bodyUsed', async function (t) { - t = tspl(t, { plan: 3 }) + t.plan(3) function resume () { } @@ -180,12 +179,12 @@ describe('Readable', () => { r.push(null) }) - t.strictEqual(r.bodyUsed, false) + t.assert.strictEqual(r.bodyUsed, false) const text = await r.text() - t.strictEqual(r.bodyUsed, true) + t.assert.strictEqual(r.bodyUsed, true) - t.strictEqual(text, 'hello world') + t.assert.strictEqual(text, 'hello world') }) }) diff --git a/test/redirect-pipeline.js b/test/redirect-pipeline.js index 52e4545e0d6..e3b4e873db2 100644 --- a/test/redirect-pipeline.js +++ b/test/redirect-pipeline.js @@ -1,6 +1,5 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { test } = require('node:test') const { pipeline: undiciPipeline, Client, interceptors } = require('..') const { pipeline: streamPipelineCb } = require('node:stream') @@ -12,7 +11,7 @@ const streamPipeline = promisify(streamPipelineCb) const redirect = interceptors.redirect test('should not follow redirection by default if not using RedirectAgent', async t => { - t = tspl(t, { plan: 3 }) + t.plan(3) const body = [] const serverRoot = await startRedirectingServer() @@ -22,19 +21,19 @@ test('should not follow redirection by default if not using RedirectAgent', asyn undiciPipeline(`http://${serverRoot}/`, { dispatcher: new Client(`http://${serverRoot}/`).compose(redirect({ maxRedirections: null })) }, ({ statusCode, headers, body }) => { - t.strictEqual(statusCode, 302) - t.strictEqual(headers.location, `http://${serverRoot}/302/1`) + t.assert.strictEqual(statusCode, 302) + t.assert.strictEqual(headers.location, `http://${serverRoot}/302/1`) return body }), createWritable(body) ) - t.strictEqual(body.length, 0) + t.assert.strictEqual(body.length, 0) }) test('should not follow redirects when using RedirectAgent within pipeline', async t => { - t = tspl(t, { plan: 3 }) + t.plan(3) const body = [] const serverRoot = await startRedirectingServer() @@ -42,13 +41,13 @@ test('should not follow redirects when using RedirectAgent within pipeline', asy await streamPipeline( createReadable('REQUEST'), undiciPipeline(`http://${serverRoot}/`, { dispatcher: new Client(`http://${serverRoot}/`).compose(redirect({ maxRedirections: 1 })) }, ({ statusCode, headers, body }) => { - t.strictEqual(statusCode, 302) - t.strictEqual(headers.location, `http://${serverRoot}/302/1`) + t.assert.strictEqual(statusCode, 302) + t.assert.strictEqual(headers.location, `http://${serverRoot}/302/1`) return body }), createWritable(body) ) - t.strictEqual(body.length, 0) + t.assert.strictEqual(body.length, 0) }) diff --git a/test/redirect-request.js b/test/redirect-request.js index 38d73e68b90..41f75475d64 100644 --- a/test/redirect-request.js +++ b/test/redirect-request.js @@ -1,6 +1,5 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { test, after } = require('node:test') const undici = require('..') const { @@ -28,7 +27,7 @@ for (const factory of [ } test('should always have a history with the final URL even if no redirections were followed', async t => { - t = tspl(t, { plan: 4 }) + t.plan(4) const server = await startRedirectingServer() @@ -38,31 +37,27 @@ for (const factory of [ const body = await bodyStream.text() - t.strictEqual(statusCode, 200) - t.ok(!headers.location) - t.deepStrictEqual(history.map(x => x.toString()), [`http://${server}/200?key=value`]) - t.strictEqual(body, `GET /5 key=value :: host@${server} connection@keep-alive`) - - await t.completed + t.assert.strictEqual(statusCode, 200) + t.assert.ok(!headers.location) + t.assert.deepStrictEqual(history.map(x => x.toString()), [`http://${server}/200?key=value`]) + t.assert.strictEqual(body, `GET /5 key=value :: host@${server} connection@keep-alive`) }) test('should not follow redirection by default if not using RedirectAgent', async t => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await startRedirectingServer() const { statusCode, headers, body: bodyStream } = await request(t, server, undefined, `http://${server}`) const body = await bodyStream.text() - t.strictEqual(statusCode, 302) - t.strictEqual(headers.location, `http://${server}/302/1`) - t.strictEqual(body.length, 0) - - await t.completed + t.assert.strictEqual(statusCode, 302) + t.assert.strictEqual(headers.location, `http://${server}/302/1`) + t.assert.strictEqual(body.length, 0) }) test('should follow redirection after a HTTP 300', async t => { - t = tspl(t, { plan: 4 }) + t.plan(4) const server = await startRedirectingServer() @@ -72,9 +67,9 @@ for (const factory of [ const body = await bodyStream.text() - t.strictEqual(statusCode, 200) - t.ok(!headers.location) - t.deepStrictEqual(history.map(x => x.toString()), [ + t.assert.strictEqual(statusCode, 200) + t.assert.ok(!headers.location) + t.assert.deepStrictEqual(history.map(x => x.toString()), [ `http://${server}/300?key=value`, `http://${server}/300/1?key=value`, `http://${server}/300/2?key=value`, @@ -82,22 +77,20 @@ for (const factory of [ `http://${server}/300/4?key=value`, `http://${server}/300/5?key=value` ]) - t.strictEqual(body, `GET /5 key=value :: host@${server} connection@keep-alive`) - - await t.completed + t.assert.strictEqual(body, `GET /5 key=value :: host@${server} connection@keep-alive`) }) test('should follow redirection after a HTTP 300 default', async t => { - t = tspl(t, { plan: 4 }) + t.plan(4) const server = await startRedirectingServer() const { statusCode, headers, body: bodyStream, context: { history } } = await request(t, server, undefined, `http://${server}/300?key=value`, { maxRedirections: 10 }) const body = await bodyStream.text() - t.strictEqual(statusCode, 200) - t.ok(!headers.location) - t.deepStrictEqual(history.map(x => x.toString()), [ + t.assert.strictEqual(statusCode, 200) + t.assert.ok(!headers.location) + t.assert.deepStrictEqual(history.map(x => x.toString()), [ `http://${server}/300?key=value`, `http://${server}/300/1?key=value`, `http://${server}/300/2?key=value`, @@ -105,13 +98,11 @@ for (const factory of [ `http://${server}/300/4?key=value`, `http://${server}/300/5?key=value` ]) - t.strictEqual(body, `GET /5 key=value :: host@${server} connection@keep-alive`) - - await t.completed + t.assert.strictEqual(body, `GET /5 key=value :: host@${server} connection@keep-alive`) }) test('should follow redirection after a HTTP 301', async t => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await startRedirectingServer() @@ -123,13 +114,13 @@ for (const factory of [ const body = await bodyStream.text() - t.strictEqual(statusCode, 200) - t.ok(!headers.location) - t.strictEqual(body, `GET /5 :: host@${server} connection@keep-alive`) + t.assert.strictEqual(statusCode, 200) + t.assert.ok(!headers.location) + t.assert.strictEqual(body, `GET /5 :: host@${server} connection@keep-alive`) }) test('should follow redirection after a HTTP 302', async t => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await startRedirectingServer() const { statusCode, headers, body: bodyStream } = await request(t, server, undefined, `http://${server}/302`, { @@ -140,13 +131,13 @@ for (const factory of [ const body = await bodyStream.text() - t.strictEqual(statusCode, 200) - t.ok(!headers.location) - t.strictEqual(body, `PUT /5 :: host@${server} connection@keep-alive content-length@7 :: REQUEST`) + t.assert.strictEqual(statusCode, 200) + t.assert.ok(!headers.location) + t.assert.strictEqual(body, `PUT /5 :: host@${server} connection@keep-alive content-length@7 :: REQUEST`) }) test('should follow redirection after a HTTP 303 changing method to GET', async t => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await startRedirectingServer() @@ -158,15 +149,13 @@ for (const factory of [ const body = await bodyStream.text() - t.strictEqual(statusCode, 200) - t.ok(!headers.location) - t.strictEqual(body, `GET /5 :: host@${server} connection@keep-alive`) - - await t.completed + t.assert.strictEqual(statusCode, 200) + t.assert.ok(!headers.location) + t.assert.strictEqual(body, `GET /5 :: host@${server} connection@keep-alive`) }) test('should remove Host and request body related headers when following HTTP 303 (array)', async t => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await startRedirectingServer() @@ -193,15 +182,13 @@ for (const factory of [ const body = await bodyStream.text() - t.strictEqual(statusCode, 200) - t.ok(!headers.location) - t.strictEqual(body, `GET /5 :: host@${server} connection@keep-alive x-foo1@1 x-foo2@2 x-foo3@3 x-bar@4`) - - await t.completed + t.assert.strictEqual(statusCode, 200) + t.assert.ok(!headers.location) + t.assert.strictEqual(body, `GET /5 :: host@${server} connection@keep-alive x-foo1@1 x-foo2@2 x-foo3@3 x-bar@4`) }) test('should remove Host and request body related headers when following HTTP 303 (object)', async t => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await startRedirectingServer() @@ -221,15 +208,13 @@ for (const factory of [ const body = await bodyStream.text() - t.strictEqual(statusCode, 200) - t.ok(!headers.location) - t.strictEqual(body, `GET /5 :: host@${server} connection@keep-alive x-foo1@1 x-foo2@2 x-foo3@3 x-bar@4`) - - await t.completed + t.assert.strictEqual(statusCode, 200) + t.assert.ok(!headers.location) + t.assert.strictEqual(body, `GET /5 :: host@${server} connection@keep-alive x-foo1@1 x-foo2@2 x-foo3@3 x-bar@4`) }) test('should remove Host and request body related headers when following HTTP 303 (Global Headers)', async t => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await startRedirectingServer() @@ -250,15 +235,13 @@ for (const factory of [ const body = await bodyStream.text() - t.strictEqual(statusCode, 200) - t.ok(!headers.location) - t.strictEqual(body, `GET /5 :: host@${server} connection@keep-alive x-bar@4 x-foo1@1 x-foo2@2 x-foo3@3`) - - await t.completed + t.assert.strictEqual(statusCode, 200) + t.assert.ok(!headers.location) + t.assert.strictEqual(body, `GET /5 :: host@${server} connection@keep-alive x-bar@4 x-foo1@1 x-foo2@2 x-foo3@3`) }) test('should remove Host and request body related headers when following HTTP 303 (Undici Headers)', async t => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await startRedirectingServer() @@ -278,15 +261,13 @@ for (const factory of [ const body = await bodyStream.text() - t.strictEqual(statusCode, 200) - t.ok(!headers.location) - t.strictEqual(body, `GET /5 :: host@${server} connection@keep-alive x-bar@4 x-foo1@1 x-foo2@2 x-foo3@3`) - - await t.completed + t.assert.strictEqual(statusCode, 200) + t.assert.ok(!headers.location) + t.assert.strictEqual(body, `GET /5 :: host@${server} connection@keep-alive x-bar@4 x-foo1@1 x-foo2@2 x-foo3@3`) }) test('should remove Host and request body related headers when following HTTP 303 (Maps)', async t => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await startRedirectingServer() @@ -306,15 +287,13 @@ for (const factory of [ const body = await bodyStream.text() - t.strictEqual(statusCode, 200) - t.ok(!headers.location) - t.strictEqual(body, `GET /5 :: host@${server} connection@keep-alive x-foo1@1 x-foo2@2 x-foo3@3 x-bar@4`) - - await t.completed + t.assert.strictEqual(statusCode, 200) + t.assert.ok(!headers.location) + t.assert.strictEqual(body, `GET /5 :: host@${server} connection@keep-alive x-foo1@1 x-foo2@2 x-foo3@3 x-bar@4`) }) test('should follow redirection after a HTTP 307', async t => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await startRedirectingServer() @@ -325,15 +304,13 @@ for (const factory of [ const body = await bodyStream.text() - t.strictEqual(statusCode, 200) - t.ok(!headers.location) - t.strictEqual(body, `DELETE /5 :: host@${server} connection@keep-alive`) - - await t.completed + t.assert.strictEqual(statusCode, 200) + t.assert.ok(!headers.location) + t.assert.strictEqual(body, `DELETE /5 :: host@${server} connection@keep-alive`) }) test('should follow redirection after a HTTP 308', async t => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await startRedirectingServer() @@ -344,15 +321,13 @@ for (const factory of [ const body = await bodyStream.text() - t.strictEqual(statusCode, 200) - t.ok(!headers.location) - t.strictEqual(body, `OPTIONS /5 :: host@${server} connection@keep-alive`) - - await t.completed + t.assert.strictEqual(statusCode, 200) + t.assert.ok(!headers.location) + t.assert.strictEqual(body, `OPTIONS /5 :: host@${server} connection@keep-alive`) }) test('should ignore HTTP 3xx response bodies', async t => { - t = tspl(t, { plan: 4 }) + t.plan(4) const server = await startRedirectingWithBodyServer() @@ -362,16 +337,14 @@ for (const factory of [ const body = await bodyStream.text() - t.strictEqual(statusCode, 200) - t.ok(!headers.location) - t.deepStrictEqual(history.map(x => x.toString()), [`http://${server}/`, `http://${server}/end`]) - t.strictEqual(body, 'FINAL') - - await t.completed + t.assert.strictEqual(statusCode, 200) + t.assert.ok(!headers.location) + t.assert.deepStrictEqual(history.map(x => x.toString()), [`http://${server}/`, `http://${server}/end`]) + t.assert.strictEqual(body, 'FINAL') }) test('should ignore query after redirection', async t => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await startRedirectingWithQueryParams() @@ -380,15 +353,13 @@ for (const factory of [ query: { param1: 'first' } }) - t.strictEqual(statusCode, 200) - t.ok(!headers.location) - t.deepStrictEqual(history.map(x => x.toString()), [`http://${server}/`, `http://${server}/?param2=second`]) - - await t.completed + t.assert.strictEqual(statusCode, 200) + t.assert.ok(!headers.location) + t.assert.deepStrictEqual(history.map(x => x.toString()), [`http://${server}/`, `http://${server}/?param2=second`]) }) test('should follow a redirect chain up to the allowed number of times', async t => { - t = tspl(t, { plan: 4 }) + t.plan(4) const server = await startRedirectingServer() @@ -398,16 +369,14 @@ for (const factory of [ const body = await bodyStream.text() - t.strictEqual(statusCode, 300) - t.strictEqual(headers.location, `http://${server}/300/3`) - t.deepStrictEqual(history.map(x => x.toString()), [`http://${server}/300`, `http://${server}/300/1`, `http://${server}/300/2`]) - t.strictEqual(body.length, 0) - - await t.completed + t.assert.strictEqual(statusCode, 300) + t.assert.strictEqual(headers.location, `http://${server}/300/3`) + t.assert.deepStrictEqual(history.map(x => x.toString()), [`http://${server}/300`, `http://${server}/300/1`, `http://${server}/300/2`]) + t.assert.strictEqual(body.length, 0) }) test('should follow a redirect chain up to the allowed number of times for redirectionLimitReached', async t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const server = await startRedirectingServer() @@ -418,17 +387,15 @@ for (const factory of [ }) } catch (error) { if (error.message.startsWith('max redirects')) { - t.ok(true, 'Max redirects handled correctly') + t.assert.ok(true, 'Max redirects handled correctly') } else { - t.fail(`Unexpected error: ${error.message}`) + t.assert.fail(`Unexpected error: ${error.message}`) } } - - await t.completed }) test('when a Location response header is NOT present', async t => { - t = tspl(t, { plan: 6 * 3 }) + t.plan(6 * 3) const redirectCodes = [300, 301, 302, 303, 307, 308] const server = await startRedirectingWithoutLocationServer() @@ -440,15 +407,14 @@ for (const factory of [ const body = await bodyStream.text() - t.strictEqual(statusCode, code) - t.ok(!headers.location) - t.strictEqual(body.length, 0) + t.assert.strictEqual(statusCode, code) + t.assert.ok(!headers.location) + t.assert.strictEqual(body.length, 0) } - await t.completed }) test('should not allow invalid maxRedirections arguments', async t => { - t = tspl(t, { plan: 1 }) + t.plan(1) try { await request(t, 'localhost', undefined, 'http://localhost', { @@ -456,15 +422,14 @@ for (const factory of [ maxRedirections: 'INVALID' }) - t.fail('Did not throw') + t.assert.fail('Did not throw') } catch (err) { - t.strictEqual(err.message, 'maxRedirections must be a positive number') + t.assert.strictEqual(err.message, 'maxRedirections must be a positive number') } - await t.completed }) test('should not allow invalid maxRedirections arguments default', async t => { - t = tspl(t, { plan: 1 }) + t.plan(1) try { await request(t, 'localhost', undefined, 'http://localhost', { @@ -472,16 +437,14 @@ for (const factory of [ maxRedirections: 'INVALID' }) - t.fail('Did not throw') + t.assert.fail('Did not throw') } catch (err) { - t.strictEqual(err.message, 'maxRedirections must be a positive number') + t.assert.strictEqual(err.message, 'maxRedirections must be a positive number') } - - await t.completed }) test('should not follow redirects when using ReadableStream request bodies', async t => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await startRedirectingServer() @@ -493,15 +456,13 @@ for (const factory of [ const body = await bodyStream.text() - t.strictEqual(statusCode, 301) - t.strictEqual(headers.location, `http://${server}/301/2`) - t.strictEqual(body.length, 0) - - await t.completed + t.assert.strictEqual(statusCode, 301) + t.assert.strictEqual(headers.location, `http://${server}/301/2`) + t.assert.strictEqual(body.length, 0) }) test('should not follow redirects when using Readable request bodies', async t => { - t = tspl(t, { plan: 3 }) + t.plan(3) const server = await startRedirectingServer() @@ -513,14 +474,13 @@ for (const factory of [ const body = await bodyStream.text() - t.strictEqual(statusCode, 301) - t.strictEqual(headers.location, `http://${server}/301/1`) - t.strictEqual(body.length, 0) - await t.completed + t.assert.strictEqual(statusCode, 301) + t.assert.strictEqual(headers.location, `http://${server}/301/1`) + t.assert.strictEqual(body.length, 0) }) test('should follow redirects when using Readable request bodies for POST 301', async t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const server = await startRedirectingServer() @@ -532,13 +492,12 @@ for (const factory of [ await bodyStream.text() - t.strictEqual(statusCode, 200) - await t.completed + t.assert.strictEqual(statusCode, 200) }) } test('should follow redirections when going cross origin', async t => { - t = tspl(t, { plan: 4 }) + t.plan(4) const [server1, server2, server3] = await startRedirectingChainServers() @@ -549,9 +508,9 @@ test('should follow redirections when going cross origin', async t => { const body = await bodyStream.text() - t.strictEqual(statusCode, 200) - t.ok(!headers.location) - t.deepStrictEqual(history.map(x => x.toString()), [ + t.assert.strictEqual(statusCode, 200) + t.assert.ok(!headers.location) + t.assert.deepStrictEqual(history.map(x => x.toString()), [ `http://${server1}/`, `http://${server2}/`, `http://${server3}/`, @@ -559,13 +518,11 @@ test('should follow redirections when going cross origin', async t => { `http://${server3}/end`, `http://${server1}/end` ]) - t.strictEqual(body, 'GET') - - await t.completed + t.assert.strictEqual(body, 'GET') }) -test('should handle errors (callback)', async t => { - t = tspl(t, { plan: 1 }) +test('should handle errors (callback)', (t, done) => { + t.plan(1) undici.request( 'http://localhost:0', @@ -573,28 +530,25 @@ test('should handle errors (callback)', async t => { dispatcher: new undici.Agent({}).compose(redirect({ maxRedirections: 10 })) }, error => { - t.match(error.code, /EADDRNOTAVAIL|ECONNREFUSED/) + t.assert.match(error.code, /EADDRNOTAVAIL|ECONNREFUSED/) + done() } ) - - await t.completed }) test('should handle errors (promise)', async t => { - t = tspl(t, { plan: 1 }) + t.plan(1) try { await undici.request('http://localhost:0', { dispatcher: new undici.Agent({}).compose(redirect({ maxRedirections: 10 })) }) - t.fail('Did not throw') + t.assert.fail('Did not throw') } catch (error) { - t.match(error.code, /EADDRNOTAVAIL|ECONNREFUSED/) + t.assert.match(error.code, /EADDRNOTAVAIL|ECONNREFUSED/) } - - await t.completed }) test('removes authorization header on third party origin', async t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const [server1] = await startRedirectingWithAuthorization('secret') const { body: bodyStream } = await undici.request(`http://${server1}`, { @@ -606,13 +560,11 @@ test('removes authorization header on third party origin', async t => { const body = await bodyStream.text() - t.strictEqual(body, '') - - await t.completed + t.assert.strictEqual(body, '') }) test('removes cookie header on third party origin', async t => { - t = tspl(t, { plan: 1 }) + t.plan(1) const [server1] = await startRedirectingWithCookie('a=b') const { body: bodyStream } = await undici.request(`http://${server1}`, { dispatcher: new undici.Agent({}).compose(redirect({ maxRedirections: 10 })), @@ -623,7 +575,5 @@ test('removes cookie header on third party origin', async t => { const body = await bodyStream.text() - t.strictEqual(body, '') - - await t.completed + t.assert.strictEqual(body, '') }) diff --git a/test/snapshot-recorder.js b/test/snapshot-recorder.js index 55fa38c747e..efcd1f6da4f 100644 --- a/test/snapshot-recorder.js +++ b/test/snapshot-recorder.js @@ -1,7 +1,6 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') const { tmpdir } = require('node:os') const { join } = require('node:path') const { unlink } = require('node:fs/promises') @@ -28,16 +27,16 @@ test('SnapshotRecorder - basic recording and retrieval', (t) => { recorder.record(requestOpts, response) // Verify it was recorded - assert.strictEqual(recorder.size(), 1) + t.assert.strictEqual(recorder.size(), 1) // Retrieve the snapshot const snapshot = recorder.findSnapshot(requestOpts) - assert(snapshot) - assert.strictEqual(snapshot.request.method, 'GET') - assert.strictEqual(snapshot.request.url, 'https://api.example.com/users/123') - assert.strictEqual(snapshot.response.statusCode, 200) + t.assert.ok(snapshot) + t.assert.strictEqual(snapshot.request.method, 'GET') + t.assert.strictEqual(snapshot.request.url, 'https://api.example.com/users/123') + t.assert.strictEqual(snapshot.response.statusCode, 200) // Body is stored as base64 string - assert.strictEqual(snapshot.response.body, response.body.toString('base64')) + t.assert.strictEqual(snapshot.response.body, response.body.toString('base64')) }) test('SnapshotRecorder - request key formatting', (t) => { @@ -55,11 +54,11 @@ test('SnapshotRecorder - request key formatting', (t) => { const cachedSets = createHeaderFilters({}) const formatted = formatRequestKey(requestOpts, cachedSets) - assert.strictEqual(formatted.method, 'POST') - assert.strictEqual(formatted.url, 'https://api.example.com/search?q=test&limit=10') - assert.strictEqual(formatted.headers['content-type'], 'application/json') - assert.strictEqual(formatted.headers.authorization, 'Bearer token') - assert.strictEqual(formatted.body, '{"filter": "active"}') + t.assert.strictEqual(formatted.method, 'POST') + t.assert.strictEqual(formatted.url, 'https://api.example.com/search?q=test&limit=10') + t.assert.strictEqual(formatted.headers['content-type'], 'application/json') + t.assert.strictEqual(formatted.headers.authorization, 'Bearer token') + t.assert.strictEqual(formatted.body, '{"filter": "active"}') }) test('SnapshotRecorder - request hashing', (t) => { @@ -89,13 +88,13 @@ test('SnapshotRecorder - request hashing', (t) => { const hash3 = createRequestHash(request3) // Same requests should have same hash - assert.strictEqual(hash1, hash2) + t.assert.strictEqual(hash1, hash2) // Different requests should have different hashes - assert.notStrictEqual(hash1, hash3) + t.assert.notStrictEqual(hash1, hash3) // Hashes should be URL-safe base64 - assert(hash1.match(/^[A-Za-z0-9_-]+$/)) + t.assert.ok(hash1.match(/^[A-Za-z0-9_-]+$/)) }) test('SnapshotRecorder - header normalization', (t) => { @@ -122,9 +121,9 @@ test('SnapshotRecorder - header normalization', (t) => { const formatted2 = formatRequestKey(requestOpts2, cachedSets) // Headers should be normalized to lowercase - assert.deepStrictEqual(formatted1.headers, formatted2.headers) - assert.strictEqual(formatted1.headers['content-type'], 'application/json') - assert.strictEqual(formatted1.headers.authorization, 'Bearer token') + t.assert.deepStrictEqual(formatted1.headers, formatted2.headers) + t.assert.strictEqual(formatted1.headers['content-type'], 'application/json') + t.assert.strictEqual(formatted1.headers.authorization, 'Bearer token') }) test('SnapshotRecorder - file persistence', async (t) => { @@ -144,7 +143,7 @@ test('SnapshotRecorder - file persistence', async (t) => { { statusCode: 200, headers: {}, body: Buffer.from('post data'), trailers: {} } ) - assert.strictEqual(recorder.size(), 2) + t.assert.strictEqual(recorder.size(), 2) // Save to file await recorder.saveSnapshots() @@ -153,7 +152,7 @@ test('SnapshotRecorder - file persistence', async (t) => { const newRecorder = new SnapshotRecorder({ snapshotPath }) await newRecorder.loadSnapshots() - assert.strictEqual(newRecorder.size(), 2) + t.assert.strictEqual(newRecorder.size(), 2) // Verify snapshots were loaded correctly const userSnapshot = newRecorder.findSnapshot({ @@ -162,10 +161,10 @@ test('SnapshotRecorder - file persistence', async (t) => { method: 'GET' }) - assert(userSnapshot) - assert.strictEqual(userSnapshot.response.statusCode, 200) + t.assert.ok(userSnapshot) + t.assert.strictEqual(userSnapshot.response.statusCode, 200) // Body is now stored as base64 string - assert.strictEqual(userSnapshot.response.body, Buffer.from('user data').toString('base64')) + t.assert.strictEqual(userSnapshot.response.body, Buffer.from('user data').toString('base64')) }) test('SnapshotRecorder - loading non-existent file', async (t) => { @@ -174,7 +173,7 @@ test('SnapshotRecorder - loading non-existent file', async (t) => { // Should not throw, just create empty recorder await recorder.loadSnapshots() - assert.strictEqual(recorder.size(), 0) + t.assert.strictEqual(recorder.size(), 0) }) test('SnapshotRecorder - array header handling', (t) => { @@ -191,8 +190,8 @@ test('SnapshotRecorder - array header handling', (t) => { const formatted = formatRequestKey(requestOpts, cachedSets) // Array headers should be joined with comma - assert.strictEqual(formatted.headers.accept, 'application/json, text/plain') - assert.strictEqual(formatted.headers['x-custom'], 'single-value') + t.assert.strictEqual(formatted.headers.accept, 'application/json, text/plain') + t.assert.strictEqual(formatted.headers['x-custom'], 'single-value') }) test('SnapshotRecorder - query parameter handling', (t) => { @@ -213,7 +212,7 @@ test('SnapshotRecorder - query parameter handling', (t) => { const formatted2 = formatRequestKey(requestOpts2, cachedSets) // URLs with different query parameter order should be normalized - assert.strictEqual(formatted1.url, 'https://api.example.com/search?q=test&sort=date') + t.assert.strictEqual(formatted1.url, 'https://api.example.com/search?q=test&sort=date') // But they should still create different hashes if params are truly different const hash1 = createRequestHash(formatted1) @@ -221,7 +220,7 @@ test('SnapshotRecorder - query parameter handling', (t) => { // This tests that parameter order matters in our current implementation // We might want to normalize parameter order in the future - assert.notStrictEqual(hash1, hash2) + t.assert.notStrictEqual(hash1, hash2) }) test('SnapshotRecorder - clear functionality', async (t) => { @@ -238,18 +237,18 @@ test('SnapshotRecorder - clear functionality', async (t) => { { statusCode: 200, headers: {}, body: Buffer.from('data2'), trailers: {} } ) - assert.strictEqual(recorder.size(), 2) + t.assert.strictEqual(recorder.size(), 2) // Clear and verify recorder.clear() - assert.strictEqual(recorder.size(), 0) + t.assert.strictEqual(recorder.size(), 0) // Should not find any snapshots const snapshot = recorder.findSnapshot({ origin: 'https://api.example.com', path: '/test1' }) - assert.strictEqual(snapshot, undefined) + t.assert.strictEqual(snapshot, undefined) }) test('SnapshotRecorder - custom header matching', (t) => { @@ -265,7 +264,7 @@ test('SnapshotRecorder - custom header matching', (t) => { const matchSpecificCachedSets = createHeaderFilters(matchSpecificOptions) const matchSpecific = filterHeadersForMatching(headers, matchSpecificCachedSets, matchSpecificOptions) - assert.deepStrictEqual(matchSpecific, { + t.assert.deepStrictEqual(matchSpecific, { 'content-type': 'application/json', accept: 'application/json' }) @@ -275,7 +274,7 @@ test('SnapshotRecorder - custom header matching', (t) => { const ignoreCachedSets = createHeaderFilters(ignoreOptions) const ignoreAuth = filterHeadersForMatching(headers, ignoreCachedSets, ignoreOptions) - assert.deepStrictEqual(ignoreAuth, { + t.assert.deepStrictEqual(ignoreAuth, { 'content-type': 'application/json', accept: 'application/json' }) @@ -285,7 +284,7 @@ test('SnapshotRecorder - custom header matching', (t) => { const excludeCachedSets = createHeaderFilters(excludeOptions) const excludeSensitive = filterHeadersForMatching(headers, excludeCachedSets, excludeOptions) - assert.deepStrictEqual(excludeSensitive, { + t.assert.deepStrictEqual(excludeSensitive, { 'content-type': 'application/json', 'x-request-id': '123', accept: 'application/json' @@ -305,7 +304,7 @@ test('SnapshotRecorder - header filtering for storage', (t) => { exclude: new Set(['set-cookie', 'authorization']) }) - assert.deepStrictEqual(filtered, { + t.assert.deepStrictEqual(filtered, { 'content-type': 'application/json', 'cache-control': 'no-cache' }) @@ -323,7 +322,7 @@ test('SnapshotRecorder - case sensitivity in header filtering', (t) => { const caseInsensitiveCachedSets = createHeaderFilters(caseInsensitiveOptions) const caseInsensitive = filterHeadersForMatching(headers, caseInsensitiveCachedSets, caseInsensitiveOptions) - assert.deepStrictEqual(caseInsensitive, { + t.assert.deepStrictEqual(caseInsensitive, { 'content-type': 'application/json' }) @@ -333,7 +332,7 @@ test('SnapshotRecorder - case sensitivity in header filtering', (t) => { const caseSensitive = filterHeadersForMatching(headers, caseSensitiveCachedSets, caseSensitiveOptions) // Should keep all headers since case doesn't match - assert.deepStrictEqual(caseSensitive, { + t.assert.deepStrictEqual(caseSensitive, { 'Content-Type': 'application/json', AUTHORIZATION: 'Bearer token', 'X-Request-ID': '123' @@ -362,12 +361,12 @@ test('SnapshotRecorder - request formatting with match options', (t) => { const cachedSets = createHeaderFilters(matchOptions) const formatted = formatRequestKey(requestOpts, cachedSets, matchOptions) - assert.strictEqual(formatted.method, 'POST') - assert.strictEqual(formatted.url, 'https://api.example.com/search') // No query - assert.deepStrictEqual(formatted.headers, { + t.assert.strictEqual(formatted.method, 'POST') + t.assert.strictEqual(formatted.url, 'https://api.example.com/search') // No query + t.assert.deepStrictEqual(formatted.headers, { 'content-type': 'application/json' }) - assert.strictEqual(formatted.body, '') // No body + t.assert.strictEqual(formatted.body, '') // No body }) test('SnapshotRecorder - redirect responses are stored correctly', (t) => { @@ -399,26 +398,26 @@ test('SnapshotRecorder - redirect responses are stored correctly', (t) => { // Record the redirect response (this will be stored as it's a valid response) recorder.record(redirectRequestOpts, redirectResponse) - assert.strictEqual(recorder.size(), 1, 'Redirect response (302) should be stored') + t.assert.strictEqual(recorder.size(), 1, 'Redirect response (302) should be stored') // First snapshot should contain the redirect response let snapshot = recorder.findSnapshot(redirectRequestOpts) - assert(snapshot, 'Should find snapshot for redirect request') - assert.strictEqual(snapshot.request.url, 'https://api.example.com/redirect-start') - assert.strictEqual(snapshot.response.statusCode, 302, 'First stored response should be the 302 redirect') + t.assert.ok(snapshot, 'Should find snapshot for redirect request') + t.assert.strictEqual(snapshot.request.url, 'https://api.example.com/redirect-start') + t.assert.strictEqual(snapshot.response.statusCode, 302, 'First stored response should be the 302 redirect') // Record the final response (this will create a second response for the same request) recorder.record(redirectRequestOpts, finalResponse) - assert.strictEqual(recorder.size(), 1, 'Should still have one snapshot (same request)') + t.assert.strictEqual(recorder.size(), 1, 'Should still have one snapshot (same request)') // Retrieve the snapshot again - should now have multiple responses snapshot = recorder.findSnapshot(redirectRequestOpts) - assert(snapshot, 'Should find snapshot for redirect request') - assert.strictEqual(snapshot.request.url, 'https://api.example.com/redirect-start') + t.assert.ok(snapshot, 'Should find snapshot for redirect request') + t.assert.strictEqual(snapshot.request.url, 'https://api.example.com/redirect-start') // The recorder supports sequential responses, so it should have both - assert(Array.isArray(snapshot.responses), 'Should have responses array') - assert.strictEqual(snapshot.responses.length, 2, 'Should have two responses') - assert.strictEqual(snapshot.responses[0].statusCode, 302, 'First response should be redirect') - assert.strictEqual(snapshot.responses[1].statusCode, 200, 'Second response should be final') + t.assert.ok(Array.isArray(snapshot.responses), 'Should have responses array') + t.assert.strictEqual(snapshot.responses.length, 2, 'Should have two responses') + t.assert.strictEqual(snapshot.responses[0].statusCode, 302, 'First response should be redirect') + t.assert.strictEqual(snapshot.responses[1].statusCode, 200, 'Second response should be final') }) diff --git a/test/snapshot-redirect-interceptor.js b/test/snapshot-redirect-interceptor.js index ccf9d00cb83..75b8a92606c 100644 --- a/test/snapshot-redirect-interceptor.js +++ b/test/snapshot-redirect-interceptor.js @@ -1,7 +1,6 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') const { createServer } = require('node:http') const { promisify } = require('node:util') const { unlink } = require('node:fs/promises') @@ -47,10 +46,10 @@ test('SnapshotAgent - integration with redirect interceptor', async (t) => { const redirectBody = await redirectResponse.body.json() // Verify redirect worked - assert.strictEqual(redirectResponse.statusCode, 200) - assert.deepStrictEqual(redirectBody, { message: 'Final destination' }) - assert(redirectResponse.context && redirectResponse.context.history) - assert.strictEqual(redirectResponse.context.history.length, 2) + t.assert.strictEqual(redirectResponse.statusCode, 200) + t.assert.deepStrictEqual(redirectBody, { message: 'Final destination' }) + t.assert.ok(redirectResponse.context && redirectResponse.context.history) + t.assert.strictEqual(redirectResponse.context.history.length, 2) await redirectAgent.close() @@ -68,8 +67,8 @@ test('SnapshotAgent - integration with redirect interceptor', async (t) => { const recordingBody = await recordingResponse.body.json() // Verify that we got the final response (not the 302) - assert.strictEqual(recordingResponse.statusCode, 200) - assert.deepStrictEqual(recordingBody, { message: 'Final destination' }) + t.assert.strictEqual(recordingResponse.statusCode, 200) + t.assert.deepStrictEqual(recordingBody, { message: 'Final destination' }) // Note: context.history is not preserved in SnapshotAgent recording mode // since we capture the final response directly @@ -89,30 +88,30 @@ test('SnapshotAgent - integration with redirect interceptor', async (t) => { const playbackResponse = await request(`${origin}/redirect-start`) const playbackBody = await playbackResponse.body.json() - assert.strictEqual(playbackResponse.statusCode, 200) - assert.deepStrictEqual(playbackBody, { message: 'Final destination' }) + t.assert.strictEqual(playbackResponse.statusCode, 200) + t.assert.deepStrictEqual(playbackBody, { message: 'Final destination' }) // In playback mode, context is not preserved since we're replaying recorded responses // The important thing is that we get the correct final response content // Verify the snapshot recorded the redirect request with final response const playbackRecorder = playbackAgent.getRecorder() - assert.strictEqual(playbackRecorder.size(), 2, 'Should have two snapshots') + t.assert.strictEqual(playbackRecorder.size(), 2, 'Should have two snapshots') const snapshots = playbackRecorder.getSnapshots() { const snapshot = snapshots[0] - assert.strictEqual(snapshot.request.url, `${origin}/redirect-start`) - assert.strictEqual(snapshot.responses[0].statusCode, 302) - assert.strictEqual(Buffer.from(snapshot.responses[0].body, 'base64').toString(), 'Redirecting...') + t.assert.strictEqual(snapshot.request.url, `${origin}/redirect-start`) + t.assert.strictEqual(snapshot.responses[0].statusCode, 302) + t.assert.strictEqual(Buffer.from(snapshot.responses[0].body, 'base64').toString(), 'Redirecting...') } { const snapshot = snapshots[1] - assert.strictEqual(snapshot.request.url, `${origin}/redirect-target`) - assert.strictEqual(snapshot.responses[0].statusCode, 200) - assert.deepStrictEqual(JSON.parse(Buffer.from(snapshot.responses[0].body, 'base64')), { + t.assert.strictEqual(snapshot.request.url, `${origin}/redirect-target`) + t.assert.strictEqual(snapshot.responses[0].statusCode, 200) + t.assert.deepStrictEqual(JSON.parse(Buffer.from(snapshot.responses[0].body, 'base64')), { message: 'Final destination' }) } diff --git a/test/snapshot-testing.js b/test/snapshot-testing.js index c81620d38ea..a440a37f453 100644 --- a/test/snapshot-testing.js +++ b/test/snapshot-testing.js @@ -1,7 +1,6 @@ 'use strict' const { describe, it } = require('node:test') -const assert = require('node:assert') const { createServer } = require('node:http') const { promisify } = require('node:util') const { unlink, writeFile, readFile } = require('node:fs/promises') @@ -158,8 +157,8 @@ describe('SnapshotAgent - Basic Operations', () => { }) const body = await response.body.json() - assert.strictEqual(response.statusCode, 200, 'Response should have status 200') - assert.deepStrictEqual(body, { + t.assert.strictEqual(response.statusCode, 200, 'Response should have status 200') + t.assert.deepStrictEqual(body, { message: TEST_CONSTANTS.TEST_MESSAGE, timestamp: TEST_CONSTANTS.TEST_TIMESTAMP }, 'Response body should match expected data') @@ -169,13 +168,13 @@ describe('SnapshotAgent - Basic Operations', () => { // Verify snapshot was recorded const recorder = agent.getRecorder() - assert.strictEqual(recorder.size(), 1, 'Should have recorded exactly one snapshot') + t.assert.strictEqual(recorder.size(), 1, 'Should have recorded exactly one snapshot') const snapshots = recorder.getSnapshots() - assert.strictEqual(snapshots.length, 1, 'Snapshots array should contain one item') - assert.strictEqual(snapshots[0].request.method, 'GET', 'Recorded request method should be GET') - assert.strictEqual(snapshots[0].request.url, `${origin}/test`, 'Recorded request URL should match') - assert.strictEqual(snapshots[0].responses[0].statusCode, 200, 'Recorded response status should be 200') + t.assert.strictEqual(snapshots.length, 1, 'Snapshots array should contain one item') + t.assert.strictEqual(snapshots[0].request.method, 'GET', 'Recorded request method should be GET') + t.assert.strictEqual(snapshots[0].request.url, `${origin}/test`, 'Recorded request URL should match') + t.assert.strictEqual(snapshots[0].responses[0].statusCode, 200, 'Recorded response status should be 200') }) it('playback mode', async (t) => { @@ -216,8 +215,8 @@ describe('SnapshotAgent - Basic Operations', () => { const response = await request(`${origin}/api/test`) const body = await response.body.text() - assert.strictEqual(response.statusCode, 200, 'Playback response should have status 200') - assert.strictEqual(body, 'Recorded response', 'Playback should return recorded response') + t.assert.strictEqual(response.statusCode, 200, 'Playback response should have status 200') + t.assert.strictEqual(body, 'Recorded response', 'Playback should return recorded response') }) it('update mode', async (t) => { @@ -253,7 +252,7 @@ describe('SnapshotAgent - Basic Operations', () => { // First request - should be recorded as new const response1 = await request(`${origin}/existing`) const body1 = await response1.body.text() - assert.strictEqual(body1, 'Existing endpoint', 'First request should get live response') + t.assert.strictEqual(body1, 'Existing endpoint', 'First request should get live response') // Save and reload to simulate existing snapshots await agent.saveSnapshots() @@ -261,16 +260,16 @@ describe('SnapshotAgent - Basic Operations', () => { // Second request to same endpoint - should use existing snapshot const response2 = await request(`${origin}/existing`) const body2 = await response2.body.text() - assert.strictEqual(body2, 'Existing endpoint', 'Second request should use cached response') + t.assert.strictEqual(body2, 'Existing endpoint', 'Second request should use cached response') // Request to new endpoint - should be recorded const response3 = await request(`${origin}/new`) const body3 = await response3.body.text() - assert.strictEqual(body3, 'New endpoint', 'New endpoint should get live response') + t.assert.strictEqual(body3, 'New endpoint', 'New endpoint should get live response') // Verify we have 2 different snapshots const recorder = agent.getRecorder() - assert.strictEqual(recorder.size(), 2, 'Should have exactly two snapshots recorded') + t.assert.strictEqual(recorder.size(), 2, 'Should have exactly two snapshots recorded') }) }) @@ -302,8 +301,8 @@ describe('SnapshotAgent - Request Handling', () => { }) const responseBody = await response.body.json() - assert.strictEqual(responseBody.received, requestBody, 'Server should receive the request body') - assert.strictEqual(responseBody.method, 'POST', 'Server should receive POST method') + t.assert.strictEqual(responseBody.received, requestBody, 'Server should receive the request body') + t.assert.strictEqual(responseBody.method, 'POST', 'Server should receive POST method') await recordingAgent.saveSnapshots() @@ -323,8 +322,8 @@ describe('SnapshotAgent - Request Handling', () => { }) const playbackBody = await playbackResponse.body.json() - assert.strictEqual(playbackBody.received, requestBody, 'Playback should return recorded request body') - assert.strictEqual(playbackBody.method, 'POST', 'Playback should return recorded method') + t.assert.strictEqual(playbackBody.received, requestBody, 'Playback should return recorded request body') + t.assert.strictEqual(playbackBody.method, 'POST', 'Playback should return recorded method') }) it('sequential response support', async (t) => { @@ -364,9 +363,9 @@ describe('SnapshotAgent - Request Handling', () => { // Verify recording worked correctly before switching to playback const recordingRecorder = recordingAgent.getRecorder() - assert.strictEqual(recordingRecorder.size(), 1, 'Should have recorded exactly one snapshot') + t.assert.strictEqual(recordingRecorder.size(), 1, 'Should have recorded exactly one snapshot') const recordedSnapshots = recordingRecorder.getSnapshots() - assert.strictEqual(recordedSnapshots[0].responses.length, 3, 'Should have recorded three responses') + t.assert.strictEqual(recordedSnapshots[0].responses.length, 3, 'Should have recorded three responses') // Close recording agent cleanly before starting playback await recordingAgent.close() @@ -388,29 +387,29 @@ describe('SnapshotAgent - Request Handling', () => { // Verify we have the expected snapshots before proceeding const recorder = playbackAgent.getRecorder() - assert.strictEqual(recorder.size(), 1, 'Should have exactly one snapshot loaded') + t.assert.strictEqual(recorder.size(), 1, 'Should have exactly one snapshot loaded') const snapshots = recorder.getSnapshots() - assert.strictEqual(snapshots.length, 1, 'Should have exactly one snapshot') - assert.strictEqual(snapshots[0].responses.length, 3, 'Should have three sequential responses') + t.assert.strictEqual(snapshots.length, 1, 'Should have exactly one snapshot') + t.assert.strictEqual(snapshots[0].responses.length, 3, 'Should have three sequential responses') // Test sequential responses const response1 = await request(`${origin}/api/test`) const body1 = await response1.body.text() - assert.strictEqual(body1, 'First response', 'First call should return first response') + t.assert.strictEqual(body1, 'First response', 'First call should return first response') const response2 = await request(`${origin}/api/test`) const body2 = await response2.body.text() - assert.strictEqual(body2, 'Second response', 'Second call should return second response') + t.assert.strictEqual(body2, 'Second response', 'Second call should return second response') const response3 = await request(`${origin}/api/test`) const body3 = await response3.body.text() - assert.strictEqual(body3, 'Third response', 'Third call should return third response') + t.assert.strictEqual(body3, 'Third response', 'Third call should return third response') // Fourth call should repeat the last response const response4 = await request(`${origin}/api/test`) const body4 = await response4.body.text() - assert.strictEqual(body4, 'Third response', 'Fourth call should repeat the last response') + t.assert.strictEqual(body4, 'Third response', 'Fourth call should repeat the last response') }) }) @@ -434,18 +433,18 @@ describe('SnapshotAgent - Error Handling', () => { await request('http://localhost:9999/nonexistent') } catch (error) { errorThrown = true - assert.strictEqual(error.name, 'UndiciError', 'Error should be UndiciError') - assert(error.message.includes(TEST_CONSTANTS.ERROR_MESSAGES.NO_SNAPSHOT_FOUND), + t.assert.strictEqual(error.name, 'UndiciError', 'Error should be UndiciError') + t.assert.ok(error.message.includes(TEST_CONSTANTS.ERROR_MESSAGES.NO_SNAPSHOT_FOUND), 'Error message should indicate no snapshot found') - assert.strictEqual(error.code, 'UND_ERR', 'Error code should be UND_ERR') + t.assert.strictEqual(error.code, 'UND_ERR', 'Error code should be UND_ERR') } - assert(errorThrown, 'Expected an error to be thrown for missing snapshot') + t.assert.ok(errorThrown, 'Expected an error to be thrown for missing snapshot') }) it('constructor options validation', async (t) => { // Test invalid mode - assert.throws(() => { + t.assert.throws(() => { return new SnapshotAgent({ mode: 'invalid' }) }, { name: 'InvalidArgumentError', @@ -453,7 +452,7 @@ describe('SnapshotAgent - Error Handling', () => { }, 'Should throw for invalid mode') // Test missing snapshotPath for playback mode - assert.throws(() => { + t.assert.throws(() => { return new SnapshotAgent({ mode: 'playback' }) }, { name: 'InvalidArgumentError', @@ -461,7 +460,7 @@ describe('SnapshotAgent - Error Handling', () => { }, 'Should throw for missing snapshotPath in playback mode') // Test missing snapshotPath for update mode - assert.throws(() => { + t.assert.throws(() => { return new SnapshotAgent({ mode: 'update' }) }, { name: 'InvalidArgumentError', @@ -469,18 +468,18 @@ describe('SnapshotAgent - Error Handling', () => { }, 'Should throw for missing snapshotPath in update mode') // Test valid configurations should not throw - await assert.doesNotReject(async () => { + await t.assert.doesNotReject(async () => { const agent1 = new SnapshotAgent({ mode: 'record' }) await agent1.close() }, 'Should not throw for valid record mode') - await assert.doesNotReject(async () => { + await t.assert.doesNotReject(async () => { const snapshotPath = createSnapshotPath('valid-playback') const agent2 = new SnapshotAgent({ mode: 'playback', snapshotPath }) await agent2.close() }, 'Should not throw for valid playback mode') - await assert.doesNotReject(async () => { + await t.assert.doesNotReject(async () => { const snapshotPath = createSnapshotPath('valid-update') const agent3 = new SnapshotAgent({ mode: 'update', snapshotPath }) await agent3.close() @@ -506,14 +505,14 @@ describe('SnapshotAgent - Edge Cases', () => { // Should load large files without issues await agent.loadSnapshots() const recorder = agent.getRecorder() - assert.strictEqual(recorder.size(), 100, 'Should load all 100 snapshots from large file') + t.assert.strictEqual(recorder.size(), 100, 'Should load all 100 snapshots from large file') setGlobalDispatcher(agent) // Should be able to find and use snapshots from large file const response = await request('http://localhost:3000/api/test-0') const body = await response.body.json() - assert.deepStrictEqual(body, { data: 'test-0' }, 'Should return correct data from large snapshot file') + t.assert.deepStrictEqual(body, { data: 'test-0' }, 'Should return correct data from large snapshot file') }) it('concurrent access scenarios', async (t) => { @@ -548,13 +547,13 @@ describe('SnapshotAgent - Edge Cases', () => { // Verify all responses were handled correctly for (let i = 0; i < responses.length; i++) { const body = await responses[i].body.json() - assert.deepStrictEqual(body, { path: `/api/test-${i}` }, + t.assert.deepStrictEqual(body, { path: `/api/test-${i}` }, `Concurrent request ${i} should return correct response`) } await agent.saveSnapshots() const recorder = agent.getRecorder() - assert.strictEqual(recorder.size(), 10, 'Should record all 10 concurrent requests') + t.assert.strictEqual(recorder.size(), 10, 'Should record all 10 concurrent requests') }) }) @@ -586,22 +585,22 @@ describe('SnapshotAgent - Advanced Features', () => { // Read and verify the snapshot file format const snapshotData = JSON.parse(await readFile(snapshotPath, 'utf8')) - assert(Array.isArray(snapshotData), 'Snapshot data should be an array') - assert.strictEqual(snapshotData.length, 1, 'Should contain exactly one snapshot') + t.assert.ok(Array.isArray(snapshotData), 'Snapshot data should be an array') + t.assert.strictEqual(snapshotData.length, 1, 'Should contain exactly one snapshot') const snapshot = snapshotData[0] - assert(typeof snapshot.hash === 'string', 'Snapshot should have string hash') - assert(typeof snapshot.snapshot === 'object', 'Snapshot should have snapshot object') + t.assert.ok(typeof snapshot.hash === 'string', 'Snapshot should have string hash') + t.assert.ok(typeof snapshot.snapshot === 'object', 'Snapshot should have snapshot object') const { request: req, responses, timestamp } = snapshot.snapshot - assert.strictEqual(req.method, 'GET', 'Request method should be GET') - assert.strictEqual(req.url, `${origin}/test-endpoint`, 'Request URL should match') - assert.strictEqual(responses[0].statusCode, 200, 'Response status should be 200') + t.assert.strictEqual(req.method, 'GET', 'Request method should be GET') + t.assert.strictEqual(req.url, `${origin}/test-endpoint`, 'Request URL should match') + t.assert.strictEqual(responses[0].statusCode, 200, 'Response status should be 200') // Headers should be normalized to lowercase - assert(responses[0].headers['x-custom-header'], 'Custom header should be present') - assert.strictEqual(responses[0].headers['x-custom-header'], 'test-value', 'Custom header value should match') - assert(typeof timestamp === 'string', 'Timestamp should be a string') + t.assert.ok(responses[0].headers['x-custom-header'], 'Custom header should be present') + t.assert.strictEqual(responses[0].headers['x-custom-header'], 'test-value', 'Custom header value should match') + t.assert.ok(typeof timestamp === 'string', 'Timestamp should be a string') }) it('maxSnapshots and LRU eviction', async (t) => { @@ -633,16 +632,16 @@ describe('SnapshotAgent - Advanced Features', () => { const recorder = agent.getRecorder() // Should only have 2 snapshots due to LRU eviction - assert.strictEqual(recorder.size(), TEST_CONSTANTS.MAX_SNAPSHOTS_FOR_LRU, + t.assert.strictEqual(recorder.size(), TEST_CONSTANTS.MAX_SNAPSHOTS_FOR_LRU, `Should only keep ${TEST_CONSTANTS.MAX_SNAPSHOTS_FOR_LRU} snapshots due to LRU eviction`) const snapshots = recorder.getSnapshots() const urls = snapshots.map(s => s.request.url) // First snapshot should be evicted, should have second and third - assert(urls.includes(`${origin}/second`), 'Should contain second request') - assert(urls.includes(`${origin}/third`), 'Should contain third request') - assert(!urls.includes(`${origin}/first`), 'Should not contain first request (evicted)') + t.assert.ok(urls.includes(`${origin}/second`), 'Should contain second request') + t.assert.ok(urls.includes(`${origin}/third`), 'Should contain third request') + t.assert.ok(!urls.includes(`${origin}/first`), 'Should not contain first request (evicted)') }) it('auto-flush functionality', async (t) => { @@ -680,9 +679,9 @@ describe('SnapshotAgent - Advanced Features', () => { const fileData = await readFile(snapshotPath, 'utf8') const snapshots = JSON.parse(fileData) - assert(Array.isArray(snapshots), 'Auto-flushed data should be an array') - assert.strictEqual(snapshots.length, 1, 'Should contain exactly one auto-flushed snapshot') - assert.strictEqual(snapshots[0].snapshot.request.url, `${origin}/autoflush-test`, + t.assert.ok(Array.isArray(snapshots), 'Auto-flushed data should be an array') + t.assert.strictEqual(snapshots.length, 1, 'Should contain exactly one auto-flushed snapshot') + t.assert.strictEqual(snapshots[0].snapshot.request.url, `${origin}/autoflush-test`, 'Auto-flushed snapshot should have correct URL') }) }) @@ -742,9 +741,9 @@ describe('SnapshotAgent - Header Management', () => { } }) - assert.strictEqual(response.statusCode, 200, 'Should match despite different auth token') + t.assert.strictEqual(response.statusCode, 200, 'Should match despite different auth token') const body = await response.body.text() - assert.strictEqual(body, '{"message": "test"}', 'Should return recorded response') + t.assert.strictEqual(body, '{"message": "test"}', 'Should return recorded response') }) it('ignore headers functionality', async (t) => { @@ -798,9 +797,9 @@ describe('SnapshotAgent - Header Management', () => { } }) - assert.strictEqual(response.statusCode, 200, 'Should match despite different ignored headers') + t.assert.strictEqual(response.statusCode, 200, 'Should match despite different ignored headers') const body = await response.body.text() - assert.strictEqual(body, 'ignore headers test', 'Should return recorded response') + t.assert.strictEqual(body, 'ignore headers test', 'Should return recorded response') }) it('exclude headers for security', async (t) => { @@ -835,13 +834,13 @@ describe('SnapshotAgent - Header Management', () => { const fileData = await readFile(snapshotPath, 'utf8') const snapshots = JSON.parse(fileData) - assert.strictEqual(snapshots.length, 1, 'Should contain exactly one snapshot') + t.assert.strictEqual(snapshots.length, 1, 'Should contain exactly one snapshot') const snapshot = snapshots[0].snapshot // Verify excluded headers are not in stored response - assert(!snapshot.responses[0].headers.authorization, 'Authorization header should be excluded from storage') - assert(!snapshot.responses[0].headers['set-cookie'], 'Set-Cookie header should be excluded from storage') - assert(snapshot.responses[0].headers['content-type'], 'Content-Type header should be preserved') + t.assert.ok(!snapshot.responses[0].headers.authorization, 'Authorization header should be excluded from storage') + t.assert.ok(!snapshot.responses[0].headers['set-cookie'], 'Set-Cookie header should be excluded from storage') + t.assert.ok(snapshot.responses[0].headers['content-type'], 'Content-Type header should be preserved') }) }) @@ -886,9 +885,9 @@ describe('SnapshotAgent - Request Matching', () => { // This should match the recorded request despite different query params const response = await request(`${origin}/api/data?timestamp=456&session=xyz`) - assert.strictEqual(response.statusCode, 200, 'Should match despite different query parameters') + t.assert.strictEqual(response.statusCode, 200, 'Should match despite different query parameters') const body = await response.body.text() - assert.strictEqual(body, 'Response for /api/data?timestamp=123&session=abc', + t.assert.strictEqual(body, 'Response for /api/data?timestamp=123&session=abc', 'Should return original recorded response with original query params') }) @@ -944,9 +943,9 @@ describe('SnapshotAgent - Request Matching', () => { headers: { 'content-type': 'text/plain' } }) - assert.strictEqual(response.statusCode, 200, 'Should match despite different request body') + t.assert.strictEqual(response.statusCode, 200, 'Should match despite different request body') const responseBody = await response.body.json() - assert.strictEqual(responseBody.received, 'original-data', + t.assert.strictEqual(responseBody.received, 'original-data', 'Should return recorded response with original body') }) }) @@ -982,8 +981,8 @@ describe('SnapshotAgent - Management Features', () => { path: '/api/test', method: 'GET' }) - assert(info1, 'Should find snapshot info') - assert.strictEqual(info1.callCount, 0, 'Call count should be 0 initially (only incremented during findSnapshot)') + t.assert.ok(info1, 'Should find snapshot info') + t.assert.strictEqual(info1.callCount, 0, 'Call count should be 0 initially (only incremented during findSnapshot)') // Reset call counts agent.resetCallCounts() @@ -993,8 +992,8 @@ describe('SnapshotAgent - Management Features', () => { path: '/api/test', method: 'GET' }) - assert(info2, 'Should still find snapshot info after reset') - assert.strictEqual(info2.callCount, 0, 'Call count should remain 0 after reset') + t.assert.ok(info2, 'Should still find snapshot info after reset') + t.assert.strictEqual(info2.callCount, 0, 'Call count should remain 0 after reset') }) it('snapshot management methods', async (t) => { @@ -1027,10 +1026,10 @@ describe('SnapshotAgent - Management Features', () => { path: '/api/users', method: 'GET' }) - assert(userInfo, 'Should find user snapshot info') - assert.strictEqual(userInfo.request.method, 'GET', 'User snapshot method should be GET') - assert.strictEqual(userInfo.request.url, `${origin}/api/users`, 'User snapshot URL should match') - assert.strictEqual(userInfo.responseCount, 1, 'User snapshot should have one response') + t.assert.ok(userInfo, 'Should find user snapshot info') + t.assert.strictEqual(userInfo.request.method, 'GET', 'User snapshot method should be GET') + t.assert.strictEqual(userInfo.request.url, `${origin}/api/users`, 'User snapshot URL should match') + t.assert.strictEqual(userInfo.responseCount, 1, 'User snapshot should have one response') // Test deleteSnapshot const deleted = agent.deleteSnapshot({ @@ -1038,7 +1037,7 @@ describe('SnapshotAgent - Management Features', () => { path: '/api/users', method: 'GET' }) - assert.strictEqual(deleted, true, 'Should successfully delete user snapshot') + t.assert.strictEqual(deleted, true, 'Should successfully delete user snapshot') // Verify deletion const deletedInfo = agent.getSnapshotInfo({ @@ -1046,7 +1045,7 @@ describe('SnapshotAgent - Management Features', () => { path: '/api/users', method: 'GET' }) - assert.strictEqual(deletedInfo, null, 'Deleted snapshot should not be found') + t.assert.strictEqual(deletedInfo, null, 'Deleted snapshot should not be found') // Post snapshot should still exist const postInfo = agent.getSnapshotInfo({ @@ -1054,7 +1053,7 @@ describe('SnapshotAgent - Management Features', () => { path: '/api/posts', method: 'GET' }) - assert(postInfo, 'Post snapshot should still exist after deleting user snapshot') + t.assert.ok(postInfo, 'Post snapshot should still exist after deleting user snapshot') // Test replaceSnapshots - create a snapshot with proper hash const { createRequestHash, formatRequestKey, createHeaderFilters } = require('../lib/mock/snapshot-recorder') @@ -1083,11 +1082,11 @@ describe('SnapshotAgent - Management Features', () => { // Should only have the mock snapshot now const recorder = agent.getRecorder() - assert.strictEqual(recorder.size(), 1, 'Should have only one snapshot after replacement') + t.assert.strictEqual(recorder.size(), 1, 'Should have only one snapshot after replacement') const mockInfo = agent.getSnapshotInfo(mockRequestOpts) - assert(mockInfo, 'Should find mock snapshot after replacement') - assert.strictEqual(mockInfo.request.url, `${origin}/api/mock`, 'Mock snapshot URL should match') + t.assert.ok(mockInfo, 'Should find mock snapshot after replacement') + t.assert.strictEqual(mockInfo.request.url, `${origin}/api/mock`, 'Mock snapshot URL should match') }) }) @@ -1121,10 +1120,10 @@ describe('SnapshotAgent - Filtering', () => { await request(`${origin}/api/filtered`) const recorder = agent.getRecorder() - assert.strictEqual(recorder.size(), 1, 'Should record only the allowed request') + t.assert.strictEqual(recorder.size(), 1, 'Should record only the allowed request') const snapshots = recorder.getSnapshots() - assert.strictEqual(snapshots[0].request.url, `${origin}/api/allowed`, + t.assert.strictEqual(snapshots[0].request.url, `${origin}/api/allowed`, 'Recorded snapshot should be the allowed request') }) @@ -1169,7 +1168,7 @@ describe('SnapshotAgent - Filtering', () => { // This should use cached response const cachedResponse = await request(`${origin}/api/cached`) const cachedBody = await cachedResponse.body.text() - assert.strictEqual(cachedBody, 'Live response for /api/cached', + t.assert.strictEqual(cachedBody, 'Live response for /api/cached', 'Should return cached response for allowed path') // This should fail because playback is filtered and no live server @@ -1180,10 +1179,10 @@ describe('SnapshotAgent - Filtering', () => { await request(`${origin}/api/live`) } catch (error) { errorThrown = true - assert.strictEqual(error.name, 'UndiciError', 'Should throw UndiciError for filtered request') + t.assert.strictEqual(error.name, 'UndiciError', 'Should throw UndiciError for filtered request') } - assert(errorThrown, 'Expected an error for filtered playback request') + t.assert.ok(errorThrown, 'Expected an error for filtered playback request') }) it('URL exclusion patterns (string)', async (t) => { @@ -1213,10 +1212,10 @@ describe('SnapshotAgent - Filtering', () => { await request(`${origin}/api/secret-endpoint`) const recorder = agent.getRecorder() - assert.strictEqual(recorder.size(), 1, 'Should record only non-excluded requests') + t.assert.strictEqual(recorder.size(), 1, 'Should record only non-excluded requests') const snapshots = recorder.getSnapshots() - assert.strictEqual(snapshots[0].request.url, `${origin}/api/public`, + t.assert.strictEqual(snapshots[0].request.url, `${origin}/api/public`, 'Should record only the public API request') }) @@ -1247,10 +1246,10 @@ describe('SnapshotAgent - Filtering', () => { await request(`${origin}/api/auth?token=secret`) const recorder = agent.getRecorder() - assert.strictEqual(recorder.size(), 1, 'Should record only requests not matching exclusion patterns') + t.assert.strictEqual(recorder.size(), 1, 'Should record only requests not matching exclusion patterns') const snapshots = recorder.getSnapshots() - assert.strictEqual(snapshots[0].request.url, `${origin}/api/data`, + t.assert.strictEqual(snapshots[0].request.url, `${origin}/api/data`, 'Should record only the non-excluded API request') }) @@ -1285,12 +1284,12 @@ describe('SnapshotAgent - Filtering', () => { await request(`${origin}/api/data`, { method: 'POST' }) // Should not record (POST method) const recorder = agent.getRecorder() - assert.strictEqual(recorder.size(), 1, 'Should record only requests passing all filters') + t.assert.strictEqual(recorder.size(), 1, 'Should record only requests passing all filters') const snapshots = recorder.getSnapshots() - assert.strictEqual(snapshots[0].request.url, `${origin}/api/users`, + t.assert.strictEqual(snapshots[0].request.url, `${origin}/api/users`, 'Should record only the allowed GET request') - assert.strictEqual(snapshots[0].request.method, 'GET', + t.assert.strictEqual(snapshots[0].request.method, 'GET', 'Recorded request should have GET method') }) }) @@ -1319,7 +1318,7 @@ describe('SnapshotAgent - Close Method', () => { // Verify snapshot is in memory but not yet saved to file const recorder = agent.getRecorder() - assert.strictEqual(recorder.size(), 1, 'Should have recorded one snapshot in memory') + t.assert.strictEqual(recorder.size(), 1, 'Should have recorded one snapshot in memory') // Check that file doesn't exist yet (since autoFlush is false) let fileExists = false @@ -1329,7 +1328,7 @@ describe('SnapshotAgent - Close Method', () => { } catch { // File doesn't exist, which is expected } - assert.strictEqual(fileExists, false, 'File should not exist before close()') + t.assert.strictEqual(fileExists, false, 'File should not exist before close()') // Close the agent - this should save the snapshots await agent.close() @@ -1340,13 +1339,13 @@ describe('SnapshotAgent - Close Method', () => { const fileContent = await readFile(snapshotPath, 'utf8') savedData = JSON.parse(fileContent) } catch (error) { - assert.fail(`Failed to read saved snapshot file: ${error.message}`) + t.assert.fail(`Failed to read saved snapshot file: ${error.message}`) } - assert(Array.isArray(savedData), 'Saved data should be an array') - assert.strictEqual(savedData.length, 1, 'Should have saved one snapshot') - assert.strictEqual(savedData[0].snapshot.request.method, 'GET', 'Saved snapshot should have correct method') - assert.strictEqual(savedData[0].snapshot.request.url, `${origin}/test`, 'Saved snapshot should have correct URL') + t.assert.ok(Array.isArray(savedData), 'Saved data should be an array') + t.assert.strictEqual(savedData.length, 1, 'Should have saved one snapshot') + t.assert.strictEqual(savedData[0].snapshot.request.method, 'GET', 'Saved snapshot should have correct method') + t.assert.strictEqual(savedData[0].snapshot.request.url, `${origin}/test`, 'Saved snapshot should have correct URL') }) it('close() works when no recordings exist', async (t) => { @@ -1359,7 +1358,7 @@ describe('SnapshotAgent - Close Method', () => { }) // Close agent immediately without making any requests or setting as dispatcher - await assert.doesNotReject(async () => { + await t.assert.doesNotReject(async () => { await agent.close() }, 'Should not throw when closing agent with no recordings') @@ -1371,7 +1370,7 @@ describe('SnapshotAgent - Close Method', () => { } catch { // File doesn't exist, which is expected } - assert.strictEqual(fileExists, false, 'No file should be created when no recordings exist') + t.assert.strictEqual(fileExists, false, 'No file should be created when no recordings exist') }) it('close() works when no snapshot path is configured', async (t) => { @@ -1392,7 +1391,7 @@ describe('SnapshotAgent - Close Method', () => { await request(`${origin}/test`) // Close should not throw even without snapshot path - await assert.doesNotReject(async () => { + await t.assert.doesNotReject(async () => { await agent.close() }, 'Should not throw when closing agent without snapshot path') }) @@ -1418,7 +1417,7 @@ describe('SnapshotAgent - Close Method', () => { } ) - assert.strictEqual(recorder.size(), 1, 'Should have one recorded snapshot') + t.assert.strictEqual(recorder.size(), 1, 'Should have one recorded snapshot') // Close the recorder await recorder.close() @@ -1429,11 +1428,11 @@ describe('SnapshotAgent - Close Method', () => { const fileContent = await readFile(snapshotPath, 'utf8') savedData = JSON.parse(fileContent) } catch (error) { - assert.fail(`Failed to read saved snapshot file: ${error.message}`) + t.assert.fail(`Failed to read saved snapshot file: ${error.message}`) } - assert(Array.isArray(savedData), 'Saved data should be an array') - assert.strictEqual(savedData.length, 1, 'Should have saved one snapshot') - assert.strictEqual(savedData[0].snapshot.request.method, 'GET', 'Should have correct method') + t.assert.ok(Array.isArray(savedData), 'Saved data should be an array') + t.assert.strictEqual(savedData.length, 1, 'Should have saved one snapshot') + t.assert.strictEqual(savedData[0].snapshot.request.method, 'GET', 'Should have correct method') }) }) diff --git a/test/timers.js b/test/timers.js index 9d8cd596e90..014740049ef 100644 --- a/test/timers.js +++ b/test/timers.js @@ -1,6 +1,5 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { describe, test } = require('node:test') const FakeTimers = require('@sinonjs/fake-timers') @@ -23,93 +22,93 @@ function tick (duration) { describe('timers', () => { test('timers exports a clearTimeout', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) - t.ok(typeof timers.clearTimeout === 'function') + t.assert.ok(typeof timers.clearTimeout === 'function') }) test('timers exports a setTimeout', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) - t.ok(typeof timers.setTimeout === 'function') + t.assert.ok(typeof timers.setTimeout === 'function') }) test('setTimeout instantiates a native NodeJS.Timeout when delay is lower or equal 1e3 ms', (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) - t.strictEqual(timers.setTimeout(() => { }, 999)[timers.kFastTimer], undefined) - t.strictEqual(timers.setTimeout(() => { }, 1e3)[timers.kFastTimer], undefined) + t.assert.strictEqual(timers.setTimeout(() => { }, 999)[timers.kFastTimer], undefined) + t.assert.strictEqual(timers.setTimeout(() => { }, 1e3)[timers.kFastTimer], undefined) }) test('setTimeout instantiates a FastTimer when delay is bigger than 1e3 ms', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const timeout = timers.setTimeout(() => { }, 1001) - t.strictEqual(timeout[timers.kFastTimer], true) + t.assert.strictEqual(timeout[timers.kFastTimer], true) }) test('clearTimeout can clear a node native Timeout', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) - const nativeTimeoutId = setTimeout(() => { t.fail() }, 1) - t.ok(timers.clearTimeout(nativeTimeoutId) === undefined) + const nativeTimeoutId = setTimeout(() => { t.assert.fail() }, 1) + t.assert.ok(timers.clearTimeout(nativeTimeoutId) === undefined) tick(10) }) test('a FastTimer will get a _idleStart value after short time', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const timer = timers.setTimeout(() => { - t.fail('timer should not have fired') + t.assert.fail('timer should not have fired') }, 1e4) - t.strictEqual(timer[timers.kFastTimer], true) - t.strictEqual(timer._idleStart, -1) + t.assert.strictEqual(timer[timers.kFastTimer], true) + t.assert.strictEqual(timer._idleStart, -1) tick(1e3) - t.notStrictEqual(timer._idleStart, -1) + t.assert.notStrictEqual(timer._idleStart, -1) timers.clearTimeout(timer) }) test('a cleared FastTimer will reset the _idleStart value to -1', async (t) => { - t = tspl(t, { plan: 4 }) + t.plan(4) const timer = timers.setTimeout(() => { - t.fail('timer should not have fired') + t.assert.fail('timer should not have fired') }, 1e4) - t.strictEqual(timer[timers.kFastTimer], true) - t.strictEqual(timer._idleStart, -1) + t.assert.strictEqual(timer[timers.kFastTimer], true) + t.assert.strictEqual(timer._idleStart, -1) tick(750) - t.notStrictEqual(timer._idleStart, -1) + t.assert.notStrictEqual(timer._idleStart, -1) timers.clearTimeout(timer) - t.strictEqual(timer._idleStart, -1) + t.assert.strictEqual(timer._idleStart, -1) }) test('a FastTimer can be cleared', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const timer = timers.setTimeout(() => { - t.fail('timer should not have fired') + t.assert.fail('timer should not have fired') }, 1001) - t.strictEqual(timer[timers.kFastTimer], true) + t.assert.strictEqual(timer[timers.kFastTimer], true) timers.clearTimeout(timer) - t.strictEqual(timer._idleStart, -1) + t.assert.strictEqual(timer._idleStart, -1) tick(750) - t.strictEqual(timer._idleStart, -1) + t.assert.strictEqual(timer._idleStart, -1) }) test('a cleared FastTimer can be refreshed', async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const timer = timers.setFastTimeout(() => { - t.ok('pass') + t.assert.ok('pass') }, 1001) - t.strictEqual(timer[timers.kFastTimer], true) + t.assert.strictEqual(timer[timers.kFastTimer], true) timers.clearTimeout(timer) timer.refresh() tick(2000) @@ -123,7 +122,7 @@ describe('timers', () => { } test('refresh correctly with timeout < TICK_MS', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const start = performance.now() @@ -131,22 +130,21 @@ describe('timers', () => { // 80 ms timer was refreshed after 120 ms; total target is 200 ms const delta = getDelta(start, 200) - t.ok(delta >= -1, 'refreshed timer fired early') - t.ok(delta < ACCEPTABLE_DELTA, 'refreshed timer fired late') + t.assert.ok(delta >= -1, 'refreshed timer fired early') + t.assert.ok(delta < ACCEPTABLE_DELTA, 'refreshed timer fired late') }, 80) setTimeout(() => timeout.refresh(), 40) setTimeout(() => timeout.refresh(), 80) setTimeout(() => timeout.refresh(), 120) - setTimeout(() => t.ok(true), 260) + setTimeout(() => t.assert.ok(true), 260) tick(500) - await t.completed }) test('refresh correctly with timeout > TICK_MS', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) const start = performance.now() @@ -154,22 +152,21 @@ describe('timers', () => { // 501ms timer was refreshed after 1250ms; total target is 1751 const delta = getDelta(start, 1751) - t.ok(delta >= -1, 'refreshed timer fired early') - t.ok(delta < ACCEPTABLE_DELTA, 'refreshed timer fired late') + t.assert.ok(delta >= -1, 'refreshed timer fired early') + t.assert.ok(delta < ACCEPTABLE_DELTA, 'refreshed timer fired late') }, 501) setTimeout(() => timeout.refresh(), 250) setTimeout(() => timeout.refresh(), 750) setTimeout(() => timeout.refresh(), 1250) - setTimeout(() => t.ok(true), 1800) + setTimeout(() => t.assert.ok(true), 1800) tick(2000) - await t.completed }) test('refresh correctly FastTimer with timeout > TICK_MS', async (t) => { - t = tspl(t, { plan: 3 }) + t.plan(3) // The long running FastTimer will ensure that the internal clock is // incremented by the TICK_MS value in the onTick function @@ -180,8 +177,8 @@ describe('timers', () => { const timeout = timers.setFastTimeout(() => { const delta = (timers.now() - start) - 2493 - t.ok(delta >= -1, `refreshed timer fired early (${delta} ms)`) - t.ok(delta < ACCEPTABLE_DELTA, `refreshed timer fired late (${delta} ms)`) + t.assert.ok(delta >= -1, `refreshed timer fired early (${delta} ms)`) + t.assert.ok(delta < ACCEPTABLE_DELTA, `refreshed timer fired late (${delta} ms)`) }, 1001) tick(250) @@ -197,14 +194,13 @@ describe('timers', () => { timeout.refresh() timers.clearTimeout(longRunningFastTimer) - setTimeout(() => t.ok(true), 500) + setTimeout(() => t.assert.ok(true), 500) tick(5000) - await t.completed }) test('a FastTimer will only increment by the defined TICK_MS value', async (t) => { - t = tspl(t, { plan: 6 }) + t.plan(6) const startInternalClock = timers.now() @@ -218,17 +214,17 @@ describe('timers', () => { await new Promise((resolve) => resolve()) tick(250) - t.strictEqual(timers.now() - startInternalClock, 0) + t.assert.strictEqual(timers.now() - startInternalClock, 0) tick(250) - t.strictEqual(timers.now() - startInternalClock, 499) + t.assert.strictEqual(timers.now() - startInternalClock, 499) tick(250) - t.strictEqual(timers.now() - startInternalClock, 499) + t.assert.strictEqual(timers.now() - startInternalClock, 499) tick(250) - t.strictEqual(timers.now() - startInternalClock, 998) + t.assert.strictEqual(timers.now() - startInternalClock, 998) tick(250) - t.strictEqual(timers.now() - startInternalClock, 998) + t.assert.strictEqual(timers.now() - startInternalClock, 998) tick(250) - t.strictEqual(timers.now() - startInternalClock, 1497) + t.assert.strictEqual(timers.now() - startInternalClock, 1497) timers.clearTimeout(longRunningFastTimer) }) @@ -236,7 +232,7 @@ describe('timers', () => { test('meet acceptable resolution time', async (t) => { const testTimeouts = [0, 1, 499, 500, 501, 990, 999, 1000, 1001, 1100, 1400, 1499, 1500, 4000, 5000] - t = tspl(t, { plan: testTimeouts.length * 2 }) + t.plan(testTimeouts.length * 2) const start = performance.now() @@ -244,15 +240,13 @@ describe('timers', () => { timers.setTimeout(() => { const delta = getDelta(start, target) - t.ok(delta >= -1, `${target}ms fired early`) - t.ok(delta < ACCEPTABLE_DELTA, `${target}ms fired late, got difference of ${delta}ms`) + t.assert.ok(delta >= -1, `${target}ms fired early`) + t.assert.ok(delta < ACCEPTABLE_DELTA, `${target}ms fired late, got difference of ${delta}ms`) }, target) } for (let i = 0; i < 6000; ++i) { clock.tick(1) } - - await t.completed }) }) diff --git a/test/tls-cert-leak.js b/test/tls-cert-leak.js index 784b6980f75..4c525ab5430 100644 --- a/test/tls-cert-leak.js +++ b/test/tls-cert-leak.js @@ -1,8 +1,6 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') -const { tspl } = require('@matteo.collina/tspl') const { fetch } = require('..') const https = require('node:https') const fs = require('node:fs') @@ -18,7 +16,7 @@ test('no memory leak with TLS certificate errors', { timeout: 20000 }, async (t) throw new Error('gc is not available. Run with \'--expose-gc\'.') } - const { ok } = tspl(t, { plan: 1 }) + t.plan(1) // Create HTTPS server with self-signed certificate const serverOptions = { @@ -123,7 +121,7 @@ test('no memory leak with TLS certificate errors', { timeout: 20000 }, async (t) const leakDetected = await processBatch(i, batchSize) if (leakDetected) { // If a leak is detected, fail the test - assert.fail('Memory leak detected: heap usage is consistently increasing at a significant rate') + t.assert.fail('Memory leak detected: heap usage is consistently increasing at a significant rate') return } @@ -136,9 +134,9 @@ test('no memory leak with TLS certificate errors', { timeout: 20000 }, async (t) // Final check const finalCheckResult = finalMemoryCheck() if (finalCheckResult) { - assert.fail(`Memory leak detected: ${finalCheckResult}`) + t.assert.fail(`Memory leak detected: ${finalCheckResult}`) } else { - ok(true, 'Memory usage has stabilized') + t.assert.ok(true, 'Memory usage has stabilized') } } diff --git a/test/tls-session-reuse.js b/test/tls-session-reuse.js index 2ebd25dbd2a..ce4346ed1fd 100644 --- a/test/tls-session-reuse.js +++ b/test/tls-session-reuse.js @@ -1,6 +1,5 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { test, after, describe } = require('node:test') const { readFileSync } = require('node:fs') const { join } = require('node:path') @@ -20,8 +19,8 @@ describe('A client should disable session caching', () => { const clientSessions = {} let serverRequests = 0 - test('Prepare request', async t => { - t = tspl(t, { plan: 3 }) + test('Prepare request', (t, done) => { + t.plan(3) const server = https.createServer(options, (req, res) => { if (req.url === '/drop-key') { server.setTicketKeys(crypto.randomBytes(48)) @@ -66,30 +65,28 @@ describe('A client should disable session caching', () => { delete tls.ciphers } client.request(options, (err, data) => { - t.ifError(err) + t.assert.ifError(err) clientSessions[options.name] = client[kSocket].getSession() data.body.resume().on('end', () => { if (queue.length !== 0) { return request() } - t.ok(true, 'pass') + t.assert.ok(true, 'pass') + done() }) }) } request() }) - - await t.completed }) - test('Verify cached sessions', async t => { - t = tspl(t, { plan: 2 }) - t.strictEqual(serverRequests, 2) - t.notEqual( + test('Verify cached sessions', t => { + t.plan(2) + t.assert.strictEqual(serverRequests, 2) + t.assert.notEqual( clientSessions.first.toString('hex'), clientSessions.second.toString('hex') ) - await t.completed }) }) @@ -99,8 +96,8 @@ describe('A pool should be able to reuse TLS sessions between clients', () => { const REQ_COUNT = 10 const ASSERT_PERFORMANCE_GAIN = false - test('Prepare request', async t => { - t = tspl(t, { plan: 2 + 1 + (ASSERT_PERFORMANCE_GAIN ? 1 : 0) }) + test('Prepare request', (t, done) => { + t.plan(2 + 1 + (ASSERT_PERFORMANCE_GAIN ? 1 : 0)) const server = https.createServer(options, (req, res) => { serverRequests++ res.end() @@ -171,11 +168,10 @@ describe('A pool should be able to reuse TLS sessions between clients', () => { await runRequests(poolWithoutSessionReuse, REQ_COUNT, false) await runRequests(poolWithSessionReuse, REQ_COUNT, true) - t.strictEqual(numSessions, 2) - t.strictEqual(serverRequests, 2 + REQ_COUNT * 2) - t.ok(true, 'pass') + t.assert.strictEqual(numSessions, 2) + t.assert.strictEqual(serverRequests, 2 + REQ_COUNT * 2) + t.assert.ok(true, 'pass') + done() }) - - await t.completed }) }) diff --git a/test/tls.js b/test/tls.js index 8c2b4cc8afb..c310f303c7c 100644 --- a/test/tls.js +++ b/test/tls.js @@ -16,13 +16,13 @@ // client.request({ method: 'GET', path: '/' }, (err, data) => { // t.error(err) -// t.equal(data.statusCode, 301) -// t.equal(client[kSocket].authorized, true) +// t.assert.strictEqual(data.statusCode, 301) +// t.assert.strictEqual(client[kSocket].authorized, true) // data.body // .resume() // .on('end', () => { -// t.ok(true, 'pass') +// t.assert.ok(true, 'pass') // }) // }) // }) @@ -39,13 +39,13 @@ // client.request({ method: 'GET', path: '/' }, (err, data) => { // t.error(err) -// t.equal(data.statusCode, 301) -// t.equal(client[kSocket].authorized, true) +// t.assert.strictEqual(data.statusCode, 301) +// t.assert.strictEqual(client[kSocket].authorized, true) // data.body // .resume() // .on('end', () => { -// t.ok(true, 'pass') +// t.assert.ok(true, 'pass') // }) // }) // }) @@ -65,23 +65,23 @@ // } // }, (err, data) => { // t.error(err) -// t.equal(data.statusCode, 301) -// t.equal(client[kSocket].authorized, true) +// t.assert.strictEqual(data.statusCode, 301) +// t.assert.strictEqual(client[kSocket].authorized, true) // data.body // .resume() // .on('end', () => { -// t.ok(true, 'pass') +// t.assert.ok(true, 'pass') // }) // client.once('disconnect', () => { -// t.ok(true, 'pass') +// t.assert.ok(true, 'pass') // didDisconnect = true // }) // }) // const body = new Readable({ read () {} }) // body.on('error', (err) => { -// t.ok(err) +// t.assert.ok(err) // }) // client.request({ // method: 'POST', @@ -91,8 +91,8 @@ // host: 'www.asd.com' // } // }, (err, data) => { -// t.equal(didDisconnect, true) -// t.ok(err) +// t.assert.strictEqual(didDisconnect, true) +// t.assert.ok(err) // }) // }) @@ -115,9 +115,9 @@ // } // }, (err, data) => { // t.error(err) -// t.equal(client[kRunning], 1) -// t.equal(data.statusCode, 301) -// t.equal(client[kSocket].authorized, true) +// t.assert.strictEqual(client[kRunning], 1) +// t.assert.strictEqual(data.statusCode, 301) +// t.assert.strictEqual(client[kSocket].authorized, true) // client.request({ // method: 'GET', @@ -127,20 +127,20 @@ // } // }, (err, data) => { // t.error(err) -// t.equal(data.statusCode, 301) -// t.equal(client[kSocket].authorized, true) +// t.assert.strictEqual(data.statusCode, 301) +// t.assert.strictEqual(client[kSocket].authorized, true) // data.body // .resume() // .on('end', () => { -// t.ok(true, 'pass') +// t.assert.ok(true, 'pass') // }) // }) // data.body // .resume() // .on('end', () => { -// t.ok(true, 'pass') +// t.assert.ok(true, 'pass') // }) // }) // }) @@ -160,16 +160,16 @@ // } // }, (err, data) => { // t.error(err) -// t.equal(data.statusCode, 301) -// t.equal(client[kSocket].authorized, true) +// t.assert.strictEqual(data.statusCode, 301) +// t.assert.strictEqual(client[kSocket].authorized, true) // data.body // .resume() // .on('end', () => { -// t.ok(true, 'pass') +// t.assert.ok(true, 'pass') // }) // client.once('disconnect', () => { -// t.ok(true, 'pass') +// t.assert.ok(true, 'pass') // didDisconnect = true // }) // }) @@ -182,7 +182,7 @@ // host: 'www.asd.com' // } // }, (err, data) => { -// t.equal(didDisconnect, true) -// t.ok(err) +// t.assert.strictEqual(didDisconnect, true) +// t.assert.ok(err) // }) // }) diff --git a/test/trailers.js b/test/trailers.js index 64a29da7b22..264062195e6 100644 --- a/test/trailers.js +++ b/test/trailers.js @@ -1,12 +1,11 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { test, after } = require('node:test') const { Client } = require('..') const { createServer } = require('node:http') -test('response trailers missing is OK', async (t) => { - t = tspl(t, { plan: 1 }) +test('response trailers missing is OK', (t, done) => { + t.plan(1) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.writeHead(200, { @@ -24,14 +23,13 @@ test('response trailers missing is OK', async (t) => { body: 'asd' }) - t.strictEqual(await body.text(), 'response') + t.assert.strictEqual(await body.text(), 'response') + done() }) - - await t.completed }) -test('response trailers missing w trailers is OK', async (t) => { - t = tspl(t, { plan: 2 }) +test('response trailers missing w trailers is OK', (t, done) => { + t.plan(2) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.writeHead(200, { @@ -52,9 +50,8 @@ test('response trailers missing w trailers is OK', async (t) => { body: 'asd' }) - t.strictEqual(await body.text(), 'response') - t.deepStrictEqual(trailers, { asd: 'foo' }) + t.assert.strictEqual(await body.text(), 'response') + t.assert.deepStrictEqual(trailers, { asd: 'foo' }) + done() }) - - await t.completed }) diff --git a/test/util.js b/test/util.js index ac988997421..40b2ed6c0fb 100644 --- a/test/util.js +++ b/test/util.js @@ -1,253 +1,252 @@ 'use strict' -const { strictEqual, throws, doesNotThrow } = require('node:assert') const { test, describe } = require('node:test') const { isBlobLike, parseURL, isHttpOrHttpsPrefixed, isValidPort } = require('../lib/core/util') const { InvalidArgumentError } = require('../lib/core/errors') describe('isBlobLike', () => { - test('buffer', () => { + test('buffer', (t) => { const buffer = Buffer.alloc(1) - strictEqual(isBlobLike(buffer), false) + t.assert.strictEqual(isBlobLike(buffer), false) }) - test('blob', () => { + test('blob', (t) => { const blob = new Blob(['asd'], { type: 'application/json' }) - strictEqual(isBlobLike(blob), true) + t.assert.strictEqual(isBlobLike(blob), true) }) - test('file', () => { + test('file', (t) => { const file = new File(['asd'], 'file.txt', { type: 'text/plain' }) - strictEqual(isBlobLike(file), true) + t.assert.strictEqual(isBlobLike(file), true) }) - test('blobLikeStream', () => { + test('blobLikeStream', (t) => { const blobLikeStream = { [Symbol.toStringTag]: 'Blob', stream: () => { } } - strictEqual(isBlobLike(blobLikeStream), true) + t.assert.strictEqual(isBlobLike(blobLikeStream), true) }) - test('fileLikeStream', () => { + test('fileLikeStream', (t) => { const fileLikeStream = { stream: () => { }, [Symbol.toStringTag]: 'File' } - strictEqual(isBlobLike(fileLikeStream), true) + t.assert.strictEqual(isBlobLike(fileLikeStream), true) }) - test('fileLikeArrayBuffer', () => { + test('fileLikeArrayBuffer', (t) => { const blobLikeArrayBuffer = { [Symbol.toStringTag]: 'Blob', arrayBuffer: () => { } } - strictEqual(isBlobLike(blobLikeArrayBuffer), true) + t.assert.strictEqual(isBlobLike(blobLikeArrayBuffer), true) }) - test('blobLikeArrayBuffer', () => { + test('blobLikeArrayBuffer', (t) => { const fileLikeArrayBuffer = { [Symbol.toStringTag]: 'File', arrayBuffer: () => { } } - strictEqual(isBlobLike(fileLikeArrayBuffer), true) + t.assert.strictEqual(isBlobLike(fileLikeArrayBuffer), true) }) - test('string', () => { - strictEqual(isBlobLike('Blob'), false) + test('string', (t) => { + t.assert.strictEqual(isBlobLike('Blob'), false) }) - test('null', () => { - strictEqual(isBlobLike(null), false) + test('null', (t) => { + t.assert.strictEqual(isBlobLike(null), false) }) }) describe('isHttpOrHttpsPrefixed', () => { - test('returns false for invalid values', () => { - strictEqual(isHttpOrHttpsPrefixed('wss:'), false) + test('returns false for invalid values', (t) => { + t.assert.strictEqual(isHttpOrHttpsPrefixed('wss:'), false) }) - test('returns true for "http:" or "https:"', () => { - strictEqual(isHttpOrHttpsPrefixed('http:'), true) - strictEqual(isHttpOrHttpsPrefixed('https:'), true) + test('returns true for "http:" or "https:"', (t) => { + t.assert.strictEqual(isHttpOrHttpsPrefixed('http:'), true) + t.assert.strictEqual(isHttpOrHttpsPrefixed('https:'), true) }) }) describe('isValidPort', () => { - test('returns false for invalid values', () => { - strictEqual(isValidPort(NaN), false) - strictEqual(isValidPort(Infinity), false) - strictEqual(isValidPort(-Infinity), false) - strictEqual(isValidPort(NaN.toString()), false) - strictEqual(isValidPort(Infinity.toString()), false) - strictEqual(isValidPort(-Infinity.toString()), false) - strictEqual(isValidPort('port'), false) - strictEqual(isValidPort('65535i'), false) - }) - test('returns true for port in range of 0 to 65535 as number', () => { + test('returns false for invalid values', (t) => { + t.assert.strictEqual(isValidPort(NaN), false) + t.assert.strictEqual(isValidPort(Infinity), false) + t.assert.strictEqual(isValidPort(-Infinity), false) + t.assert.strictEqual(isValidPort(NaN.toString()), false) + t.assert.strictEqual(isValidPort(Infinity.toString()), false) + t.assert.strictEqual(isValidPort(-Infinity.toString()), false) + t.assert.strictEqual(isValidPort('port'), false) + t.assert.strictEqual(isValidPort('65535i'), false) + }) + test('returns true for port in range of 0 to 65535 as number', (t) => { for (let i = 0; i < 65536; i++) { - strictEqual(isValidPort(i), true) + t.assert.strictEqual(isValidPort(i), true) } }) - test('returns true for port in range of 0 to 65535 as string', () => { + test('returns true for port in range of 0 to 65535 as string', (t) => { for (let i = 0; i < 65536; i++) { - strictEqual(isValidPort(i.toString()), true) + t.assert.strictEqual(isValidPort(i.toString()), true) } }) }) describe('parseURL', () => { - test('throws if url is not a string or object', () => { - throws(() => { parseURL(null) }, new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')) - throws(() => { parseURL(1) }, new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')) - throws(() => { parseURL(true) }, new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')) - throws(() => { parseURL(false) }, new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')) - throws(() => { parseURL(false) }, new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')) + test('throws if url is not a string or object', (t) => { + t.assert.throws(() => { parseURL(null) }, new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')) + t.assert.throws(() => { parseURL(1) }, new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')) + t.assert.throws(() => { parseURL(true) }, new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')) + t.assert.throws(() => { parseURL(false) }, new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')) + t.assert.throws(() => { parseURL(false) }, new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')) }) - test('throws if protocol is not beginning with http:', () => { - throws(() => { parseURL('ws://www.example.com') }, new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')) + test('throws if protocol is not beginning with http:', (t) => { + t.assert.throws(() => { parseURL('ws://www.example.com') }, new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')) }) - test('throws if protocol is not beginning with https:', () => { - throws(() => { parseURL('wss://www.example.com') }, new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')) + test('throws if protocol is not beginning with https:', (t) => { + t.assert.throws(() => { parseURL('wss://www.example.com') }, new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')) }) - test('returns an URL object if url is a string of an https URL', () => { + test('returns an URL object if url is a string of an https URL', (t) => { const url = parseURL('https://www.example.com') - strictEqual(url instanceof URL, true) - strictEqual(url.href, 'https://www.example.com/') + t.assert.strictEqual(url instanceof URL, true) + t.assert.strictEqual(url.href, 'https://www.example.com/') }) - test('returns an URL object if url is a string of an http URL', () => { + test('returns an URL object if url is a string of an http URL', (t) => { const url = parseURL('http://www.example.com') - strictEqual(url instanceof URL, true) - strictEqual(url.href, 'http://www.example.com/') + t.assert.strictEqual(url instanceof URL, true) + t.assert.strictEqual(url.href, 'http://www.example.com/') }) describe('when url is an instance of URL', () => { - test('returns the same URL object', () => { + test('returns the same URL object', (t) => { const url = new URL('https://www.example.com') const parsedURL = parseURL(url) - strictEqual(parsedURL, url) + t.assert.strictEqual(parsedURL, url) }) - test('throws if the URL protocol is not http: or https:', () => { + test('throws if the URL protocol is not http: or https:', (t) => { const url = new URL('ws://www.example.com') - throws(() => { parseURL(url) }, new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')) + t.assert.throws(() => { parseURL(url) }, new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')) }) - test('passes if the URL protocol is http:', () => { + test('passes if the URL protocol is http:', (t) => { const url = new URL('http://www.example.com') delete url.origin - doesNotThrow(() => { parseURL(url) }) + t.assert.doesNotThrow(() => { parseURL(url) }) }) - test('passes if the URL protocol is https:', () => { + test('passes if the URL protocol is https:', (t) => { const url = new URL('https://www.example.com') delete url.origin - doesNotThrow(() => { parseURL(url) }) + t.assert.doesNotThrow(() => { parseURL(url) }) }) - test('passes if the URL protocol is http:', () => { + test('passes if the URL protocol is http:', (t) => { const url = new URL('http://www.example.com') - doesNotThrow(() => { parseURL(url) }) + t.assert.doesNotThrow(() => { parseURL(url) }) }) - test('passes if the URL protocol is https:', () => { + test('passes if the URL protocol is https:', (t) => { const url = new URL('https://www.example.com') - doesNotThrow(() => { parseURL(url) }) + t.assert.doesNotThrow(() => { parseURL(url) }) }) }) describe('when url is an common object', () => { - test.skip('does not throw if a urlLike object is passed', () => { + test.skip('does not throw if a urlLike object is passed', (t) => { const url = parseURL({ protocol: 'http:' }) console.log(url) }) describe('port', () => { - test('throws if port is not an finite number as string', () => { - throws(() => parseURL({ protocol: 'http:', port: 'NaN' }), new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.')) + test('throws if port is not an finite number as string', (t) => { + t.assert.throws(() => parseURL({ protocol: 'http:', port: 'NaN' }), new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.')) }) - test('doesn\'t throw if port is valid number', () => { + test('doesn\'t throw if port is valid number', (t) => { for (let i = 0; i < 65536; i++) { - doesNotThrow(() => parseURL({ protocol: 'http:', hostname: 'www.example.com', port: i.toString() }), i.toString()) + t.assert.doesNotThrow(() => parseURL({ protocol: 'http:', hostname: 'www.example.com', port: i.toString() }), i.toString()) } }) - test('throws if port is invalid number', () => { - throws(() => parseURL({ protocol: 'http:', port: '-1' }), new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.')) - throws(() => parseURL({ protocol: 'http:', port: '65536' }), new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.')) + test('throws if port is invalid number', (t) => { + t.assert.throws(() => parseURL({ protocol: 'http:', port: '-1' }), new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.')) + t.assert.throws(() => parseURL({ protocol: 'http:', port: '65536' }), new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.')) }) - test('sets port based on protocol', () => { - strictEqual(parseURL({ protocol: 'http:', hostname: 'www.example.com', path: '/' }).port, '') - strictEqual(parseURL({ protocol: 'https:', hostname: 'www.example.com', path: '/' }).port, '') + test('sets port based on protocol', (t) => { + t.assert.strictEqual(parseURL({ protocol: 'http:', hostname: 'www.example.com', path: '/' }).port, '') + t.assert.strictEqual(parseURL({ protocol: 'https:', hostname: 'www.example.com', path: '/' }).port, '') }) - test('don\'t override port with protocol if port was explicitly set', () => { - strictEqual(parseURL({ protocol: 'http:', hostname: 'www.example.com', path: '/', port: 1337 }).port, '1337') - strictEqual(parseURL({ protocol: 'https:', hostname: 'www.example.com', path: '/', port: 1337 }).port, '1337') + test('don\'t override port with protocol if port was explicitly set', (t) => { + t.assert.strictEqual(parseURL({ protocol: 'http:', hostname: 'www.example.com', path: '/', port: 1337 }).port, '1337') + t.assert.strictEqual(parseURL({ protocol: 'https:', hostname: 'www.example.com', path: '/', port: 1337 }).port, '1337') }) }) describe('path', () => { - test('doesn\'t throw if path null or undefined', () => { + test('doesn\'t throw if path null or undefined', (t) => { parseURL({ protocol: 'http:', hostname: 'www.example.com', path: null }) parseURL({ protocol: 'http:', hostname: 'www.example.com', path: undefined }) }) - test('throws if path is not as string', () => { - throws(() => parseURL({ protocol: 'http:', hostname: 'www.example.com', path: 1 }), new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.')) + test('throws if path is not as string', (t) => { + t.assert.throws(() => parseURL({ protocol: 'http:', hostname: 'www.example.com', path: 1 }), new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.')) }) - test('doesn\'t throw if path is a string', () => { + test('doesn\'t throw if path is a string', (t) => { parseURL({ protocol: 'http:', hostname: 'www.example.com', path: '/' }) }) - test('accepts path with and without leading /', () => { - strictEqual(parseURL({ protocol: 'http:', hostname: 'www.example.com', path: 'abc' }).pathname, '/abc') - strictEqual(parseURL({ protocol: 'https:', hostname: 'www.example.com', path: '/abc' }).pathname, '/abc') + test('accepts path with and without leading /', (t) => { + t.assert.strictEqual(parseURL({ protocol: 'http:', hostname: 'www.example.com', path: 'abc' }).pathname, '/abc') + t.assert.strictEqual(parseURL({ protocol: 'https:', hostname: 'www.example.com', path: '/abc' }).pathname, '/abc') }) }) describe('pathname', () => { - test('doesn\'t throw if pathname null or undefined', () => { + test('doesn\'t throw if pathname null or undefined', (t) => { parseURL({ protocol: 'http:', hostname: 'www.example.com', pathname: null }) parseURL({ protocol: 'http:', hostname: 'www.example.com', pathname: undefined }) }) - test('throws if pathname is not as string', () => { - throws(() => parseURL({ protocol: 'http:', pathname: 1 }), new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.')) + test('throws if pathname is not as string', (t) => { + t.assert.throws(() => parseURL({ protocol: 'http:', pathname: 1 }), new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.')) }) - test('doesn\'t throw if pathname is a string', () => { + test('doesn\'t throw if pathname is a string', (t) => { parseURL({ protocol: 'http:', hostname: 'www.example.com', pathname: '/' }) }) }) describe('hostname', () => { - test('doesn\'t throw if hostname null or undefined', () => { + test('doesn\'t throw if hostname null or undefined', (t) => { parseURL({ protocol: 'http:', hostname: null, origin: 'http://www.example.com' }) parseURL({ protocol: 'http:', hostname: undefined, origin: 'http://www.example.com' }) }) - test('throws if hostname is not as string', () => { - throws(() => parseURL({ protocol: 'http:', hostname: 1 }), new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.')) + test('throws if hostname is not as string', (t) => { + t.assert.throws(() => parseURL({ protocol: 'http:', hostname: 1 }), new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.')) }) - test('doesn\'t throw if hostname is a string', () => { + test('doesn\'t throw if hostname is a string', (t) => { parseURL({ protocol: 'http:', hostname: 'www.example.com' }) }) }) describe('origin', () => { - test('doesn\'t throw if origin null or undefined', () => { + test('doesn\'t throw if origin null or undefined', (t) => { parseURL({ protocol: 'http:', hostname: 'www.example.com', origin: null }) parseURL({ protocol: 'http:', hostname: 'www.example.com', origin: undefined }) }) - test('throws if origin is not as string', () => { - throws(() => parseURL({ protocol: 'http:', origin: 1 }), new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.')) + test('throws if origin is not as string', (t) => { + t.assert.throws(() => parseURL({ protocol: 'http:', origin: 1 }), new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.')) }) - test('doesn\'t throw if origin is a string', () => { + test('doesn\'t throw if origin is a string', (t) => { parseURL({ protocol: 'http:', origin: 'https://www.example.com' }) }) - test('removes trailing /', () => { - strictEqual(parseURL({ protocol: 'http:', origin: 'https://www.example.com/' }).origin, 'https://www.example.com') + test('removes trailing /', (t) => { + t.assert.strictEqual(parseURL({ protocol: 'http:', origin: 'https://www.example.com/' }).origin, 'https://www.example.com') }) }) describe('protocol', () => { - test('throws if protocol is not http: or https: and no origin is defined', () => { - throws(() => parseURL({ protocol: 'wss:', hostname: 'www.example.com', path: '' })) + test('throws if protocol is not http: or https: and no origin is defined', (t) => { + t.assert.throws(() => parseURL({ protocol: 'wss:', hostname: 'www.example.com', path: '' })) }) - test('doesn\'t throw when origin is not provided', () => { - strictEqual(parseURL({ protocol: 'http:', hostname: 'www.example.com', path: '' }).origin, 'http://www.example.com') + test('doesn\'t throw when origin is not provided', (t) => { + t.assert.strictEqual(parseURL({ protocol: 'http:', hostname: 'www.example.com', path: '' }).origin, 'http://www.example.com') }) }) })