diff --git a/test/fetch/407-statuscode-window-null.js b/test/fetch/407-statuscode-window-null.js index 26e763c59dc..5e87574d550 100644 --- a/test/fetch/407-statuscode-window-null.js +++ b/test/fetch/407-statuscode-window-null.js @@ -4,7 +4,6 @@ const { fetch } = require('../..') const { createServer } = require('node:http') const { once } = require('node:events') const { test } = require('node:test') -const assert = require('node:assert') const { closeServerAsPromise } = require('../utils/node-http') @@ -19,5 +18,5 @@ test('Receiving a 407 status code w/ a window option present should reject', asy // if init.window exists, the spec tells us to set request.window to 'no-window', // which later causes the request to be rejected if the status code is 407 - await assert.rejects(fetch(`http://localhost:${server.address().port}`, { window: null })) + await t.assert.rejects(fetch(`http://localhost:${server.address().port}`, { window: null })) }) diff --git a/test/fetch/abort.js b/test/fetch/abort.js index 7bb2505b6d2..6a0162d3d4b 100644 --- a/test/fetch/abort.js +++ b/test/fetch/abort.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 { createServer } = require('node:http') const { once } = require('node:events') @@ -15,20 +13,20 @@ test('allows aborting with custom errors', async (t) => { await once(server, 'listening') await t.test('Using AbortSignal.timeout with cause', async (t) => { - const { strictEqual } = tspl(t, { plan: 2 }) + t.plan(2) try { await fetch(`http://localhost:${server.address().port}`, { signal: AbortSignal.timeout(50) }) - assert.fail('should throw') + t.assert.fail('should throw') } catch (err) { if (err.name === 'TypeError') { const cause = err.cause - strictEqual(cause.name, 'HeadersTimeoutError') - strictEqual(cause.code, 'UND_ERR_HEADERS_TIMEOUT') + t.assert.strictEqual(cause.name, 'HeadersTimeoutError') + t.assert.strictEqual(cause.code, 'UND_ERR_HEADERS_TIMEOUT') } else if (err.name === 'TimeoutError') { - strictEqual(err.code, DOMException.TIMEOUT_ERR) - strictEqual(err.cause, undefined) + t.assert.strictEqual(err.code, DOMException.TIMEOUT_ERR) + t.assert.strictEqual(err.cause, undefined) } else { throw err } @@ -39,7 +37,7 @@ test('allows aborting with custom errors', async (t) => { const ac = new AbortController() ac.abort() // no reason - await assert.rejects( + await t.assert.rejects( fetch(`http://localhost:${server.address().port}`, { signal: ac.signal }), diff --git a/test/fetch/abort2.js b/test/fetch/abort2.js index f62e5c8c49a..beffd3fd998 100644 --- a/test/fetch/abort2.js +++ b/test/fetch/abort2.js @@ -1,7 +1,6 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') const { fetch } = require('../..') const { createServer } = require('node:http') const { once } = require('node:events') @@ -52,9 +51,9 @@ test('parallel fetch with the same AbortController works as expected', async (t) return a }, { resolved: [], rejected: [] }) - assert.strictEqual(rejected.length, 9) // out of 10 requests, only 1 should succeed - assert.strictEqual(resolved.length, 1) + t.assert.strictEqual(rejected.length, 9) // out of 10 requests, only 1 should succeed + t.assert.strictEqual(resolved.length, 1) - assert.ok(rejected.every(rej => rej.reason?.code === DOMException.ABORT_ERR)) - assert.deepStrictEqual(resolved[0].value, body) + t.assert.ok(rejected.every(rej => rej.reason?.code === DOMException.ABORT_ERR)) + t.assert.deepStrictEqual(resolved[0].value, body) }) diff --git a/test/fetch/about-uri.js b/test/fetch/about-uri.js index fc8ef5f3455..643001f962e 100644 --- a/test/fetch/about-uri.js +++ b/test/fetch/about-uri.js @@ -1,20 +1,19 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') const { fetch } = require('../..') test('fetching about: uris', async (t) => { await t.test('about:blank', async () => { - await assert.rejects(fetch('about:blank')) + await t.assert.rejects(fetch('about:blank')) }) await t.test('All other about: urls should return an error', async () => { try { await fetch('about:config') - assert.fail('fetching about:config should fail') + t.assert.fail('fetching about:config should fail') } catch (e) { - assert.ok(e, 'this error was expected') + t.assert.ok(e, 'this error was expected') } }) }) diff --git a/test/fetch/blob-uri.js b/test/fetch/blob-uri.js index 342d9bfb9ec..74062246e88 100644 --- a/test/fetch/blob-uri.js +++ b/test/fetch/blob-uri.js @@ -1,7 +1,6 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') const { fetch } = require('../..') test('fetching blob: uris', async (t) => { @@ -19,9 +18,9 @@ test('fetching blob: uris', async (t) => { await t.test('a normal fetch request works', async () => { const res = await fetch(objectURL) - assert.strictEqual(blobContents, await res.text()) - assert.strictEqual(blob.type, res.headers.get('Content-Type')) - assert.strictEqual(`${blob.size}`, res.headers.get('Content-Length')) + t.assert.strictEqual(blobContents, await res.text()) + t.assert.strictEqual(blob.type, res.headers.get('Content-Type')) + t.assert.strictEqual(`${blob.size}`, res.headers.get('Content-Length')) }) await t.test('non-GET method to blob: fails', async () => { @@ -29,9 +28,9 @@ test('fetching blob: uris', async (t) => { await fetch(objectURL, { method: 'POST' }) - assert.fail('expected POST to blob: uri to fail') + t.assert.fail('expected POST to blob: uri to fail') } catch (e) { - assert.ok(e, 'Got the expected error') + t.assert.ok(e, 'Got the expected error') } }) @@ -41,9 +40,9 @@ test('fetching blob: uris', async (t) => { try { await fetch(objectURL) - assert.fail('expected revoked blob: url to fail') + t.assert.fail('expected revoked blob: url to fail') } catch (e) { - assert.ok(e, 'Got the expected error') + t.assert.ok(e, 'Got the expected error') } }) @@ -51,16 +50,16 @@ test('fetching blob: uris', async (t) => { await t.test('works with a fragment', async () => { const res = await fetch(objectURL + '#fragment') - assert.strictEqual(blobContents, await res.text()) + t.assert.strictEqual(blobContents, await res.text()) }) // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56 await t.test('Appending a query string to blob: url should cause fetch to fail', async () => { try { await fetch(objectURL + '?querystring') - assert.fail('expected ?querystring blob: url to fail') + t.assert.fail('expected ?querystring blob: url to fail') } catch (e) { - assert.ok(e, 'Got the expected error') + t.assert.ok(e, 'Got the expected error') } }) @@ -68,9 +67,9 @@ test('fetching blob: uris', async (t) => { await t.test('Appending a path should cause fetch to fail', async () => { try { await fetch(objectURL + '/path') - assert.fail('expected /path blob: url to fail') + t.assert.fail('expected /path blob: url to fail') } catch (e) { - assert.ok(e, 'Got the expected error') + t.assert.ok(e, 'Got the expected error') } }) @@ -79,9 +78,9 @@ test('fetching blob: uris', async (t) => { for (const method of ['HEAD', 'POST', 'DELETE', 'OPTIONS', 'PUT', 'CUSTOM']) { try { await fetch(objectURL, { method }) - assert.fail(`${method} fetch should have failed`) + t.assert.fail(`${method} fetch should have failed`) } catch (e) { - assert.ok(e, `${method} blob url - test succeeded`) + t.assert.ok(e, `${method} blob url - test succeeded`) } } }) diff --git a/test/fetch/bundle.js b/test/fetch/bundle.js index f073e9e18f9..b39dd0d0b02 100644 --- a/test/fetch/bundle.js +++ b/test/fetch/bundle.js @@ -1,25 +1,24 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') const { Response, Request, FormData, Headers, MessageEvent, CloseEvent, ErrorEvent } = require('../../undici-fetch') -test('bundle sets constructor.name and .name properly', () => { - assert.strictEqual(new Response().constructor.name, 'Response') - assert.strictEqual(Response.name, 'Response') +test('bundle sets constructor.name and .name properly', (t) => { + t.assert.strictEqual(new Response().constructor.name, 'Response') + t.assert.strictEqual(Response.name, 'Response') - assert.strictEqual(new Request('http://a').constructor.name, 'Request') - assert.strictEqual(Request.name, 'Request') + t.assert.strictEqual(new Request('http://a').constructor.name, 'Request') + t.assert.strictEqual(Request.name, 'Request') - assert.strictEqual(new Headers().constructor.name, 'Headers') - assert.strictEqual(Headers.name, 'Headers') + t.assert.strictEqual(new Headers().constructor.name, 'Headers') + t.assert.strictEqual(Headers.name, 'Headers') - assert.strictEqual(new FormData().constructor.name, 'FormData') - assert.strictEqual(FormData.name, 'FormData') + t.assert.strictEqual(new FormData().constructor.name, 'FormData') + t.assert.strictEqual(FormData.name, 'FormData') }) -test('regression test for https://github.com/nodejs/node/issues/50263', () => { +test('regression test for https://github.com/nodejs/node/issues/50263', (t) => { const request = new Request('https://a', { headers: { test: 'abc' @@ -29,11 +28,11 @@ test('regression test for https://github.com/nodejs/node/issues/50263', () => { const request1 = new Request(request, { body: 'does not matter' }) - assert.strictEqual(request1.headers.get('test'), 'abc') + t.assert.strictEqual(request1.headers.get('test'), 'abc') }) test('WebSocket related events are exported', (t) => { - assert.deepStrictEqual(typeof CloseEvent, 'function') - assert.deepStrictEqual(typeof MessageEvent, 'function') - assert.deepStrictEqual(typeof ErrorEvent, 'function') + t.assert.deepStrictEqual(typeof CloseEvent, 'function') + t.assert.deepStrictEqual(typeof MessageEvent, 'function') + t.assert.deepStrictEqual(typeof ErrorEvent, 'function') }) diff --git a/test/fetch/client-error-stack-trace.js b/test/fetch/client-error-stack-trace.js index b72aaa2dcad..a49d9d654cd 100644 --- a/test/fetch/client-error-stack-trace.js +++ b/test/fetch/client-error-stack-trace.js @@ -1,7 +1,6 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') const { sep } = require('node:path') const { fetch, setGlobalDispatcher, Agent } = require('../..') const { fetch: fetchIndex } = require('../../index-fetch') @@ -16,10 +15,10 @@ test('FETCH: request errors and prints trimmed stack trace', async (t) => { await fetch('http://a.com') } catch (error) { const stackLines = error.stack.split('\n') - assert.ok(stackLines[0].includes('TypeError: fetch failed')) - assert.ok(stackLines[1].includes(`undici${sep}index.js`)) - assert.ok(stackLines[2].includes('at process.processTicksAndRejections')) - assert.ok(stackLines[3].includes(`at async TestContext. (${__filename}`)) + t.assert.ok(stackLines[0].includes('TypeError: fetch failed')) + t.assert.ok(stackLines[1].includes(`undici${sep}index.js`)) + t.assert.ok(stackLines[2].includes('at process.processTicksAndRejections')) + t.assert.ok(stackLines[3].includes(`at async TestContext. (${__filename}`)) } }) @@ -28,9 +27,9 @@ test('FETCH-index: request errors and prints trimmed stack trace', async (t) => await fetchIndex('http://a.com') } catch (error) { const stackLines = error.stack.split('\n') - assert.ok(stackLines[0].includes('TypeError: fetch failed')) - assert.ok(stackLines[1].includes(`undici${sep}index-fetch.js`)) - assert.ok(stackLines[2].includes('at process.processTicksAndRejections')) - assert.ok(stackLines[3].includes(`at async TestContext. (${__filename}`)) + t.assert.ok(stackLines[0].includes('TypeError: fetch failed')) + t.assert.ok(stackLines[1].includes(`undici${sep}index-fetch.js`)) + t.assert.ok(stackLines[2].includes('at process.processTicksAndRejections')) + t.assert.ok(stackLines[3].includes(`at async TestContext. (${__filename}`)) } }) diff --git a/test/fetch/client-fetch.js b/test/fetch/client-fetch.js index 66f2dd1f5c2..5e424783d09 100644 --- a/test/fetch/client-fetch.js +++ b/test/fetch/client-fetch.js @@ -3,8 +3,6 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') -const { tspl } = require('@matteo.collina/tspl') const { createServer } = require('node:http') const { fetch, Response, Request, FormData } = require('../..') const { Client, setGlobalDispatcher, Agent } = require('../..') @@ -22,21 +20,21 @@ setGlobalDispatcher(new Agent({ })) test('function signature', (t) => { - const { strictEqual } = tspl(t, { plan: 2 }) + t.plan(2) - strictEqual(fetch.name, 'fetch') - strictEqual(fetch.length, 1) + t.assert.strictEqual(fetch.name, 'fetch') + t.assert.strictEqual(fetch.length, 1) }) test('args validation', async (t) => { - const { rejects } = tspl(t, { plan: 2 }) + t.plan(2) - await rejects(fetch(), TypeError) - await rejects(fetch('ftp://unsupported'), TypeError) + await t.assert.rejects(fetch(), TypeError) + await t.assert.rejects(fetch('ftp://unsupported'), TypeError) }) test('request json', (t, done) => { - const { deepStrictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const obj = { asd: true } const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { @@ -46,13 +44,13 @@ test('request json', (t, done) => { server.listen(0, async () => { const body = await fetch(`http://localhost:${server.address().port}`) - deepStrictEqual(obj, await body.json()) + t.assert.deepStrictEqual(obj, await body.json()) done() }) }) test('request text', (t, done) => { - const { strictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const obj = { asd: true } const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { @@ -62,13 +60,13 @@ test('request text', (t, done) => { server.listen(0, async () => { const body = await fetch(`http://localhost:${server.address().port}`) - strictEqual(JSON.stringify(obj), await body.text()) + t.assert.strictEqual(JSON.stringify(obj), await body.text()) done() }) }) test('request arrayBuffer', (t, done) => { - const { deepStrictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const obj = { asd: true } const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { @@ -78,13 +76,13 @@ test('request arrayBuffer', (t, done) => { server.listen(0, async () => { const body = await fetch(`http://localhost:${server.address().port}`) - deepStrictEqual(Buffer.from(JSON.stringify(obj)), Buffer.from(await body.arrayBuffer())) + t.assert.deepStrictEqual(Buffer.from(JSON.stringify(obj)), Buffer.from(await body.arrayBuffer())) done() }) }) test('should set type of blob object to the value of the `Content-Type` header from response', (t, done) => { - const { strictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const obj = { asd: true } const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { @@ -95,13 +93,13 @@ test('should set type of blob object to the value of the `Content-Type` header f server.listen(0, async () => { const response = await fetch(`http://localhost:${server.address().port}`) - strictEqual('application/json', (await response.blob()).type) + t.assert.strictEqual('application/json', (await response.blob()).type) done() }) }) test('pre aborted with readable request body', (t, done) => { - const { strictEqual } = tspl(t, { plan: 2 }) + t.plan(2) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { }) @@ -115,18 +113,18 @@ test('pre aborted with readable request body', (t, done) => { method: 'POST', body: new ReadableStream({ async cancel (reason) { - strictEqual(reason.name, 'AbortError') + t.assert.strictEqual(reason.name, 'AbortError') } }), duplex: 'half' }).catch(err => { - strictEqual(err.name, 'AbortError') + t.assert.strictEqual(err.name, 'AbortError') }).finally(done) }) }) test('pre aborted with closed readable request body', (t, done) => { - const { ok, strictEqual } = tspl(t, { plan: 2 }) + t.plan(2) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { }) @@ -137,11 +135,11 @@ test('pre aborted with closed readable request body', (t, done) => { ac.abort() const body = new ReadableStream({ async start (c) { - ok(true) + t.assert.ok(true) c.close() }, async cancel (reason) { - assert.fail() + t.assert.fail() } }) queueMicrotask(() => { @@ -151,14 +149,14 @@ test('pre aborted with closed readable request body', (t, done) => { body, duplex: 'half' }).catch(err => { - strictEqual(err.name, 'AbortError') + t.assert.strictEqual(err.name, 'AbortError') }).finally(done) }) }) }) test('unsupported formData 1', (t, done) => { - const { strictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'asdasdsad') @@ -170,14 +168,14 @@ test('unsupported formData 1', (t, done) => { fetch(`http://localhost:${server.address().port}`) .then(res => res.formData()) .catch(err => { - strictEqual(err.name, 'TypeError') + t.assert.strictEqual(err.name, 'TypeError') }) .finally(done) }) }) test('multipart formdata not base64', async (t) => { - const { strictEqual } = tspl(t, { plan: 2 }) + t.plan(2) // Construct example form data, with text and blob fields const formData = new FormData() @@ -201,14 +199,14 @@ test('multipart formdata not base64', async (t) => { const res = await fetch(`http://localhost:${server.address().port}`) const form = await res.formData() - strictEqual(form.get('field1'), 'value1') + t.assert.strictEqual(form.get('field1'), 'value1') const text = await form.get('field2').text() - strictEqual(text, 'example\ntext file') + t.assert.strictEqual(text, 'example\ntext file') }) test('multipart formdata base64', (t, done) => { - const { strictEqual } = tspl(t, { plan: 1 }) + t.plan(1) // Example form data with base64 encoding const data = randomFillSync(Buffer.alloc(256)) @@ -239,14 +237,14 @@ test('multipart formdata base64', (t, done) => { .then(form => form.get('file').arrayBuffer()) .then(buffer => createHash('sha256').update(Buffer.from(buffer)).digest('base64')) .then(digest => { - strictEqual(createHash('sha256').update(data).digest('base64'), digest) + t.assert.strictEqual(createHash('sha256').update(data).digest('base64'), digest) }) .finally(done) }) }) test('multipart fromdata non-ascii filed names', async (t) => { - const { strictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const request = new Request('http://localhost', { method: 'POST', @@ -262,11 +260,11 @@ test('multipart fromdata non-ascii filed names', async (t) => { }) const form = await request.formData() - strictEqual(form.get('fiŝo'), 'value1') + t.assert.strictEqual(form.get('fiŝo'), 'value1') }) test('busboy emit error', async (t) => { - const { rejects } = tspl(t, { plan: 1 }) + t.plan(1) const formData = new FormData() formData.append('field1', 'value1') @@ -284,23 +282,23 @@ test('busboy emit error', async (t) => { await listen(0) const res = await fetch(`http://localhost:${server.address().port}`) - await rejects(res.formData(), 'Unexpected end of multipart data') + await t.assert.rejects(res.formData(), 'Unexpected end of multipart data') }) // https://github.com/nodejs/undici/issues/2244 test('parsing formData preserve full path on files', async (t) => { - const { strictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const formData = new FormData() formData.append('field1', new File(['foo'], 'a/b/c/foo.txt')) const tempRes = new Response(formData) const form = await tempRes.formData() - strictEqual(form.get('field1').name, 'a/b/c/foo.txt') + t.assert.strictEqual(form.get('field1').name, 'a/b/c/foo.txt') }) test('urlencoded formData', (t, done) => { - const { strictEqual } = tspl(t, { plan: 2 }) + t.plan(2) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'application/x-www-form-urlencoded') @@ -312,15 +310,15 @@ test('urlencoded formData', (t, done) => { fetch(`http://localhost:${server.address().port}`) .then(res => res.formData()) .then(formData => { - strictEqual(formData.get('field1'), 'value1') - strictEqual(formData.get('field2'), 'value2') + t.assert.strictEqual(formData.get('field1'), 'value1') + t.assert.strictEqual(formData.get('field2'), 'value2') }) .finally(done) }) }) test('text with BOM', (t, done) => { - const { strictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'application/x-www-form-urlencoded') @@ -332,14 +330,14 @@ test('text with BOM', (t, done) => { fetch(`http://localhost:${server.address().port}`) .then(res => res.text()) .then(text => { - strictEqual(text, 'test=\uFEFF') + t.assert.strictEqual(text, 'test=\uFEFF') }) .finally(done) }) }) test('formData with BOM', (t, done) => { - const { strictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('content-type', 'application/x-www-form-urlencoded') @@ -351,14 +349,14 @@ test('formData with BOM', (t, done) => { fetch(`http://localhost:${server.address().port}`) .then(res => res.formData()) .then(formData => { - strictEqual(formData.get('\uFEFFtest'), '\uFEFF') + t.assert.strictEqual(formData.get('\uFEFFtest'), '\uFEFF') }) .finally(done) }) }) test('locked blob body', (t, done) => { - const { strictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.end() @@ -369,14 +367,14 @@ test('locked blob body', (t, done) => { const res = await fetch(`http://localhost:${server.address().port}`) const reader = res.body.getReader() res.blob().catch(err => { - strictEqual(err.message, 'Body is unusable: Body has already been read') + t.assert.strictEqual(err.message, 'Body is unusable: Body has already been read') reader.cancel() }).finally(done) }) }) test('disturbed blob body', (t, done) => { - const { ok, strictEqual } = tspl(t, { plan: 2 }) + t.plan(2) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.end() @@ -386,17 +384,17 @@ test('disturbed blob body', (t, done) => { server.listen(0, async () => { const res = await fetch(`http://localhost:${server.address().port}`) await res.blob().then(() => { - ok(true) + t.assert.ok(true) }) await res.blob().catch(err => { - strictEqual(err.message, 'Body is unusable: Body has already been read') + t.assert.strictEqual(err.message, 'Body is unusable: Body has already been read') }) done() }) }) test('redirect with body', (t, done) => { - const { strictEqual } = tspl(t, { plan: 3 }) + t.plan(3) let count = 0 const server = createServer({ joinDuplicateHeaders: true }, async (req, res) => { @@ -404,7 +402,7 @@ test('redirect with body', (t, done) => { for await (const chunk of req) { body += chunk } - strictEqual(body, 'asd') + t.assert.strictEqual(body, 'asd') if (count++ === 0) { res.setHeader('location', 'asd') res.statusCode = 302 @@ -420,13 +418,13 @@ test('redirect with body', (t, done) => { method: 'PUT', body: 'asd' }) - strictEqual(await res.text(), '2') + t.assert.strictEqual(await res.text(), '2') done() }) }) test('redirect with stream', (t, done) => { - const { strictEqual } = tspl(t, { plan: 3 }) + t.plan(3) const location = '/asd' const body = 'hello!' @@ -447,15 +445,15 @@ test('redirect with stream', (t, done) => { const res = await fetch(`http://localhost:${server.address().port}`, { redirect: 'manual' }) - strictEqual(res.status, 302) - strictEqual(res.headers.get('location'), location) - strictEqual(await res.text(), body) + t.assert.strictEqual(res.status, 302) + t.assert.strictEqual(res.headers.get('location'), location) + t.assert.strictEqual(await res.text(), body) done() }) }) test('fail to extract locked body', (t) => { - const { strictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const stream = new ReadableStream({}) const reader = stream.getReader() @@ -463,13 +461,13 @@ test('fail to extract locked body', (t) => { // eslint-disable-next-line new Response(stream) } catch (err) { - strictEqual(err.name, 'TypeError') + t.assert.strictEqual(err.name, 'TypeError') } reader.cancel() }) test('fail to extract locked body', (t) => { - const { strictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const stream = new ReadableStream({}) const reader = stream.getReader() @@ -481,13 +479,13 @@ test('fail to extract locked body', (t) => { keepalive: true }) } catch (err) { - strictEqual(err.message, 'keepalive') + t.assert.strictEqual(err.message, 'keepalive') } reader.cancel() }) test('post FormData with Blob', (t, done) => { - const { ok } = tspl(t, { plan: 1 }) + t.plan(1) const body = new FormData() body.append('field1', new Blob(['asd1'])) @@ -502,13 +500,13 @@ test('post FormData with Blob', (t, done) => { method: 'PUT', body }) - ok(/asd1/.test(await res.text())) + t.assert.ok(/asd1/.test(await res.text())) done() }) }) test('post FormData with File', (t, done) => { - const { ok } = tspl(t, { plan: 2 }) + t.plan(2) const body = new FormData() body.append('field1', new File(['asd1'], 'filename123')) @@ -524,24 +522,24 @@ test('post FormData with File', (t, done) => { body }) const result = await res.text() - ok(/asd1/.test(result)) - ok(/filename123/.test(result)) + t.assert.ok(/asd1/.test(result)) + t.assert.ok(/filename123/.test(result)) done() }) }) test('invalid url', async (t) => { - const { match } = tspl(t, { plan: 1 }) + t.plan(1) try { await fetch('http://invalid') } catch (e) { - match(e.cause.message, /invalid/) + t.assert.match(e.cause.message, /invalid/) } }) test('custom agent', (t, done) => { - const { ok, deepStrictEqual } = tspl(t, { plan: 2 }) + t.plan(2) const obj = { asd: true } const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { @@ -556,19 +554,19 @@ test('custom agent', (t, done) => { }) const oldDispatch = dispatcher.dispatch dispatcher.dispatch = function (options, handler) { - ok(true) + t.assert.ok(true) return oldDispatch.call(this, options, handler) } const body = await fetch(`http://localhost:${server.address().port}`, { dispatcher }) - deepStrictEqual(obj, await body.json()) + t.assert.deepStrictEqual(obj, await body.json()) done() }) }) test('custom agent node fetch', (t, done) => { - const { ok, deepStrictEqual } = tspl(t, { plan: 2 }) + t.plan(2) const obj = { asd: true } const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { @@ -583,13 +581,13 @@ test('custom agent node fetch', (t, done) => { }) const oldDispatch = dispatcher.dispatch dispatcher.dispatch = function (options, handler) { - ok(true) + t.assert.ok(true) return oldDispatch.call(this, options, handler) } const body = await nodeFetch.fetch(`http://localhost:${server.address().port}`, { dispatcher }) - deepStrictEqual(obj, await body.json()) + t.assert.deepStrictEqual(obj, await body.json()) done() }) }) @@ -606,7 +604,7 @@ test('error on redirect', (t, done) => { redirect: 'error' }).catch((e) => e.cause) - assert.strictEqual(errorCause.message, 'unexpected redirect') + t.assert.strictEqual(errorCause.message, 'unexpected redirect') done() }) }) @@ -614,7 +612,7 @@ test('error on redirect', (t, done) => { // https://github.com/nodejs/undici/issues/1527 test('fetching with Request object - issue #1527', async (t) => { const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - assert.ok(true) + t.assert.ok(true) res.end() }).listen(0) @@ -627,16 +625,16 @@ test('fetching with Request object - issue #1527', async (t) => { body }) - await assert.doesNotReject(fetch(request)) + await t.assert.doesNotReject(fetch(request)) }) test('do not decode redirect body', (t, done) => { - const { ok, strictEqual } = tspl(t, { plan: 3 }) + t.plan(3) const obj = { asd: true } const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { if (req.url === '/resource') { - ok(true) + t.assert.ok(true) res.statusCode = 301 res.setHeader('location', '/resource/') // Some dumb http servers set the content-encoding gzip @@ -645,7 +643,7 @@ test('do not decode redirect body', (t, done) => { res.end() return } - ok(true) + t.assert.ok(true) res.setHeader('content-encoding', 'gzip') res.end(gzipSync(JSON.stringify(obj))) }) @@ -653,17 +651,17 @@ test('do not decode redirect body', (t, done) => { server.listen(0, async () => { const body = await fetch(`http://localhost:${server.address().port}/resource`) - strictEqual(JSON.stringify(obj), await body.text()) + t.assert.strictEqual(JSON.stringify(obj), await body.text()) done() }) }) test('decode non-redirect body with location header', (t, done) => { - const { ok, strictEqual } = tspl(t, { plan: 2 }) + t.plan(2) const obj = { asd: true } const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - ok(true) + t.assert.ok(true) res.statusCode = 201 res.setHeader('location', '/resource/') res.setHeader('content-encoding', 'gzip') @@ -673,7 +671,7 @@ test('decode non-redirect body with location header', (t, done) => { server.listen(0, async () => { const body = await fetch(`http://localhost:${server.address().port}/resource`) - strictEqual(JSON.stringify(obj), await body.text()) + t.assert.strictEqual(JSON.stringify(obj), await body.text()) done() }) }) @@ -705,6 +703,6 @@ test('Receiving non-Latin1 headers', async (t) => { .map(([, v]) => v) const lengths = cdHeaders.map(h => h.length) - assert.deepStrictEqual(cdHeaders, ContentDisposition) - assert.deepStrictEqual(lengths, [30, 34, 94, 104, 90]) + t.assert.deepStrictEqual(cdHeaders, ContentDisposition) + t.assert.deepStrictEqual(lengths, [30, 34, 94, 104, 90]) }) diff --git a/test/fetch/client-node-max-header-size.js b/test/fetch/client-node-max-header-size.js index 533d2377737..a6d9a2db029 100644 --- a/test/fetch/client-node-max-header-size.js +++ b/test/fetch/client-node-max-header-size.js @@ -1,6 +1,5 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { exec } = require('node:child_process') const { once } = require('node:events') const { createServer } = require('node:http') @@ -23,23 +22,23 @@ describe('fetch respects --max-http-header-size', () => { after(() => server.close()) - test("respect Node.js' --max-http-header-size", async (t) => { - t = tspl(t, { plan: 6 }) + test("respect Node.js' --max-http-header-size", (t, done) => { + t.plan(6) const command = 'node -e "require(\'./undici-fetch.js\').fetch(\'http://localhost:' + server.address().port + '\')"' exec(`${command} --max-http-header-size=1`, { stdio: 'pipe' }, (err, stdout, stderr) => { - t.strictEqual(err.code, 1) - t.strictEqual(stdout, '') - t.match(stderr, /UND_ERR_HEADERS_OVERFLOW/, '--max-http-header-size=1 should throw') - }) + t.assert.strictEqual(err.code, 1) + t.assert.strictEqual(stdout, '') + t.assert.match(stderr, /UND_ERR_HEADERS_OVERFLOW/, '--max-http-header-size=1 should throw') - exec(command, { stdio: 'pipe' }, (err, stdout, stderr) => { - t.ifError(err) - t.strictEqual(stdout, '') - t.strictEqual(stderr, '', 'default max-http-header-size should not throw') - }) + exec(command, { stdio: 'pipe' }, (err, stdout, stderr) => { + t.assert.ifError(err) + t.assert.strictEqual(stdout, '') + t.assert.strictEqual(stderr, '', 'default max-http-header-size should not throw') - await t.completed + done() + }) + }) }) }) diff --git a/test/fetch/content-length.js b/test/fetch/content-length.js index a85fa0b23a5..7c430b9578d 100644 --- a/test/fetch/content-length.js +++ b/test/fetch/content-length.js @@ -1,7 +1,6 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') const { createServer } = require('node:http') const { once } = require('node:events') const { fetch, FormData } = require('../..') @@ -11,8 +10,8 @@ const { closeServerAsPromise } = require('../utils/node-http') test('Content-Length is set when using a FormData body with fetch', async (t) => { const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { // TODO: check the length's value once the boundary has a fixed length - assert.ok('content-length' in req.headers) // request has content-length header - assert.ok(!Number.isNaN(Number(req.headers['content-length']))) + t.assert.ok('content-length' in req.headers) // request has content-length header + t.assert.ok(!Number.isNaN(Number(req.headers['content-length']))) res.end() }).listen(0) diff --git a/test/fetch/cookies.js b/test/fetch/cookies.js index 25d2838315a..7ac6ca835db 100644 --- a/test/fetch/cookies.js +++ b/test/fetch/cookies.js @@ -1,6 +1,5 @@ 'use strict' -const { strictEqual, deepStrictEqual } = require('node:assert').strict const { once } = require('node:events') const { createServer } = require('node:http') const { test, describe, before, after } = require('node:test') @@ -29,24 +28,24 @@ describe('cookies', () => { return once(server, 'close') }) - test('Can receive set-cookie headers from a server using fetch - issue #1262', async () => { + test('Can receive set-cookie headers from a server using fetch - issue #1262', async (t) => { const query = qsStringify({ 'set-cookie': 'name=value; Domain=example.com' }) const response = await fetch(`http://localhost:${server.address().port}?${query}`) - strictEqual(response.headers.get('set-cookie'), 'name=value; Domain=example.com') - strictEqual(await response.text(), '') + t.assert.strictEqual(response.headers.get('set-cookie'), 'name=value; Domain=example.com') + t.assert.strictEqual(await response.text(), '') const response2 = await fetch(`http://localhost:${server.address().port}?${query}`, { credentials: 'include' }) - strictEqual(response2.headers.get('set-cookie'), 'name=value; Domain=example.com') - strictEqual(await response2.text(), '') + t.assert.strictEqual(response2.headers.get('set-cookie'), 'name=value; Domain=example.com') + t.assert.strictEqual(await response2.text(), '') }) - test('Can send cookies to a server with fetch - issue #1463', async () => { + test('Can send cookies to a server with fetch - issue #1463', async (t) => { const headersInit = [ new Headers([['cookie', 'value']]), { cookie: 'value' }, @@ -56,11 +55,11 @@ describe('cookies', () => { for (const headers of headersInit) { const response = await fetch(`http://localhost:${server.address().port}`, { headers }) const text = await response.text() - strictEqual(text, 'value') + t.assert.strictEqual(text, 'value') } }) - test('Cookie header is delimited with a semicolon rather than a comma - issue #1905', async () => { + test('Cookie header is delimited with a semicolon rather than a comma - issue #1905', async (t) => { const response = await fetch(`http://localhost:${server.address().port}`, { headers: [ ['cookie', 'FOO=lorem-ipsum-dolor-sit-amet'], @@ -68,10 +67,10 @@ describe('cookies', () => { ] }) - strictEqual(await response.text(), 'FOO=lorem-ipsum-dolor-sit-amet; BAR=the-quick-brown-fox') + t.assert.strictEqual(await response.text(), 'FOO=lorem-ipsum-dolor-sit-amet; BAR=the-quick-brown-fox') }) - test('Can receive set-cookie headers from a http2 server using fetch - issue #2885', async () => { + test('Can receive set-cookie headers from a http2 server using fetch - issue #2885', async (t) => { const server = createSecureServer(pem) server.on('stream', (stream, headers) => { stream.respond({ @@ -105,8 +104,8 @@ describe('cookies', () => { } ) - deepStrictEqual(response.headers.getSetCookie(), ['Space=Cat; Secure; HttpOnly']) - strictEqual(await response.text(), 'test') + t.assert.deepStrictEqual(response.headers.getSetCookie(), ['Space=Cat; Secure; HttpOnly']) + t.assert.strictEqual(await response.text(), 'test') await client.close() await new Promise((resolve, reject) => server.close(err => err ? reject(err) : resolve())) diff --git a/test/fetch/data-uri.js b/test/fetch/data-uri.js index 42cdb83708b..e0370296bc9 100644 --- a/test/fetch/data-uri.js +++ b/test/fetch/data-uri.js @@ -1,8 +1,6 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') -const { tspl } = require('@matteo.collina/tspl') const { URLSerializer, stringPercentDecode, @@ -12,44 +10,44 @@ const { const { fetch } = require('../..') test('https://url.spec.whatwg.org/#concept-url-serializer', async (t) => { - await t.test('url scheme gets appended', () => { + await t.test('url scheme gets appended', (t) => { const url = new URL('https://www.google.com/') const serialized = URLSerializer(url) - assert.ok(serialized.startsWith(url.protocol)) + t.assert.ok(serialized.startsWith(url.protocol)) }) - await t.test('non-null url host with authentication', () => { + await t.test('non-null url host with authentication', (t) => { const url = new URL('https://username:password@google.com') const serialized = URLSerializer(url) - assert.ok(serialized.includes(`//${url.username}:${url.password}`)) - assert.ok(serialized.endsWith('@google.com/')) + t.assert.ok(serialized.includes(`//${url.username}:${url.password}`)) + t.assert.ok(serialized.endsWith('@google.com/')) }) - await t.test('null url host', () => { + await t.test('null url host', (t) => { for (const url of ['web+demo:/.//not-a-host/', 'web+demo:/path/..//not-a-host/']) { - assert.strictEqual( + t.assert.strictEqual( URLSerializer(new URL(url)), 'web+demo:/.//not-a-host/' ) } }) - await t.test('url with query works', () => { - assert.strictEqual( + await t.test('url with query works', (t) => { + t.assert.strictEqual( URLSerializer(new URL('https://www.google.com/?fetch=undici')), 'https://www.google.com/?fetch=undici' ) }) - await t.test('exclude fragment', () => { - assert.strictEqual( + await t.test('exclude fragment', (t) => { + t.assert.strictEqual( URLSerializer(new URL('https://www.google.com/#frag')), 'https://www.google.com/#frag' ) - assert.strictEqual( + t.assert.strictEqual( URLSerializer(new URL('https://www.google.com/#frag'), true), 'https://www.google.com/' ) @@ -57,46 +55,46 @@ test('https://url.spec.whatwg.org/#concept-url-serializer', async (t) => { }) test('https://url.spec.whatwg.org/#string-percent-decode', async (t) => { - await t.test('encodes %{2} in range properly', () => { + await t.test('encodes %{2} in range properly', (t) => { const input = '%FF' const percentDecoded = stringPercentDecode(input) - assert.deepStrictEqual(percentDecoded, new Uint8Array([255])) + t.assert.deepStrictEqual(percentDecoded, new Uint8Array([255])) }) - await t.test('encodes %{2} not in range properly', () => { + await t.test('encodes %{2} not in range properly', (t) => { const input = 'Hello %XD World' const percentDecoded = stringPercentDecode(input) const expected = [...input].map(c => c.charCodeAt(0)) - assert.deepStrictEqual(percentDecoded, new Uint8Array(expected)) + t.assert.deepStrictEqual(percentDecoded, new Uint8Array(expected)) }) - await t.test('normal string works', () => { + await t.test('normal string works', (t) => { const input = 'Hello world' const percentDecoded = stringPercentDecode(input) const expected = [...input].map(c => c.charCodeAt(0)) - assert.deepStrictEqual(percentDecoded, Uint8Array.from(expected)) + t.assert.deepStrictEqual(percentDecoded, Uint8Array.from(expected)) }) }) -test('https://mimesniff.spec.whatwg.org/#parse-a-mime-type', () => { - assert.deepStrictEqual(parseMIMEType('text/plain'), { +test('https://mimesniff.spec.whatwg.org/#parse-a-mime-type', (t) => { + t.assert.deepStrictEqual(parseMIMEType('text/plain'), { type: 'text', subtype: 'plain', parameters: new Map(), essence: 'text/plain' }) - assert.deepStrictEqual(parseMIMEType('text/html;charset="shift_jis"iso-2022-jp'), { + t.assert.deepStrictEqual(parseMIMEType('text/html;charset="shift_jis"iso-2022-jp'), { type: 'text', subtype: 'html', parameters: new Map([['charset', 'shift_jis']]), essence: 'text/html' }) - assert.deepStrictEqual(parseMIMEType('application/javascript'), { + t.assert.deepStrictEqual(parseMIMEType('application/javascript'), { type: 'application', subtype: 'javascript', parameters: new Map(), @@ -106,30 +104,30 @@ test('https://mimesniff.spec.whatwg.org/#parse-a-mime-type', () => { test('https://fetch.spec.whatwg.org/#collect-an-http-quoted-string', async (t) => { // https://fetch.spec.whatwg.org/#example-http-quoted-string - await t.test('first', () => { + await t.test('first', (t) => { const position = { position: 0 } - assert.strictEqual(collectAnHTTPQuotedString('"\\', { + t.assert.strictEqual(collectAnHTTPQuotedString('"\\', { position: 0 }), '"\\') - assert.strictEqual(collectAnHTTPQuotedString('"\\', position, true), '\\') - assert.strictEqual(position.position, 2) + t.assert.strictEqual(collectAnHTTPQuotedString('"\\', position, true), '\\') + t.assert.strictEqual(position.position, 2) }) - await t.test('second', () => { + await t.test('second', (t) => { const position = { position: 0 } const input = '"Hello" World' - assert.strictEqual(collectAnHTTPQuotedString(input, { + t.assert.strictEqual(collectAnHTTPQuotedString(input, { position: 0 }), '"Hello"') - assert.strictEqual(collectAnHTTPQuotedString(input, position, true), 'Hello') - assert.strictEqual(position.position, 7) + t.assert.strictEqual(collectAnHTTPQuotedString(input, position, true), 'Hello') + t.assert.strictEqual(position.position, 7) }) }) // https://github.com/nodejs/undici/issues/1574 -test('too long base64 url', async () => { +test('too long base64 url', async (t) => { const inputStr = 'a'.repeat(1 << 20) const base64 = Buffer.from(inputStr).toString('base64') const dataURIPrefix = 'data:application/octet-stream;base64,' @@ -138,43 +136,43 @@ test('too long base64 url', async () => { const res = await fetch(dataURL) const buf = await res.arrayBuffer() const outputStr = Buffer.from(buf).toString('ascii') - assert.strictEqual(outputStr, inputStr) + t.assert.strictEqual(outputStr, inputStr) } catch (e) { - assert.fail(`failed to fetch ${dataURL}`) + t.assert.fail(`failed to fetch ${dataURL}`) } }) test('https://domain.com/#', (t) => { - const { strictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const domain = 'https://domain.com/#a' const serialized = URLSerializer(new URL(domain)) - strictEqual(serialized, domain) + t.assert.strictEqual(serialized, domain) }) test('https://domain.com/?', (t) => { - const { strictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const domain = 'https://domain.com/?a=b' const serialized = URLSerializer(new URL(domain)) - strictEqual(serialized, domain) + t.assert.strictEqual(serialized, domain) }) // https://github.com/nodejs/undici/issues/2474 test('hash url', (t) => { - const { strictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const domain = 'https://domain.com/#a#b' const url = new URL(domain) const serialized = URLSerializer(url, true) - strictEqual(serialized, url.href.substring(0, url.href.length - url.hash.length)) + t.assert.strictEqual(serialized, url.href.substring(0, url.href.length - url.hash.length)) }) // https://github.com/nodejs/undici/issues/2474 test('data url that includes the hash', async (t) => { - const { strictEqual, fail } = tspl(t, { plan: 1 }) + t.plan(1) const dataURL = 'data:,node#js#' try { const res = await fetch(dataURL) - strictEqual(await res.text(), 'node') + t.assert.strictEqual(await res.text(), 'node') } catch (error) { - fail(`failed to fetch ${dataURL}`) + t.assert.fail(`failed to fetch ${dataURL}`) } }) diff --git a/test/fetch/encoding.js b/test/fetch/encoding.js index 9ba0a6f6ca4..06b78031ac2 100644 --- a/test/fetch/encoding.js +++ b/test/fetch/encoding.js @@ -1,6 +1,5 @@ 'use strict' -const { strictEqual } = require('node:assert').strict const { once } = require('node:events') const { createServer } = require('node:http') const { test, before, after, describe } = require('node:test') @@ -60,9 +59,9 @@ describe('content-encoding handling', () => { headers: { 'accept-encoding': 'deflate, gzip' } }) - strictEqual(response.headers.get('content-encoding'), 'deflate, gzip') - strictEqual(response.headers.get('content-type'), 'text/plain') - strictEqual(await response.text(), 'Hello, World!') + t.assert.strictEqual(response.headers.get('content-encoding'), 'deflate, gzip') + t.assert.strictEqual(response.headers.get('content-type'), 'text/plain') + t.assert.strictEqual(await response.text(), 'Hello, World!') }) test('content-encoding header is case-iNsENsITIve', async (t) => { @@ -71,21 +70,21 @@ describe('content-encoding handling', () => { headers: { 'accept-encoding': 'DeFlAtE, GzIp' } }) - strictEqual(response.headers.get('content-encoding'), 'deflate, gzip') - strictEqual(response.headers.get('content-type'), 'text/plain') - strictEqual(await response.text(), 'Hello, World!') + t.assert.strictEqual(response.headers.get('content-encoding'), 'deflate, gzip') + t.assert.strictEqual(response.headers.get('content-type'), 'text/plain') + t.assert.strictEqual(await response.text(), 'Hello, World!') }) test('should decompress zstandard response', { skip: typeof require('node:zlib').createZstdDecompress !== 'function' }, - async () => { + async (t) => { const response = await fetch(`http://localhost:${server.address().port}`, { keepalive: false, headers: { 'accept-encoding': 'zstd' } }) - strictEqual(response.headers.get('content-encoding'), 'zstd') - strictEqual(response.headers.get('content-type'), 'text/plain') - strictEqual(await response.text(), 'Hello, World!') + t.assert.strictEqual(response.headers.get('content-encoding'), 'zstd') + t.assert.strictEqual(response.headers.get('content-type'), 'text/plain') + t.assert.strictEqual(await response.text(), 'Hello, World!') }) }) diff --git a/test/fetch/exiting.js b/test/fetch/exiting.js index 746a7fd97ee..223af588c59 100644 --- a/test/fetch/exiting.js +++ b/test/fetch/exiting.js @@ -4,23 +4,26 @@ const { test } = require('node:test') const { fetch } = require('../..') const { createServer } = require('node:http') const { closeServerAsPromise } = require('../utils/node-http') -const tspl = require('@matteo.collina/tspl') +const { once } = require('node:events') +const { createDeferredPromise } = require('../../lib/util/promise') test('abort the request on the other side if the stream is canceled', async (t) => { - const p = tspl(t, { plan: 1 }) + t.plan(1) + + const promise = createDeferredPromise() + const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.writeHead(200) res.write('hello') req.on('aborted', () => { - p.ok('aborted') + t.assert.ok('aborted') + promise.resolve() }) // Let's not end the response on purpose }) t.after(closeServerAsPromise(server)) - await new Promise((resolve) => { - server.listen(0, resolve) - }) + await once(server.listen(0), 'listening') const url = new URL(`http://127.0.0.1:${server.address().port}`) @@ -35,5 +38,5 @@ test('abort the request on the other side if the stream is canceled', async (t) await response.body.cancel() } - await p.completed + await promise.promise }) diff --git a/test/fetch/export-env-proxy-agent.js b/test/fetch/export-env-proxy-agent.js index 933a6bb530d..a40a48566ee 100644 --- a/test/fetch/export-env-proxy-agent.js +++ b/test/fetch/export-env-proxy-agent.js @@ -1,15 +1,14 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') const undiciFetch = require('../../undici-fetch') -test('EnvHttpProxyAgent should be part of Node.js bundle', () => { - assert.strictEqual(typeof undiciFetch.EnvHttpProxyAgent, 'function') - assert.strictEqual(typeof undiciFetch.getGlobalDispatcher, 'function') - assert.strictEqual(typeof undiciFetch.setGlobalDispatcher, 'function') +test('EnvHttpProxyAgent should be part of Node.js bundle', (t) => { + t.assert.strictEqual(typeof undiciFetch.EnvHttpProxyAgent, 'function') + t.assert.strictEqual(typeof undiciFetch.getGlobalDispatcher, 'function') + t.assert.strictEqual(typeof undiciFetch.setGlobalDispatcher, 'function') const agent = new undiciFetch.EnvHttpProxyAgent() undiciFetch.setGlobalDispatcher(agent) - assert.strictEqual(undiciFetch.getGlobalDispatcher(), agent) + t.assert.strictEqual(undiciFetch.getGlobalDispatcher(), agent) }) diff --git a/test/fetch/fetch-leak.js b/test/fetch/fetch-leak.js index 761a63f9700..aa467763a24 100644 --- a/test/fetch/fetch-leak.js +++ b/test/fetch/fetch-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 { createServer } = require('node:http') const { closeServerAsPromise } = require('../utils/node-http') @@ -13,7 +11,7 @@ test('do not leak', (t, done) => { if (!hasGC) { throw new Error('gc is not available. Run with \'--expose-gc\'.') } - const { ok } = tspl(t, { plan: 1 }) + t.plan(1) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.end() }) @@ -40,10 +38,10 @@ test('do not leak', (t, done) => { global.gc() const next = process.memoryUsage().heapUsed if (next <= prev) { - ok(true) + t.assert.ok(true) done() } else if (count++ > 20) { - assert.fail() + t.assert.fail() } else { prev = next } diff --git a/test/fetch/fetch-timeouts.js b/test/fetch/fetch-timeouts.js index 41f9484e01d..83eb6bbeba2 100644 --- a/test/fetch/fetch-timeouts.js +++ b/test/fetch/fetch-timeouts.js @@ -1,7 +1,6 @@ 'use strict' const { test } = require('node:test') -const { tspl } = require('@matteo.collina/tspl') const { fetch, Agent } = require('../..') const timers = require('../../lib/util/timers') @@ -13,7 +12,7 @@ test('Fetch very long request, timeout overridden so no error', (t, done) => { const minutes = 6 const msToDelay = 1000 * 60 * minutes - const { strictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const clock = FakeTimers.install() t.after(clock.uninstall.bind(clock)) @@ -44,7 +43,7 @@ test('Fetch very long request, timeout overridden so no error', (t, done) => { }) .then((response) => response.text()) .then((response) => { - strictEqual('hello', response) + t.assert.strictEqual('hello', response) done() }) .catch((err) => { diff --git a/test/fetch/fetch-url-after-redirect.js b/test/fetch/fetch-url-after-redirect.js index c24c092e15b..0500c3cc492 100644 --- a/test/fetch/fetch-url-after-redirect.js +++ b/test/fetch/fetch-url-after-redirect.js @@ -1,6 +1,5 @@ 'use strict' -const assert = require('node:assert') const { test } = require('node:test') const { createServer } = require('node:http') const { fetch } = require('../..') @@ -36,7 +35,7 @@ test('after redirecting the url of the response is set to the target url', async const { port } = server.address() const response = await fetch(`http://127.0.0.1:${port}/redirect-1`) - assert.strictEqual(response.url, `http://127.0.0.1:${port}/target`) + t.assert.strictEqual(response.url, `http://127.0.0.1:${port}/target`) }) test('location header with non-ASCII character redirects to a properly encoded url', async (t) => { @@ -57,5 +56,5 @@ test('location header with non-ASCII character redirects to a properly encoded u const { port } = server.address() const response = await fetch(`http://127.0.0.1:${port}/redirect`) - assert.strictEqual(response.url, `http://127.0.0.1:${port}/${encodeURIComponent('안녕')}`) + t.assert.strictEqual(response.url, `http://127.0.0.1:${port}/${encodeURIComponent('안녕')}`) }) diff --git a/test/fetch/formdata-inspect-custom.js b/test/fetch/formdata-inspect-custom.js index 4fb70069439..fcf67175bf1 100644 --- a/test/fetch/formdata-inspect-custom.js +++ b/test/fetch/formdata-inspect-custom.js @@ -3,14 +3,13 @@ const { FormData } = require('../../') const { inspect } = require('node:util') const { test } = require('node:test') -const assert = require('node:assert') -test('FormData class custom inspection', () => { +test('FormData class custom inspection', (t) => { const formData = new FormData() formData.append('username', 'john_doe') formData.append('email', 'john@example.com') const expectedOutput = "FormData {\n username: 'john_doe',\n email: 'john@example.com'\n}" - assert.deepStrictEqual(inspect(formData), expectedOutput) + t.assert.deepStrictEqual(inspect(formData), expectedOutput) }) diff --git a/test/fetch/formdata.js b/test/fetch/formdata.js index 97f91ca0b10..5c0b721d281 100644 --- a/test/fetch/formdata.js +++ b/test/fetch/formdata.js @@ -1,163 +1,161 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') -const { tspl } = require('@matteo.collina/tspl') const { FormData, Response, Request } = require('../../') const { isFormDataLike } = require('../../lib/core/util') -test('arg validation', () => { +test('arg validation', (t) => { const form = new FormData() // constructor - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line new FormData('asd') }, TypeError) // append - assert.throws(() => { + t.assert.throws(() => { FormData.prototype.append.call(null) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { form.append() }, TypeError) - assert.throws(() => { + t.assert.throws(() => { form.append('k', 'not usv', '') }, TypeError) // delete - assert.throws(() => { + t.assert.throws(() => { FormData.prototype.delete.call(null) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { form.delete() }, TypeError) // get - assert.throws(() => { + t.assert.throws(() => { FormData.prototype.get.call(null) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { form.get() }, TypeError) // getAll - assert.throws(() => { + t.assert.throws(() => { FormData.prototype.getAll.call(null) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { form.getAll() }, TypeError) // has - assert.throws(() => { + t.assert.throws(() => { FormData.prototype.has.call(null) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { form.has() }, TypeError) // set - assert.throws(() => { + t.assert.throws(() => { FormData.prototype.set.call(null) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { form.set('k') }, TypeError) - assert.throws(() => { + t.assert.throws(() => { form.set('k', 'not usv', '') }, TypeError) // iterator - assert.throws(() => { + t.assert.throws(() => { Reflect.apply(FormData.prototype[Symbol.iterator], null) }, TypeError) // toStringTag - assert.doesNotThrow(() => { + t.assert.doesNotThrow(() => { FormData.prototype[Symbol.toStringTag].charAt(0) }) }) -test('set blob', () => { +test('set blob', (t) => { const form = new FormData() form.set('key', new Blob([]), undefined) - assert.strictEqual(form.get('key').name, 'blob') + t.assert.strictEqual(form.get('key').name, 'blob') form.set('key1', new Blob([]), null) - assert.strictEqual(form.get('key1').name, 'null') + t.assert.strictEqual(form.get('key1').name, 'null') }) -test('append file', () => { +test('append file', (t) => { const form = new FormData() form.set('asd', new File([], 'asd1', { type: 'text/plain' }), 'asd2') form.append('asd2', new File([], 'asd1'), 'asd2') - assert.strictEqual(form.has('asd'), true) - assert.strictEqual(form.has('asd2'), true) - assert.strictEqual(form.get('asd').name, 'asd2') - assert.strictEqual(form.get('asd2').name, 'asd2') - assert.strictEqual(form.get('asd').type, 'text/plain') + t.assert.strictEqual(form.has('asd'), true) + t.assert.strictEqual(form.has('asd2'), true) + t.assert.strictEqual(form.get('asd').name, 'asd2') + t.assert.strictEqual(form.get('asd2').name, 'asd2') + t.assert.strictEqual(form.get('asd').type, 'text/plain') form.delete('asd') - assert.strictEqual(form.get('asd'), null) - assert.strictEqual(form.has('asd2'), true) - assert.strictEqual(form.has('asd'), false) + t.assert.strictEqual(form.get('asd'), null) + t.assert.strictEqual(form.has('asd2'), true) + t.assert.strictEqual(form.has('asd'), false) }) -test('append blob', async () => { +test('append blob', async (t) => { const form = new FormData() form.set('asd', new Blob(['asd1'], { type: 'text/plain' })) - assert.strictEqual(form.has('asd'), true) - assert.strictEqual(form.get('asd').type, 'text/plain') - assert.strictEqual(await form.get('asd').text(), 'asd1') + t.assert.strictEqual(form.has('asd'), true) + t.assert.strictEqual(form.get('asd').type, 'text/plain') + t.assert.strictEqual(await form.get('asd').text(), 'asd1') form.delete('asd') - assert.strictEqual(form.get('asd'), null) + t.assert.strictEqual(form.get('asd'), null) form.append('key', new Blob([]), undefined) - assert.strictEqual(form.get('key').name, 'blob') + t.assert.strictEqual(form.get('key').name, 'blob') form.append('key1', new Blob([]), null) - assert.strictEqual(form.get('key1').name, 'null') + t.assert.strictEqual(form.get('key1').name, 'null') }) -test('append string', () => { +test('append string', (t) => { const form = new FormData() form.set('k1', 'v1') form.set('k2', 'v2') - assert.deepStrictEqual([...form], [['k1', 'v1'], ['k2', 'v2']]) - assert.strictEqual(form.has('k1'), true) - assert.strictEqual(form.get('k1'), 'v1') + t.assert.deepStrictEqual([...form], [['k1', 'v1'], ['k2', 'v2']]) + t.assert.strictEqual(form.has('k1'), true) + t.assert.strictEqual(form.get('k1'), 'v1') form.append('k1', 'v1+') - assert.deepStrictEqual(form.getAll('k1'), ['v1', 'v1+']) + t.assert.deepStrictEqual(form.getAll('k1'), ['v1', 'v1+']) form.set('k2', 'v1++') - assert.strictEqual(form.get('k2'), 'v1++') + t.assert.strictEqual(form.get('k2'), 'v1++') form.delete('asd') - assert.strictEqual(form.get('asd'), null) + t.assert.strictEqual(form.get('asd'), null) }) test('formData.entries', async (t) => { const form = new FormData() await t.test('with 0 entries', (t) => { - const { deepStrictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const entries = [...form.entries()] - deepStrictEqual(entries, []) + t.assert.deepStrictEqual(entries, []) }) await t.test('with 1+ entries', (t) => { - const { deepStrictEqual } = tspl(t, { plan: 2 }) + t.plan(2) form.set('k1', 'v1') form.set('k2', 'v2') const entries = [...form.entries()] const entries2 = [...form.entries()] - deepStrictEqual(entries, [['k1', 'v1'], ['k2', 'v2']]) - deepStrictEqual(entries, entries2) + t.assert.deepStrictEqual(entries, [['k1', 'v1'], ['k2', 'v2']]) + t.assert.deepStrictEqual(entries, entries2) }) }) @@ -165,22 +163,22 @@ test('formData.keys', async (t) => { const form = new FormData() await t.test('with 0 keys', (t) => { - const { deepStrictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const keys = [...form.entries()] - deepStrictEqual(keys, []) + t.assert.deepStrictEqual(keys, []) }) await t.test('with 1+ keys', (t) => { - const { deepStrictEqual } = tspl(t, { plan: 2 }) + t.plan(2) form.set('k1', 'v1') form.set('k2', 'v2') const keys = [...form.keys()] const keys2 = [...form.keys()] - deepStrictEqual(keys, ['k1', 'k2']) - deepStrictEqual(keys, keys2) + t.assert.deepStrictEqual(keys, ['k1', 'k2']) + t.assert.deepStrictEqual(keys, keys2) }) }) @@ -188,39 +186,39 @@ test('formData.values', async (t) => { const form = new FormData() await t.test('with 0 values', (t) => { - const { deepStrictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const values = [...form.values()] - deepStrictEqual(values, []) + t.assert.deepStrictEqual(values, []) }) await t.test('with 1+ values', (t) => { - const { deepStrictEqual } = tspl(t, { plan: 2 }) + t.plan(2) form.set('k1', 'v1') form.set('k2', 'v2') const values = [...form.values()] const values2 = [...form.values()] - deepStrictEqual(values, ['v1', 'v2']) - deepStrictEqual(values, values2) + t.assert.deepStrictEqual(values, ['v1', 'v2']) + t.assert.deepStrictEqual(values, values2) }) }) test('formData forEach', async (t) => { - await t.test('invalid arguments', () => { - assert.throws(() => { + await t.test('invalid arguments', (t) => { + t.assert.throws(() => { FormData.prototype.forEach.call({}) }, TypeError('Illegal invocation')) - assert.throws(() => { + t.assert.throws(() => { const fd = new FormData() fd.forEach({}) }, TypeError) }) - await t.test('with a callback', () => { + await t.test('with a callback', (t) => { const fd = new FormData() fd.set('a', 'b') @@ -229,48 +227,48 @@ test('formData forEach', async (t) => { let i = 0 fd.forEach((value, key, self) => { if (i++ === 0) { - assert.strictEqual(value, 'b') - assert.strictEqual(key, 'a') + t.assert.strictEqual(value, 'b') + t.assert.strictEqual(key, 'a') } else { - assert.strictEqual(value, 'd') - assert.strictEqual(key, 'c') + t.assert.strictEqual(value, 'd') + t.assert.strictEqual(key, 'c') } - assert.strictEqual(fd, self) + t.assert.strictEqual(fd, self) }) }) - await t.test('with a thisArg', () => { + await t.test('with a thisArg', (t) => { const fd = new FormData() fd.set('b', 'a') fd.forEach(function (value, key, self) { - assert.strictEqual(this, globalThis) - assert.strictEqual(fd, self) - assert.strictEqual(key, 'b') - assert.strictEqual(value, 'a') + t.assert.strictEqual(this, globalThis) + t.assert.strictEqual(fd, self) + t.assert.strictEqual(key, 'b') + t.assert.strictEqual(value, 'a') }) const thisArg = Symbol('thisArg') fd.forEach(function () { - assert.strictEqual(this, thisArg) + t.assert.strictEqual(this, thisArg) }, thisArg) }) }) -test('formData toStringTag', () => { +test('formData toStringTag', (t) => { const form = new FormData() - assert.strictEqual(form[Symbol.toStringTag], 'FormData') - assert.strictEqual(FormData.prototype[Symbol.toStringTag], 'FormData') + t.assert.strictEqual(form[Symbol.toStringTag], 'FormData') + t.assert.strictEqual(FormData.prototype[Symbol.toStringTag], 'FormData') }) -test('formData.constructor.name', () => { +test('formData.constructor.name', (t) => { const form = new FormData() - assert.strictEqual(form.constructor.name, 'FormData') + t.assert.strictEqual(form.constructor.name, 'FormData') }) test('formData should be an instance of FormData', async (t) => { - await t.test('Invalid class FormData', () => { + await t.test('Invalid class FormData', (t) => { class FormData { constructor () { this.data = [] @@ -286,10 +284,10 @@ test('formData should be an instance of FormData', async (t) => { } const form = new FormData() - assert.strictEqual(isFormDataLike(form), false) + t.assert.strictEqual(isFormDataLike(form), false) }) - await t.test('Invalid function FormData', () => { + await t.test('Invalid function FormData', (t) => { function FormData () { const data = [] return { @@ -303,17 +301,17 @@ test('formData should be an instance of FormData', async (t) => { } const form = new FormData() - assert.strictEqual(isFormDataLike(form), false) + t.assert.strictEqual(isFormDataLike(form), false) }) - await t.test('Valid FormData', () => { + await t.test('Valid FormData', (t) => { const form = new FormData() - assert.strictEqual(isFormDataLike(form), true) + t.assert.strictEqual(isFormDataLike(form), true) }) }) test('FormData should be compatible with third-party libraries', (t) => { - const { strictEqual } = tspl(t, { plan: 1 }) + t.plan(1) class FormData { constructor () { @@ -337,21 +335,21 @@ test('FormData should be compatible with third-party libraries', (t) => { } const form = new FormData() - strictEqual(isFormDataLike(form), true) + t.assert.strictEqual(isFormDataLike(form), true) }) -test('arguments', () => { - assert.strictEqual(FormData.length, 0) - assert.strictEqual(FormData.prototype.append.length, 2) - assert.strictEqual(FormData.prototype.delete.length, 1) - assert.strictEqual(FormData.prototype.get.length, 1) - assert.strictEqual(FormData.prototype.getAll.length, 1) - assert.strictEqual(FormData.prototype.has.length, 1) - assert.strictEqual(FormData.prototype.set.length, 2) +test('arguments', (t) => { + t.assert.strictEqual(FormData.length, 0) + t.assert.strictEqual(FormData.prototype.append.length, 2) + t.assert.strictEqual(FormData.prototype.delete.length, 1) + t.assert.strictEqual(FormData.prototype.get.length, 1) + t.assert.strictEqual(FormData.prototype.getAll.length, 1) + t.assert.strictEqual(FormData.prototype.has.length, 1) + t.assert.strictEqual(FormData.prototype.set.length, 2) }) // https://github.com/nodejs/undici/pull/1814 -test('FormData returned from bodyMixin.formData is not a clone', async () => { +test('FormData returned from bodyMixin.formData is not a clone', async (t) => { const fd = new FormData() fd.set('foo', 'bar') @@ -360,13 +358,13 @@ test('FormData returned from bodyMixin.formData is not a clone', async () => { const fd2 = await res.formData() - assert.strictEqual(fd2.get('foo'), 'bar') - assert.strictEqual(fd.get('foo'), 'foo') + t.assert.strictEqual(fd2.get('foo'), 'bar') + t.assert.strictEqual(fd.get('foo'), 'foo') fd2.set('foo', 'baz') - assert.strictEqual(fd2.get('foo'), 'baz') - assert.strictEqual(fd.get('foo'), 'foo') + t.assert.strictEqual(fd2.get('foo'), 'baz') + t.assert.strictEqual(fd.get('foo'), 'foo') }) test('.formData() with multipart/form-data body that ends with --\r\n', async (t) => { diff --git a/test/fetch/general.js b/test/fetch/general.js index a23554b931b..9e65f4ab039 100644 --- a/test/fetch/general.js +++ b/test/fetch/general.js @@ -1,7 +1,6 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') const { FormData, Headers, @@ -9,7 +8,7 @@ const { Response } = require('../../index') -test('Symbol.toStringTag descriptor', () => { +test('Symbol.toStringTag descriptor', (t) => { for (const cls of [ FormData, Headers, @@ -17,7 +16,7 @@ test('Symbol.toStringTag descriptor', () => { Response ]) { const desc = Object.getOwnPropertyDescriptor(cls.prototype, Symbol.toStringTag) - assert.deepStrictEqual(desc, { + t.assert.deepStrictEqual(desc, { value: cls.name, writable: false, enumerable: false, diff --git a/test/fetch/headers-case.js b/test/fetch/headers-case.js index e0314565bf7..1deb30b593c 100644 --- a/test/fetch/headers-case.js +++ b/test/fetch/headers-case.js @@ -4,14 +4,13 @@ const { fetch, Headers, Request } = require('../..') const { createServer } = require('node:http') const { once } = require('node:events') const { test } = require('node:test') -const { tspl } = require('@matteo.collina/tspl') const { closeServerAsPromise } = require('../utils/node-http') test('Headers retain keys case-sensitive', async (t) => { - const assert = tspl(t, { plan: 4 }) + t.plan(4) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - assert.ok(req.rawHeaders.includes('Content-Type')) + t.assert.ok(req.rawHeaders.includes('Content-Type')) res.end() }).listen(0) diff --git a/test/fetch/headers-inspect-custom.js b/test/fetch/headers-inspect-custom.js index 8145e9d7536..5c5b556a14f 100644 --- a/test/fetch/headers-inspect-custom.js +++ b/test/fetch/headers-inspect-custom.js @@ -2,10 +2,9 @@ const { Headers } = require('../../lib/web/fetch/headers') const { test } = require('node:test') -const assert = require('node:assert') const util = require('node:util') -test('Headers class custom inspection', () => { +test('Headers class custom inspection', (t) => { const headers = new Headers() headers.set('Content-Type', 'application/json') headers.set('Authorization', 'Bearer token') @@ -13,5 +12,5 @@ test('Headers class custom inspection', () => { const inspectedOutput = util.inspect(headers, { depth: 1 }) const expectedOutput = "Headers { 'Content-Type': 'application/json', Authorization: 'Bearer token' }" - assert.strictEqual(inspectedOutput, expectedOutput) + t.assert.strictEqual(inspectedOutput, expectedOutput) }) diff --git a/test/fetch/headers.js b/test/fetch/headers.js index 23d0c363205..a55994cace9 100644 --- a/test/fetch/headers.js +++ b/test/fetch/headers.js @@ -1,8 +1,6 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') -const { tspl } = require('@matteo.collina/tspl') const { Headers, fill, setHeadersGuard } = require('../../lib/web/fetch/headers') const { once } = require('node:events') const { fetch } = require('../..') @@ -11,35 +9,35 @@ const { closeServerAsPromise } = require('../utils/node-http') test('Headers initialization', async (t) => { await t.test('allows undefined', (t) => { - const { doesNotThrow } = tspl(t, { plan: 1 }) + t.plan(1) - doesNotThrow(() => new Headers()) + t.assert.doesNotThrow(() => new Headers()) }) await t.test('with array of header entries', async (t) => { await t.test('fails on invalid array-based init', (t) => { - const { throws } = tspl(t, { plan: 3 }) - throws( + t.plan(3) + t.assert.throws( () => new Headers([['undici', 'fetch'], ['fetch']]), TypeError('Headers constructor: expected name/value pair to be length 2, found 1.') ) - throws(() => new Headers(['undici', 'fetch', 'fetch']), TypeError) - throws( + t.assert.throws(() => new Headers(['undici', 'fetch', 'fetch']), TypeError) + t.assert.throws( () => new Headers([0, 1, 2]), TypeError('Headers constructor: init[0] (0) is not iterable.') ) }) await t.test('allows even length init', (t) => { - const { doesNotThrow } = tspl(t, { plan: 1 }) + t.plan(1) const init = [['undici', 'fetch'], ['fetch', 'undici']] - doesNotThrow(() => new Headers(init)) + t.assert.doesNotThrow(() => new Headers(init)) }) await t.test('fails for event flattened init', (t) => { - const { throws } = tspl(t, { plan: 1 }) + t.plan(1) const init = ['undici', 'fetch', 'fetch', 'undici'] - throws( + t.assert.throws( () => new Headers(init), TypeError('Headers constructor: init[0] ("undici") is not iterable.') ) @@ -47,69 +45,69 @@ test('Headers initialization', async (t) => { }) await t.test('with object of header entries', (t) => { - const { doesNotThrow } = tspl(t, { plan: 1 }) + t.plan(1) const init = { undici: 'fetch', fetch: 'undici' } - doesNotThrow(() => new Headers(init)) + t.assert.doesNotThrow(() => new Headers(init)) }) await t.test('fails silently if a boxed primitive object is passed', (t) => { - const { doesNotThrow } = tspl(t, { plan: 3 }) + t.plan(3) /* eslint-disable no-new-wrappers */ - doesNotThrow(() => new Headers(new Number())) - doesNotThrow(() => new Headers(new Boolean())) - doesNotThrow(() => new Headers(new String())) + t.assert.doesNotThrow(() => new Headers(new Number())) + t.assert.doesNotThrow(() => new Headers(new Boolean())) + t.assert.doesNotThrow(() => new Headers(new String())) /* eslint-enable no-new-wrappers */ }) await t.test('fails if primitive is passed', (t) => { - const { throws } = tspl(t, { plan: 2 }) + t.plan(2) const expectedTypeError = TypeError - throws(() => new Headers(1), expectedTypeError) - throws(() => new Headers('1'), expectedTypeError) + t.assert.throws(() => new Headers(1), expectedTypeError) + t.assert.throws(() => new Headers('1'), expectedTypeError) }) - await t.test('allows some weird stuff (because of webidl)', () => { - assert.doesNotThrow(() => { + await t.test('allows some weird stuff (because of webidl)', (t) => { + t.assert.doesNotThrow(() => { new Headers(function () {}) // eslint-disable-line no-new }) - assert.doesNotThrow(() => { + t.assert.doesNotThrow(() => { new Headers(Function) // eslint-disable-line no-new }) }) await t.test('allows a myriad of header values to be passed', (t) => { - const { doesNotThrow, throws } = tspl(t, { plan: 4 }) + t.plan(4) // Headers constructor uses Headers.append - doesNotThrow(() => new Headers([ + t.assert.doesNotThrow(() => new Headers([ ['a', ['b', 'c']], ['d', ['e', 'f']] ]), 'allows any array values') - doesNotThrow(() => new Headers([ + t.assert.doesNotThrow(() => new Headers([ ['key', null] ]), 'allows null values') - throws(() => new Headers([ + t.assert.throws(() => new Headers([ ['key'] ]), 'throws when 2 arguments are not passed') - throws(() => new Headers([ + t.assert.throws(() => new Headers([ ['key', 'value', 'value2'] ]), 'throws when too many arguments are passed') }) await t.test('accepts headers as objects with array values', (t) => { - const { deepStrictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const headers = new Headers({ c: '5', b: ['3', '4'], a: ['1', '2'] }) - deepStrictEqual([...headers.entries()], [ + t.assert.deepStrictEqual([...headers.entries()], [ ['a', '1,2'], ['b', '3,4'], ['c', '5'] @@ -119,17 +117,17 @@ test('Headers initialization', async (t) => { test('Headers append', async (t) => { await t.test('adds valid header entry to instance', (t) => { - const { doesNotThrow, strictEqual } = tspl(t, { plan: 2 }) + t.plan(2) const headers = new Headers() const name = 'undici' const value = 'fetch' - doesNotThrow(() => headers.append(name, value)) - strictEqual(headers.get(name), value) + t.assert.doesNotThrow(() => headers.append(name, value)) + t.assert.strictEqual(headers.get(name), value) }) await t.test('adds valid header to existing entry', (t) => { - const { strictEqual, doesNotThrow } = tspl(t, { plan: 4 }) + t.plan(4) const headers = new Headers() const name = 'undici' @@ -137,200 +135,200 @@ test('Headers append', async (t) => { const value2 = 'fetch2' const value3 = 'fetch3' headers.append(name, value1) - strictEqual(headers.get(name), value1) - doesNotThrow(() => headers.append(name, value2)) - doesNotThrow(() => headers.append(name, value3)) - strictEqual(headers.get(name), [value1, value2, value3].join(', ')) + t.assert.strictEqual(headers.get(name), value1) + t.assert.doesNotThrow(() => headers.append(name, value2)) + t.assert.doesNotThrow(() => headers.append(name, value3)) + t.assert.strictEqual(headers.get(name), [value1, value2, value3].join(', ')) }) await t.test('throws on invalid entry', (t) => { - const { throws } = tspl(t, { plan: 3 }) + t.plan(3) const headers = new Headers() - throws(() => headers.append(), 'throws on missing name and value') - throws(() => headers.append('undici'), 'throws on missing value') - throws(() => headers.append('invalid @ header ? name', 'valid value'), 'throws on invalid name') + t.assert.throws(() => headers.append(), 'throws on missing name and value') + t.assert.throws(() => headers.append('undici'), 'throws on missing value') + t.assert.throws(() => headers.append('invalid @ header ? name', 'valid value'), 'throws on invalid name') }) }) test('Headers delete', async (t) => { await t.test('deletes valid header entry from instance', (t) => { - const { strictEqual, doesNotThrow } = tspl(t, { plan: 3 }) + t.plan(3) const headers = new Headers() const name = 'undici' const value = 'fetch' headers.append(name, value) - strictEqual(headers.get(name), value) - doesNotThrow(() => headers.delete(name)) - strictEqual(headers.get(name), null) + t.assert.strictEqual(headers.get(name), value) + t.assert.doesNotThrow(() => headers.delete(name)) + t.assert.strictEqual(headers.get(name), null) }) await t.test('does not mutate internal list when no match is found', (t) => { - const { strictEqual, doesNotThrow } = tspl(t, { plan: 3 }) + t.plan(3) const headers = new Headers() const name = 'undici' const value = 'fetch' headers.append(name, value) - strictEqual(headers.get(name), value) - doesNotThrow(() => headers.delete('not-undici')) - strictEqual(headers.get(name), value) + t.assert.strictEqual(headers.get(name), value) + t.assert.doesNotThrow(() => headers.delete('not-undici')) + t.assert.strictEqual(headers.get(name), value) }) await t.test('throws on invalid entry', (t) => { - const { throws } = tspl(t, { plan: 2 }) + t.plan(2) const headers = new Headers() - throws(() => headers.delete(), 'throws on missing namee') - throws(() => headers.delete('invalid @ header ? name'), 'throws on invalid name') + t.assert.throws(() => headers.delete(), 'throws on missing namee') + t.assert.throws(() => headers.delete('invalid @ header ? name'), 'throws on invalid name') }) // https://github.com/nodejs/undici/issues/2429 await t.test('`Headers#delete` returns undefined', (t) => { - const { strictEqual } = tspl(t, { plan: 2 }) + t.plan(2) const headers = new Headers({ test: 'test' }) - strictEqual(headers.delete('test'), undefined) - strictEqual(headers.delete('test2'), undefined) + t.assert.strictEqual(headers.delete('test'), undefined) + t.assert.strictEqual(headers.delete('test2'), undefined) }) }) test('Headers get', async (t) => { await t.test('returns null if not found in instance', (t) => { - const { strictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const headers = new Headers() headers.append('undici', 'fetch') - strictEqual(headers.get('not-undici'), null) + t.assert.strictEqual(headers.get('not-undici'), null) }) await t.test('returns header values from valid header name', (t) => { - const { strictEqual } = tspl(t, { plan: 2 }) + t.plan(2) const headers = new Headers() const name = 'undici'; const value1 = 'fetch1'; const value2 = 'fetch2' headers.append(name, value1) - strictEqual(headers.get(name), value1) + t.assert.strictEqual(headers.get(name), value1) headers.append(name, value2) - strictEqual(headers.get(name), [value1, value2].join(', ')) + t.assert.strictEqual(headers.get(name), [value1, value2].join(', ')) }) await t.test('throws on invalid entry', (t) => { - const { throws } = tspl(t, { plan: 2 }) + t.plan(2) const headers = new Headers() - throws(() => headers.get(), 'throws on missing name') - throws(() => headers.get('invalid @ header ? name'), 'throws on invalid name') + t.assert.throws(() => headers.get(), 'throws on missing name') + t.assert.throws(() => headers.get('invalid @ header ? name'), 'throws on invalid name') }) }) test('Headers has', async (t) => { await t.test('returns boolean existence for a header name', (t) => { - const { strictEqual } = tspl(t, { plan: 2 }) + t.plan(2) const headers = new Headers() const name = 'undici' headers.append('not-undici', 'fetch') - strictEqual(headers.has(name), false) + t.assert.strictEqual(headers.has(name), false) headers.append(name, 'fetch') - strictEqual(headers.has(name), true) + t.assert.strictEqual(headers.has(name), true) }) await t.test('throws on invalid entry', (t) => { - const { throws } = tspl(t, { plan: 2 }) + t.plan(2) const headers = new Headers() - throws(() => headers.has(), 'throws on missing name') - throws(() => headers.has('invalid @ header ? name'), 'throws on invalid name') + t.assert.throws(() => headers.has(), 'throws on missing name') + t.assert.throws(() => headers.has('invalid @ header ? name'), 'throws on invalid name') }) }) test('Headers set', async (t) => { await t.test('sets valid header entry to instance', (t) => { - const { doesNotThrow, strictEqual } = tspl(t, { plan: 2 }) + t.plan(2) const headers = new Headers() const name = 'undici' const value = 'fetch' headers.append('not-undici', 'fetch') - doesNotThrow(() => headers.set(name, value)) - strictEqual(headers.get(name), value) + t.assert.doesNotThrow(() => headers.set(name, value)) + t.assert.strictEqual(headers.get(name), value) }) await t.test('overwrites existing entry', (t) => { - const { doesNotThrow, strictEqual } = tspl(t, { plan: 4 }) + t.plan(4) const headers = new Headers() const name = 'undici' const value1 = 'fetch1' const value2 = 'fetch2' - doesNotThrow(() => headers.set(name, value1)) - strictEqual(headers.get(name), value1) - doesNotThrow(() => headers.set(name, value2)) - strictEqual(headers.get(name), value2) + t.assert.doesNotThrow(() => headers.set(name, value1)) + t.assert.strictEqual(headers.get(name), value1) + t.assert.doesNotThrow(() => headers.set(name, value2)) + t.assert.strictEqual(headers.get(name), value2) }) await t.test('allows setting a myriad of values', (t) => { - const { doesNotThrow, throws } = tspl(t, { plan: 4 }) + t.plan(4) const headers = new Headers() - doesNotThrow(() => headers.set('a', ['b', 'c']), 'sets array values properly') - doesNotThrow(() => headers.set('b', null), 'allows setting null values') - throws(() => headers.set('c'), 'throws when 2 arguments are not passed') - doesNotThrow(() => headers.set('c', 'd', 'e'), 'ignores extra arguments') + t.assert.doesNotThrow(() => headers.set('a', ['b', 'c']), 'sets array values properly') + t.assert.doesNotThrow(() => headers.set('b', null), 'allows setting null values') + t.assert.throws(() => headers.set('c'), 'throws when 2 arguments are not passed') + t.assert.doesNotThrow(() => headers.set('c', 'd', 'e'), 'ignores extra arguments') }) await t.test('throws on invalid entry', (t) => { - const { throws } = tspl(t, { plan: 3 }) + t.plan(3) const headers = new Headers() - throws(() => headers.set(), 'throws on missing name and value') - throws(() => headers.set('undici'), 'throws on missing value') - throws(() => headers.set('invalid @ header ? name', 'valid value'), 'throws on invalid name') + t.assert.throws(() => headers.set(), 'throws on missing name and value') + t.assert.throws(() => headers.set('undici'), 'throws on missing value') + t.assert.throws(() => headers.set('invalid @ header ? name', 'valid value'), 'throws on invalid name') }) // https://github.com/nodejs/undici/issues/2431 await t.test('`Headers#set` returns undefined', (t) => { - const { strictEqual, ok } = tspl(t, { plan: 2 }) + t.plan(2) const headers = new Headers() - strictEqual(headers.set('a', 'b'), undefined) + t.assert.strictEqual(headers.set('a', 'b'), undefined) - ok(!(headers.set('c', 'd') instanceof Map)) + t.assert.ok(!(headers.set('c', 'd') instanceof Map)) }) }) test('Headers forEach', async (t) => { const headers = new Headers([['a', 'b'], ['c', 'd']]) - await t.test('standard', () => { - assert.strictEqual(typeof headers.forEach, 'function') + await t.test('standard', (t) => { + t.assert.strictEqual(typeof headers.forEach, 'function') headers.forEach((value, key, headerInstance) => { - assert.ok(value === 'b' || value === 'd') - assert.ok(key === 'a' || key === 'c') - assert.strictEqual(headers, headerInstance) + t.assert.ok(value === 'b' || value === 'd') + t.assert.ok(key === 'a' || key === 'c') + t.assert.strictEqual(headers, headerInstance) }) }) - await t.test('when no thisArg is set, it is globalThis', () => { + await t.test('when no thisArg is set, it is globalThis', (t) => { headers.forEach(function () { - assert.strictEqual(this, globalThis) + t.assert.strictEqual(this, globalThis) }) }) - await t.test('with thisArg', () => { + await t.test('with thisArg', (t) => { const thisArg = { a: Math.random() } headers.forEach(function () { - assert.strictEqual(this, thisArg) + t.assert.strictEqual(this, thisArg) }, thisArg) }) }) test('Headers as Iterable', async (t) => { await t.test('should freeze values while iterating', (t) => { - const { deepStrictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const init = [ ['foo', '123'], ['bar', '456'] @@ -344,11 +342,11 @@ test('Headers as Iterable', async (t) => { headers.delete(key) headers.set(`x-${key}`, val) } - deepStrictEqual([...headers], expected) + t.assert.deepStrictEqual([...headers], expected) }) await t.test('returns combined and sorted entries using .forEach()', (t) => { - const { deepStrictEqual, strictEqual } = tspl(t, { plan: 8 }) + t.plan(8) const init = [ ['a', '1'], ['b', '2'], @@ -366,13 +364,13 @@ test('Headers as Iterable', async (t) => { const that = {} let i = 0 headers.forEach(function (value, key, _headers) { - deepStrictEqual(expected[i++], [key, value]) - strictEqual(this, that) + t.assert.deepStrictEqual(expected[i++], [key, value]) + t.assert.strictEqual(this, that) }, that) }) await t.test('returns combined and sorted entries using .entries()', (t) => { - const { deepStrictEqual } = tspl(t, { plan: 4 }) + t.plan(4) const init = [ ['a', '1'], ['b', '2'], @@ -389,12 +387,12 @@ test('Headers as Iterable', async (t) => { const headers = new Headers(init) let i = 0 for (const header of headers.entries()) { - deepStrictEqual(header, expected[i++]) + t.assert.deepStrictEqual(header, expected[i++]) } }) await t.test('returns combined and sorted keys using .keys()', (t) => { - const { strictEqual } = tspl(t, { plan: 4 }) + t.plan(4) const init = [ ['a', '1'], ['b', '2'], @@ -406,12 +404,12 @@ test('Headers as Iterable', async (t) => { const headers = new Headers(init) let i = 0 for (const key of headers.keys()) { - strictEqual(key, expected[i++]) + t.assert.strictEqual(key, expected[i++]) } }) await t.test('returns combined and sorted values using .values()', (t) => { - const { strictEqual } = tspl(t, { plan: 4 }) + t.plan(4) const init = [ ['a', '1'], ['b', '2'], @@ -423,12 +421,12 @@ test('Headers as Iterable', async (t) => { const headers = new Headers(init) let i = 0 for (const value of headers.values()) { - strictEqual(value, expected[i++]) + t.assert.strictEqual(value, expected[i++]) } }) await t.test('returns combined and sorted entries using for...of loop', (t) => { - const { deepStrictEqual } = tspl(t, { plan: 5 }) + t.plan(5) const init = [ ['a', '1'], ['b', '2'], @@ -446,12 +444,12 @@ test('Headers as Iterable', async (t) => { ] let i = 0 for (const header of new Headers(init)) { - deepStrictEqual(header, expected[i++]) + t.assert.deepStrictEqual(header, expected[i++]) } }) await t.test('validate append ordering', (t) => { - const { deepStrictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const headers = new Headers([['b', '2'], ['c', '3'], ['e', '5']]) headers.append('d', '4') headers.append('a', '1') @@ -469,7 +467,7 @@ test('Headers as Iterable', async (t) => { ['f', '6'] ])] - deepStrictEqual([...headers], expected) + t.assert.deepStrictEqual([...headers], expected) }) await t.test('always use the same prototype Iterator', (t) => { @@ -482,166 +480,166 @@ test('Headers as Iterable', async (t) => { const headers = new Headers(init) const iterator = headers[Symbol.iterator]() - assert.deepStrictEqual(HeadersIteratorNext(iterator), { value: init[0], done: false }) - assert.deepStrictEqual(HeadersIteratorNext(iterator), { value: init[1], done: false }) - assert.deepStrictEqual(HeadersIteratorNext(iterator), { value: undefined, done: true }) + t.assert.deepStrictEqual(HeadersIteratorNext(iterator), { value: init[0], done: false }) + t.assert.deepStrictEqual(HeadersIteratorNext(iterator), { value: init[1], done: false }) + t.assert.deepStrictEqual(HeadersIteratorNext(iterator), { value: undefined, done: true }) }) }) -test('arg validation', () => { +test('arg validation', (t) => { // fill - assert.throws(() => { + t.assert.throws(() => { fill({}, 0) }, TypeError) const headers = new Headers() // constructor - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line new Headers(0) }, TypeError) // get [Symbol.toStringTag] - assert.doesNotThrow(() => { + t.assert.doesNotThrow(() => { Object.prototype.toString.call(Headers.prototype) }) // toString - assert.doesNotThrow(() => { + t.assert.doesNotThrow(() => { Headers.prototype.toString.call(null) }) // append - assert.throws(() => { + t.assert.throws(() => { Headers.prototype.append.call(null) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { headers.append() }, TypeError) // delete - assert.throws(() => { + t.assert.throws(() => { Headers.prototype.delete.call(null) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { headers.delete() }, TypeError) // get - assert.throws(() => { + t.assert.throws(() => { Headers.prototype.get.call(null) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { headers.get() }, TypeError) // has - assert.throws(() => { + t.assert.throws(() => { Headers.prototype.has.call(null) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { headers.has() }, TypeError) // set - assert.throws(() => { + t.assert.throws(() => { Headers.prototype.set.call(null) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { headers.set() }, TypeError) // forEach - assert.throws(() => { + t.assert.throws(() => { Headers.prototype.forEach.call(null) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { headers.forEach() }, TypeError) - assert.throws(() => { + t.assert.throws(() => { headers.forEach(1) }, TypeError) // inspect - assert.throws(() => { + t.assert.throws(() => { Headers.prototype[Symbol.for('nodejs.util.inspect.custom')].call(null) }, TypeError) }) test('function signature verification', async (t) => { - await t.test('function length', () => { - assert.strictEqual(Headers.prototype.append.length, 2) - assert.strictEqual(Headers.prototype.constructor.length, 0) - assert.strictEqual(Headers.prototype.delete.length, 1) - assert.strictEqual(Headers.prototype.entries.length, 0) - assert.strictEqual(Headers.prototype.forEach.length, 1) - assert.strictEqual(Headers.prototype.get.length, 1) - assert.strictEqual(Headers.prototype.has.length, 1) - assert.strictEqual(Headers.prototype.keys.length, 0) - assert.strictEqual(Headers.prototype.set.length, 2) - assert.strictEqual(Headers.prototype.values.length, 0) - assert.strictEqual(Headers.prototype[Symbol.iterator].length, 0) - assert.strictEqual(Headers.prototype.toString.length, 0) - }) - - await t.test('function equality', () => { - assert.strictEqual(Headers.prototype.entries, Headers.prototype[Symbol.iterator]) - assert.strictEqual(Headers.prototype.toString, Object.prototype.toString) - }) - - await t.test('toString and Symbol.toStringTag', () => { - assert.strictEqual(Object.prototype.toString.call(Headers.prototype), '[object Headers]') - assert.strictEqual(Headers.prototype[Symbol.toStringTag], 'Headers') - assert.strictEqual(Headers.prototype.toString.call(null), '[object Null]') + await t.test('function length', (t) => { + t.assert.strictEqual(Headers.prototype.append.length, 2) + t.assert.strictEqual(Headers.prototype.constructor.length, 0) + t.assert.strictEqual(Headers.prototype.delete.length, 1) + t.assert.strictEqual(Headers.prototype.entries.length, 0) + t.assert.strictEqual(Headers.prototype.forEach.length, 1) + t.assert.strictEqual(Headers.prototype.get.length, 1) + t.assert.strictEqual(Headers.prototype.has.length, 1) + t.assert.strictEqual(Headers.prototype.keys.length, 0) + t.assert.strictEqual(Headers.prototype.set.length, 2) + t.assert.strictEqual(Headers.prototype.values.length, 0) + t.assert.strictEqual(Headers.prototype[Symbol.iterator].length, 0) + t.assert.strictEqual(Headers.prototype.toString.length, 0) + }) + + await t.test('function equality', (t) => { + t.assert.strictEqual(Headers.prototype.entries, Headers.prototype[Symbol.iterator]) + t.assert.strictEqual(Headers.prototype.toString, Object.prototype.toString) + }) + + await t.test('toString and Symbol.toStringTag', (t) => { + t.assert.strictEqual(Object.prototype.toString.call(Headers.prototype), '[object Headers]') + t.assert.strictEqual(Headers.prototype[Symbol.toStringTag], 'Headers') + t.assert.strictEqual(Headers.prototype.toString.call(null), '[object Null]') }) }) -test('various init paths of Headers', () => { +test('various init paths of Headers', (t) => { const h1 = new Headers() const h2 = new Headers({}) const h3 = new Headers(undefined) - assert.strictEqual([...h1.entries()].length, 0) - assert.strictEqual([...h2.entries()].length, 0) - assert.strictEqual([...h3.entries()].length, 0) + t.assert.strictEqual([...h1.entries()].length, 0) + t.assert.strictEqual([...h2.entries()].length, 0) + t.assert.strictEqual([...h3.entries()].length, 0) }) -test('immutable guard', () => { +test('immutable guard', (t) => { const headers = new Headers() headers.set('key', 'val') setHeadersGuard(headers, 'immutable') - assert.throws(() => { + t.assert.throws(() => { headers.set('asd', 'asd') }) - assert.throws(() => { + t.assert.throws(() => { headers.append('asd', 'asd') }) - assert.throws(() => { + t.assert.throws(() => { headers.delete('asd') }) - assert.strictEqual(headers.get('key'), 'val') - assert.strictEqual(headers.has('key'), true) + t.assert.strictEqual(headers.get('key'), 'val') + t.assert.strictEqual(headers.has('key'), true) }) -test('request-no-cors guard', () => { +test('request-no-cors guard', (t) => { const headers = new Headers() setHeadersGuard(headers, 'request-no-cors') - assert.doesNotThrow(() => { headers.set('key', 'val') }) - assert.doesNotThrow(() => { headers.append('key', 'val') }) + t.assert.doesNotThrow(() => { headers.set('key', 'val') }) + t.assert.doesNotThrow(() => { headers.append('key', 'val') }) }) -test('invalid headers', () => { - assert.doesNotThrow(() => new Headers({ "abcdefghijklmnopqrstuvwxyz0123456789!#$%&'*+-.^_`|~": 'test' })) +test('invalid headers', (t) => { + t.assert.doesNotThrow(() => new Headers({ "abcdefghijklmnopqrstuvwxyz0123456789!#$%&'*+-.^_`|~": 'test' })) const chars = '"(),/:;<=>?@[\\]{}'.split('') for (const char of chars) { - assert.throws(() => new Headers({ [char]: 'test' }), TypeError, `The string "${char}" should throw an error.`) + t.assert.throws(() => new Headers({ [char]: 'test' }), TypeError, `The string "${char}" should throw an error.`) } for (const byte of ['\r', '\n', '\t', ' ', String.fromCharCode(128), '']) { - assert.throws(() => { + t.assert.throws(() => { new Headers().set(byte, 'test') }, TypeError, 'invalid header name') } @@ -651,26 +649,26 @@ test('invalid headers', () => { '\r', '\n' ]) { - assert.throws(() => { + t.assert.throws(() => { new Headers().set('a', `a${byte}b`) }, TypeError, 'not allowed at all in header value') } - assert.doesNotThrow(() => { + t.assert.doesNotThrow(() => { new Headers().set('a', '\r') }) - assert.doesNotThrow(() => { + t.assert.doesNotThrow(() => { new Headers().set('a', '\n') }) - assert.throws(() => { + t.assert.throws(() => { new Headers().set('a', Symbol('symbol')) }, TypeError, 'symbols should throw') }) -test('headers that might cause a ReDoS', () => { - assert.doesNotThrow(() => { +test('headers that might cause a ReDoS', (t) => { + t.assert.doesNotThrow(() => { // This test will time out if the ReDoS attack is successful. const headers = new Headers() const attack = 'a' + '\t'.repeat(500_000) + '\ta' @@ -679,7 +677,7 @@ test('headers that might cause a ReDoS', () => { }) test('Headers.prototype.getSetCookie', async (t) => { - await t.test('Mutating the returned list does not affect the set-cookie list', () => { + await t.test('Mutating the returned list does not affect the set-cookie list', (t) => { const h = new Headers([ ['set-cookie', 'a=b'], ['set-cookie', 'c=d'] @@ -689,7 +687,7 @@ test('Headers.prototype.getSetCookie', async (t) => { h.getSetCookie().push('oh=no') const now = h.getSetCookie() - assert.deepStrictEqual(old, now) + t.assert.deepStrictEqual(old, now) }) // https://github.com/nodejs/undici/issues/1935 @@ -705,8 +703,8 @@ test('Headers.prototype.getSetCookie', async (t) => { const res = await fetch(`http://localhost:${server.address().port}`) const entries = Object.fromEntries(res.headers.entries()) - assert.deepStrictEqual(res.headers.getSetCookie(), ['test=onetwo']) - assert.ok('set-cookie' in entries) + t.assert.deepStrictEqual(res.headers.getSetCookie(), ['test=onetwo']) + t.assert.ok('set-cookie' in entries) }) await t.test('When Headers are cloned, so are the cookies (multiple entries)', async (t) => { @@ -721,32 +719,32 @@ test('Headers.prototype.getSetCookie', async (t) => { const res = await fetch(`http://localhost:${server.address().port}`) const entries = Object.fromEntries(res.headers.entries()) - assert.deepStrictEqual(res.headers.getSetCookie(), ['test=onetwo', 'test=onetwothree']) - assert.ok('set-cookie' in entries) + t.assert.deepStrictEqual(res.headers.getSetCookie(), ['test=onetwo', 'test=onetwothree']) + t.assert.ok('set-cookie' in entries) }) - await t.test('When Headers are cloned, so are the cookies (Headers constructor)', () => { + await t.test('When Headers are cloned, so are the cookies (Headers constructor)', (t) => { const headers = new Headers([['set-cookie', 'a'], ['set-cookie', 'b']]) - assert.deepStrictEqual([...headers], [...new Headers(headers)]) + t.assert.deepStrictEqual([...headers], [...new Headers(headers)]) }) }) test('When the value is updated, update the cache', (t) => { - const { deepStrictEqual } = tspl(t, { plan: 2 }) + t.plan(2) const expected = [['a', 'a'], ['b', 'b'], ['c', 'c']] const headers = new Headers(expected) - deepStrictEqual([...headers], expected) + t.assert.deepStrictEqual([...headers], expected) headers.append('d', 'd') - deepStrictEqual([...headers], [...expected, ['d', 'd']]) + t.assert.deepStrictEqual([...headers], [...expected, ['d', 'd']]) }) test('Symbol.iterator is only accessed once', (t) => { - const { ok } = tspl(t, { plan: 1 }) + t.plan(1) const dict = new Proxy({}, { get () { - ok(true) + t.assert.ok(true) return function * () {} } @@ -756,11 +754,11 @@ test('Symbol.iterator is only accessed once', (t) => { }) test('Invalid Symbol.iterators', (t) => { - const { throws } = tspl(t, { plan: 3 }) + t.plan(3) - throws(() => new Headers({ [Symbol.iterator]: null }), TypeError) - throws(() => new Headers({ [Symbol.iterator]: undefined }), TypeError) - throws(() => { + t.assert.throws(() => new Headers({ [Symbol.iterator]: null }), TypeError) + t.assert.throws(() => new Headers({ [Symbol.iterator]: undefined }), TypeError) + t.assert.throws(() => { const obj = { [Symbol.iterator]: null } Object.defineProperty(obj, Symbol.iterator, { enumerable: false }) @@ -770,12 +768,12 @@ test('Invalid Symbol.iterators', (t) => { // https://github.com/nodejs/undici/issues/3829 test('Invalid key/value records passed to constructor (issue #3829)', (t) => { - assert.throws( + t.assert.throws( () => new Headers({ [Symbol('x-fake-header')]: '??' }), new TypeError('Headers constructor: Key Symbol(x-fake-header) in init is a symbol, which cannot be converted to a ByteString.') ) - assert.throws( + t.assert.throws( () => new Headers({ 'x-fake-header': Symbol('why is this here?') }), new TypeError('Headers constructor: init["x-fake-header"] is a symbol, which cannot be converted to a ByteString.') ) diff --git a/test/fetch/headerslist-sortedarray.js b/test/fetch/headerslist-sortedarray.js index 9541901d2f2..ea7a330ee4e 100644 --- a/test/fetch/headerslist-sortedarray.js +++ b/test/fetch/headerslist-sortedarray.js @@ -1,7 +1,6 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') const { HeadersList, compareHeaderName } = require('../../lib/web/fetch/headers') const characters = 'abcdefghijklmnopqrstuvwxyz0123456789' @@ -17,22 +16,22 @@ function generateAsciiString (length) { const SORT_RUN = 4000 -test('toSortedArray (fast-path)', () => { +test('toSortedArray (fast-path)', (t) => { for (let i = 0; i < SORT_RUN; ++i) { const headersList = new HeadersList() for (let j = 0; j < 32; ++j) { headersList.append(generateAsciiString(4), generateAsciiString(4)) } - assert.deepStrictEqual(headersList.toSortedArray(), [...headersList].sort(compareHeaderName)) + t.assert.deepStrictEqual(headersList.toSortedArray(), [...headersList].sort(compareHeaderName)) } }) -test('toSortedArray (slow-path)', () => { +test('toSortedArray (slow-path)', (t) => { for (let i = 0; i < SORT_RUN; ++i) { const headersList = new HeadersList() for (let j = 0; j < 64; ++j) { headersList.append(generateAsciiString(4), generateAsciiString(4)) } - assert.deepStrictEqual(headersList.toSortedArray(), [...headersList].sort(compareHeaderName)) + t.assert.deepStrictEqual(headersList.toSortedArray(), [...headersList].sort(compareHeaderName)) } }) diff --git a/test/fetch/http2.js b/test/fetch/http2.js index 7f830b47c6c..75f0ec08bab 100644 --- a/test/fetch/http2.js +++ b/test/fetch/http2.js @@ -6,7 +6,6 @@ const { once } = require('node:events') const { Readable } = require('node:stream') const { test } = require('node:test') -const { tspl } = require('@matteo.collina/tspl') const pem = require('@metcoder95/https-pem') const { Client, fetch, Headers } = require('../..') @@ -33,7 +32,7 @@ test('[Fetch] Issue#2311', async (t) => { res.end(body) }) - const { strictEqual } = tspl(t, { plan: 2 }) + t.plan(2) server.listen() await once(server, 'listening') @@ -63,8 +62,8 @@ test('[Fetch] Issue#2311', async (t) => { t.after(closeClientAndServerAsPromise(client, server)) - strictEqual(responseBody, expectedBody) - strictEqual(response.headers.get('x-custom-h2'), 'foo') + t.assert.strictEqual(responseBody, expectedBody) + t.assert.strictEqual(response.headers.get('x-custom-h2'), 'foo') }) test('[Fetch] Simple GET with h2', async (t) => { @@ -82,7 +81,7 @@ test('[Fetch] Simple GET with h2', async (t) => { stream.end(expectedRequestBody) }) - const { strictEqual, throws } = tspl(t, { plan: 5 }) + t.plan(5) server.listen() await once(server, 'listening') @@ -111,16 +110,16 @@ test('[Fetch] Simple GET with h2', async (t) => { t.after(closeClientAndServerAsPromise(client, server)) - strictEqual(responseBody, expectedRequestBody) - strictEqual(response.headers.get('x-method'), 'GET') - strictEqual(response.headers.get('x-custom-h2'), 'foo') + t.assert.strictEqual(responseBody, expectedRequestBody) + t.assert.strictEqual(response.headers.get('x-method'), 'GET') + t.assert.strictEqual(response.headers.get('x-custom-h2'), 'foo') // https://github.com/nodejs/undici/issues/2415 - throws(() => { + t.assert.throws(() => { response.headers.get(':status') }, TypeError) // See https://fetch.spec.whatwg.org/#concept-response-status-message - strictEqual(response.statusText, '') + t.assert.strictEqual(response.statusText, '') }) test('[Fetch] Should handle h2 request with body (string or buffer)', async (t) => { @@ -141,7 +140,7 @@ test('[Fetch] Should handle h2 request with body (string or buffer)', async (t) stream.end(expectedRequestBody) }) - const { strictEqual } = tspl(t, { plan: 2 }) + t.plan(2) server.listen() await once(server, 'listening') @@ -171,8 +170,8 @@ test('[Fetch] Should handle h2 request with body (string or buffer)', async (t) t.after(closeClientAndServerAsPromise(client, server)) - strictEqual(Buffer.concat(requestBody).toString('utf-8'), expectedBody) - strictEqual(responseBody, expectedRequestBody) + t.assert.strictEqual(Buffer.concat(requestBody).toString('utf-8'), expectedBody) + t.assert.strictEqual(responseBody, expectedRequestBody) }) // Skipping for now, there is something odd in the way the body is handled @@ -184,12 +183,12 @@ test( const stream = createReadStream(__filename) const requestChunks = [] - const { strictEqual } = tspl(t, { plan: 8 }) + t.plan(8) server.on('stream', async (stream, headers) => { - strictEqual(headers[':method'], 'PUT') - strictEqual(headers[':path'], '/') - strictEqual(headers[':scheme'], 'https') + t.assert.strictEqual(headers[':method'], 'PUT') + t.assert.strictEqual(headers[':path'], '/') + t.assert.strictEqual(headers[':scheme'], 'https') stream.respond({ 'content-type': 'text/plain; charset=utf-8', @@ -233,11 +232,11 @@ test( const responseBody = await response.text() - strictEqual(response.status, 200) - strictEqual(response.headers.get('content-type'), 'text/plain; charset=utf-8') - strictEqual(response.headers.get('x-custom-h2'), 'foo') - strictEqual(responseBody, 'hello h2!') - strictEqual(Buffer.concat(requestChunks).toString('utf-8'), expectedBody) + t.assert.strictEqual(response.status, 200) + t.assert.strictEqual(response.headers.get('content-type'), 'text/plain; charset=utf-8') + t.assert.strictEqual(response.headers.get('x-custom-h2'), 'foo') + t.assert.strictEqual(responseBody, 'hello h2!') + t.assert.strictEqual(Buffer.concat(requestChunks).toString('utf-8'), expectedBody) } ) test('Should handle h2 request with body (Blob)', async (t) => { @@ -248,12 +247,12 @@ test('Should handle h2 request with body (Blob)', async (t) => { type: 'text/plain' }) - const { strictEqual } = tspl(t, { plan: 8 }) + t.plan(8) server.on('stream', async (stream, headers) => { - strictEqual(headers[':method'], 'POST') - strictEqual(headers[':path'], '/') - strictEqual(headers[':scheme'], 'https') + t.assert.strictEqual(headers[':method'], 'POST') + t.assert.strictEqual(headers[':path'], '/') + t.assert.strictEqual(headers[':scheme'], 'https') stream.on('data', chunk => requestChunks.push(chunk)) @@ -294,11 +293,11 @@ test('Should handle h2 request with body (Blob)', async (t) => { const responseBody = await response.arrayBuffer() - strictEqual(response.status, 200) - strictEqual(response.headers.get('content-type'), 'text/plain; charset=utf-8') - strictEqual(response.headers.get('x-custom-h2'), 'foo') - strictEqual(new TextDecoder().decode(responseBody).toString(), 'hello h2!') - strictEqual(Buffer.concat(requestChunks).toString('utf-8'), expectedBody) + t.assert.strictEqual(response.status, 200) + t.assert.strictEqual(response.headers.get('content-type'), 'text/plain; charset=utf-8') + t.assert.strictEqual(response.headers.get('x-custom-h2'), 'foo') + t.assert.strictEqual(new TextDecoder().decode(responseBody).toString(), 'hello h2!') + t.assert.strictEqual(Buffer.concat(requestChunks).toString('utf-8'), expectedBody) }) test( @@ -313,12 +312,12 @@ test( buf.copy(new Uint8Array(body)) - const { strictEqual, deepStrictEqual } = tspl(t, { plan: 8 }) + t.plan(8) server.on('stream', async (stream, headers) => { - strictEqual(headers[':method'], 'PUT') - strictEqual(headers[':path'], '/') - strictEqual(headers[':scheme'], 'https') + t.assert.strictEqual(headers[':method'], 'PUT') + t.assert.strictEqual(headers[':path'], '/') + t.assert.strictEqual(headers[':scheme'], 'https') stream.on('data', chunk => requestChunks.push(chunk)) @@ -359,16 +358,16 @@ test( const responseBody = await response.json() - strictEqual(response.status, 200) - strictEqual(response.headers.get('content-type'), 'application/json') - strictEqual(response.headers.get('x-custom-h2'), 'foo') - deepStrictEqual(responseBody, expectedResponseBody) - strictEqual(Buffer.concat(requestChunks).toString('utf-8'), expectedBody) + t.assert.strictEqual(response.status, 200) + t.assert.strictEqual(response.headers.get('content-type'), 'application/json') + t.assert.strictEqual(response.headers.get('x-custom-h2'), 'foo') + t.assert.deepStrictEqual(responseBody, expectedResponseBody) + t.assert.strictEqual(Buffer.concat(requestChunks).toString('utf-8'), expectedBody) } ) test('Issue#2415', async (t) => { - const { doesNotThrow } = tspl(t, { plan: 1 }) + t.plan(1) const server = createSecureServer(await pem.generate({ opts: { keySize: 2048 } })) server.on('stream', async (stream, headers) => { @@ -401,7 +400,7 @@ test('Issue#2415', async (t) => { t.after(closeClientAndServerAsPromise(client, server)) - doesNotThrow(() => new Headers(response.headers)) + t.assert.doesNotThrow(() => new Headers(response.headers)) }) test('Issue #2386', async (t) => { @@ -412,12 +411,12 @@ test('Issue #2386', async (t) => { const controller = new AbortController() const signal = controller.signal - const { strictEqual, ok } = tspl(t, { plan: 4 }) + t.plan(4) server.on('stream', async (stream, headers) => { - strictEqual(headers[':method'], 'PUT') - strictEqual(headers[':path'], '/') - strictEqual(headers[':scheme'], 'https') + t.assert.strictEqual(headers[':method'], 'PUT') + t.assert.strictEqual(headers[':path'], '/') + t.assert.strictEqual(headers[':scheme'], 'https') stream.on('data', chunk => requestChunks.push(chunk)) @@ -458,18 +457,18 @@ test('Issue #2386', async (t) => { ) controller.abort() - ok(true) + t.assert.ok(true) }) test('Issue #3046', async (t) => { const server = createSecureServer(await pem.generate({ opts: { keySize: 2048 } })) - const { strictEqual, deepStrictEqual } = tspl(t, { plan: 6 }) + t.plan(6) server.on('stream', async (stream, headers) => { - strictEqual(headers[':method'], 'GET') - strictEqual(headers[':path'], '/') - strictEqual(headers[':scheme'], 'https') + t.assert.strictEqual(headers[':method'], 'GET') + t.assert.strictEqual(headers[':path'], '/') + t.assert.strictEqual(headers[':scheme'], 'https') stream.respond({ 'set-cookie': ['hello=world', 'foo=bar'], @@ -501,7 +500,7 @@ test('Issue #3046', async (t) => { } ) - strictEqual(response.status, 200) - strictEqual(response.headers.get('content-type'), 'text/html; charset=utf-8') - deepStrictEqual(response.headers.getSetCookie(), ['hello=world', 'foo=bar']) + t.assert.strictEqual(response.status, 200) + t.assert.strictEqual(response.headers.get('content-type'), 'text/html; charset=utf-8') + t.assert.deepStrictEqual(response.headers.getSetCookie(), ['hello=world', 'foo=bar']) }) diff --git a/test/fetch/integrity.js b/test/fetch/integrity.js index 0fad52cfc8c..bd8d5f953f4 100644 --- a/test/fetch/integrity.js +++ b/test/fetch/integrity.js @@ -1,8 +1,6 @@ 'use strict' const { test, after } = require('node:test') -const { tspl } = require('@matteo.collina/tspl') -const assert = require('node:assert') const { createServer } = require('node:http') const { gzipSync } = require('node:zlib') const { fetch, setGlobalDispatcher, Agent } = require('../..') @@ -32,7 +30,7 @@ test('request with correct integrity checksum', { skip }, async (t) => { const response = await fetch(`http://localhost:${server.address().port}`, { integrity: `sha256-${hash}` }) - assert.strictEqual(body, await response.text()) + t.assert.strictEqual(body, await response.text()) }) test('request with wrong integrity checksum', { skip }, async (t) => { @@ -50,7 +48,7 @@ test('request with wrong integrity checksum', { skip }, async (t) => { cause: new Error('integrity mismatch') }) - await assert.rejects(fetch(`http://localhost:${server.address().port}`, { + await t.assert.rejects(fetch(`http://localhost:${server.address().port}`, { integrity: `sha256-${hash}` }), expectedError) }) @@ -70,7 +68,7 @@ test('request with integrity checksum on encoded body', { skip }, async (t) => { const response = await fetch(`http://localhost:${server.address().port}`, { integrity: `sha256-${hash}` }) - assert.strictEqual(body, await response.text()) + t.assert.strictEqual(body, await response.text()) }) test('request with a totally incorrect integrity', { skip }, async (t) => { @@ -81,7 +79,7 @@ test('request with a totally incorrect integrity', { skip }, async (t) => { t.after(closeServerAsPromise(server)) await once(server, 'listening') - await assert.doesNotReject(fetch(`http://localhost:${server.address().port}`, { + await t.assert.doesNotReject(fetch(`http://localhost:${server.address().port}`, { integrity: 'what-integrityisthis' })) }) @@ -97,7 +95,7 @@ test('request with mixed in/valid integrities', { skip }, async (t) => { t.after(closeServerAsPromise(server)) await once(server, 'listening') - await assert.doesNotReject(fetch(`http://localhost:${server.address().port}`, { + await t.assert.doesNotReject(fetch(`http://localhost:${server.address().port}`, { integrity: `invalid-integrity sha256-${hash}` })) }) @@ -114,12 +112,12 @@ test('request with sha384 hash', { skip }, async (t) => { await once(server, 'listening') // request should succeed - await assert.doesNotReject(fetch(`http://localhost:${server.address().port}`, { + await t.assert.doesNotReject(fetch(`http://localhost:${server.address().port}`, { integrity: `sha384-${hash}` })) // request should fail - await assert.rejects(fetch(`http://localhost:${server.address().port}`, { + await t.assert.rejects(fetch(`http://localhost:${server.address().port}`, { integrity: 'sha384-ypeBEsobvcr6wjGzmiPcTaeG7/gUfE5yuYB3ha/uSLs=' })) }) @@ -136,12 +134,12 @@ test('request with sha512 hash', { skip }, async (t) => { await once(server, 'listening') // request should succeed - await assert.doesNotReject(fetch(`http://localhost:${server.address().port}`, { + await t.assert.doesNotReject(fetch(`http://localhost:${server.address().port}`, { integrity: `sha512-${hash}` })) // request should fail - await assert.rejects(fetch(`http://localhost:${server.address().port}`, { + await t.assert.rejects(fetch(`http://localhost:${server.address().port}`, { integrity: 'sha512-ypeBEsobvcr6wjGzmiPcTaeG7/gUfE5yuYB3ha/uSLs=' })) }) @@ -158,13 +156,13 @@ test('request with sha512 hash', { skip }, async (t) => { await once(server, 'listening') // request should fail - await assert.rejects(fetch(`http://localhost:${server.address().port}`, { + await t.assert.rejects(fetch(`http://localhost:${server.address().port}`, { integrity: `sha512-${hash384} sha384-${hash384}` })) }) test('request with correct integrity checksum (base64url)', { skip }, async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const body = 'Hello world!' const hash = 'wFNeS-K3n_2TKRMFQ2v4iTFOSj-uwF7P_Lt98xrZ5Ro' @@ -174,18 +172,15 @@ test('request with correct integrity checksum (base64url)', { skip }, async (t) after(closeServerAsPromise(server)) - server.listen(0, async () => { - const response = await fetch(`http://localhost:${server.address().port}`, { - integrity: `sha256-${hash}` - }) - t.strictEqual(body, await response.text()) + await once(server.listen(0), 'listening') + const response = await fetch(`http://localhost:${server.address().port}`, { + integrity: `sha256-${hash}` }) - - await t.completed + t.assert.strictEqual(body, await response.text()) }) test('request with incorrect integrity checksum (base64url)', { skip }, async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const body = 'Hello world!' // base64url for 'invalid' sha256 @@ -197,17 +192,14 @@ test('request with incorrect integrity checksum (base64url)', { skip }, async (t after(closeServerAsPromise(server)) - server.listen(0, async () => { - await t.rejects(fetch(`http://localhost:${server.address().port}`, { - integrity: `sha256-${hash}` - })) - }) - - await t.completed + await once(server.listen(0), 'listening') + await t.assert.rejects(fetch(`http://localhost:${server.address().port}`, { + integrity: `sha256-${hash}` + })) }) test('request with incorrect integrity checksum (only dash)', { skip }, async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const body = 'Hello world!' @@ -217,17 +209,14 @@ test('request with incorrect integrity checksum (only dash)', { skip }, async (t after(closeServerAsPromise(server)) - server.listen(0, async () => { - await t.rejects(fetch(`http://localhost:${server.address().port}`, { - integrity: 'sha256--' - })) - }) - - await t.completed + await once(server.listen(0), 'listening') + await t.assert.rejects(fetch(`http://localhost:${server.address().port}`, { + integrity: 'sha256--' + })) }) test('request with incorrect integrity checksum (non-ascii character)', { skip }, async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const body = 'Hello world!' @@ -237,17 +226,14 @@ test('request with incorrect integrity checksum (non-ascii character)', { skip } after(closeServerAsPromise(server)) - server.listen(0, async () => { - await t.rejects(() => fetch(`http://localhost:${server.address().port}`, { - integrity: 'sha256-ä' - })) - }) - - await t.completed + await once(server.listen(0), 'listening') + await t.assert.rejects(() => fetch(`http://localhost:${server.address().port}`, { + integrity: 'sha256-ä' + })) }) test('request with incorrect stronger integrity checksum (non-ascii character)', { skip }, async (t) => { - t = tspl(t, { plan: 2 }) + t.plan(2) const body = 'Hello world!' const sha256 = 'wFNeS+K3n/2TKRMFQ2v4iTFOSj+uwF7P/Lt98xrZ5Ro=' @@ -259,20 +245,17 @@ test('request with incorrect stronger integrity checksum (non-ascii character)', after(closeServerAsPromise(server)) - server.listen(0, async () => { - await t.rejects(() => fetch(`http://localhost:${server.address().port}`, { - integrity: `sha256-${sha256} sha384-${sha384}` - })) - await t.rejects(() => fetch(`http://localhost:${server.address().port}`, { - integrity: `sha384-${sha384} sha256-${sha256}` - })) - }) - - await t.completed + await once(server.listen(0), 'listening') + await t.assert.rejects(() => fetch(`http://localhost:${server.address().port}`, { + integrity: `sha256-${sha256} sha384-${sha384}` + })) + await t.assert.rejects(() => fetch(`http://localhost:${server.address().port}`, { + integrity: `sha384-${sha384} sha256-${sha256}` + })) }) test('request with correct integrity checksum (base64). mixed', { skip }, async (t) => { - t = tspl(t, { plan: 6 }) + t.plan(6) const body = 'Hello world!' const sha256 = 'wFNeS+K3n/2TKRMFQ2v4iTFOSj+uwF7P/Lt98xrZ5Ro=' const sha384 = 'hiVfosNuSzCWnq4X3DTHcsvr38WLWEA5AL6HYU6xo0uHgCY/JV615lypu7hkHMz+' @@ -284,41 +267,38 @@ test('request with correct integrity checksum (base64). mixed', { skip }, async after(closeServerAsPromise(server)) - server.listen(0, async () => { - let response - response = await fetch(`http://localhost:${server.address().port}`, { - integrity: `sha256-${sha256} sha512-${sha512}` - }) - t.strictEqual(body, await response.text()) - response = await fetch(`http://localhost:${server.address().port}`, { - integrity: `sha512-${sha512} sha256-${sha256}` - }) - - t.strictEqual(body, await response.text()) - response = await fetch(`http://localhost:${server.address().port}`, { - integrity: `sha384-${sha384} sha512-${sha512}` - }) - t.strictEqual(body, await response.text()) - response = await fetch(`http://localhost:${server.address().port}`, { - integrity: `sha384-${sha384} sha512-${sha512}` - }) - t.strictEqual(body, await response.text()) - - response = await fetch(`http://localhost:${server.address().port}`, { - integrity: `sha256-${sha256} sha384-${sha384}` - }) - t.strictEqual(body, await response.text()) - response = await fetch(`http://localhost:${server.address().port}`, { - integrity: `sha384-${sha384} sha256-${sha256}` - }) - t.strictEqual(body, await response.text()) + await once(server.listen(0), 'listening') + let response + response = await fetch(`http://localhost:${server.address().port}`, { + integrity: `sha256-${sha256} sha512-${sha512}` + }) + t.assert.strictEqual(body, await response.text()) + response = await fetch(`http://localhost:${server.address().port}`, { + integrity: `sha512-${sha512} sha256-${sha256}` + }) + + t.assert.strictEqual(body, await response.text()) + response = await fetch(`http://localhost:${server.address().port}`, { + integrity: `sha384-${sha384} sha512-${sha512}` + }) + t.assert.strictEqual(body, await response.text()) + response = await fetch(`http://localhost:${server.address().port}`, { + integrity: `sha384-${sha384} sha512-${sha512}` }) + t.assert.strictEqual(body, await response.text()) - await t.completed + response = await fetch(`http://localhost:${server.address().port}`, { + integrity: `sha256-${sha256} sha384-${sha384}` + }) + t.assert.strictEqual(body, await response.text()) + response = await fetch(`http://localhost:${server.address().port}`, { + integrity: `sha384-${sha384} sha256-${sha256}` + }) + t.assert.strictEqual(body, await response.text()) }) test('request with correct integrity checksum (base64url). mixed', { skip }, async (t) => { - t = tspl(t, { plan: 6 }) + t.plan(6) const body = 'Hello world!' const sha256 = 'wFNeS-K3n_2TKRMFQ2v4iTFOSj-uwF7P_Lt98xrZ5Ro' const sha384 = 'hiVfosNuSzCWnq4X3DTHcsvr38WLWEA5AL6HYU6xo0uHgCY_JV615lypu7hkHMz-' @@ -330,35 +310,32 @@ test('request with correct integrity checksum (base64url). mixed', { skip }, asy after(closeServerAsPromise(server)) - server.listen(0, async () => { - let response - response = await fetch(`http://localhost:${server.address().port}`, { - integrity: `sha256-${sha256} sha512-${sha512}` - }) - t.strictEqual(body, await response.text()) - response = await fetch(`http://localhost:${server.address().port}`, { - integrity: `sha512-${sha512} sha256-${sha256}` - }) - - t.strictEqual(body, await response.text()) - response = await fetch(`http://localhost:${server.address().port}`, { - integrity: `sha384-${sha384} sha512-${sha512}` - }) - t.strictEqual(body, await response.text()) - response = await fetch(`http://localhost:${server.address().port}`, { - integrity: `sha384-${sha384} sha512-${sha512}` - }) - t.strictEqual(body, await response.text()) - - response = await fetch(`http://localhost:${server.address().port}`, { - integrity: `sha256-${sha256} sha384-${sha384}` - }) - t.strictEqual(body, await response.text()) - response = await fetch(`http://localhost:${server.address().port}`, { - integrity: `sha384-${sha384} sha256-${sha256}` - }) - t.strictEqual(body, await response.text()) + await once(server.listen(0), 'listening') + let response + response = await fetch(`http://localhost:${server.address().port}`, { + integrity: `sha256-${sha256} sha512-${sha512}` + }) + t.assert.strictEqual(body, await response.text()) + response = await fetch(`http://localhost:${server.address().port}`, { + integrity: `sha512-${sha512} sha256-${sha256}` }) - await t.completed + t.assert.strictEqual(body, await response.text()) + response = await fetch(`http://localhost:${server.address().port}`, { + integrity: `sha384-${sha384} sha512-${sha512}` + }) + t.assert.strictEqual(body, await response.text()) + response = await fetch(`http://localhost:${server.address().port}`, { + integrity: `sha384-${sha384} sha512-${sha512}` + }) + t.assert.strictEqual(body, await response.text()) + + response = await fetch(`http://localhost:${server.address().port}`, { + integrity: `sha256-${sha256} sha384-${sha384}` + }) + t.assert.strictEqual(body, await response.text()) + response = await fetch(`http://localhost:${server.address().port}`, { + integrity: `sha384-${sha384} sha256-${sha256}` + }) + t.assert.strictEqual(body, await response.text()) }) diff --git a/test/fetch/issue-1447.js b/test/fetch/issue-1447.js index dc49113665b..118237b7772 100644 --- a/test/fetch/issue-1447.js +++ b/test/fetch/issue-1447.js @@ -1,13 +1,12 @@ 'use strict' const { test } = require('node:test') -const { tspl } = require('@matteo.collina/tspl') const undici = require('../..') const { fetch: theoreticalGlobalFetch } = require('../../undici-fetch') test('Mocking works with both fetches', async (t) => { - const { strictEqual } = tspl(t, { plan: 3 }) + t.plan(3) const mockAgent = new undici.MockAgent() const body = JSON.stringify({ foo: 'bar' }) @@ -20,7 +19,7 @@ test('Mocking works with both fetches', async (t) => { path: '/path', method: 'POST', body (bodyString) { - strictEqual(bodyString, body) + t.assert.strictEqual(bodyString, body) return true } }).reply(200, { ok: 1 }).times(2) diff --git a/test/fetch/issue-1711.js b/test/fetch/issue-1711.js index ca78897ae5f..5abe64c849d 100644 --- a/test/fetch/issue-1711.js +++ b/test/fetch/issue-1711.js @@ -1,6 +1,5 @@ 'use strict' -const assert = require('node:assert') const { once } = require('node:events') const { createServer } = require('node:http') const { test } = require('node:test') @@ -24,12 +23,12 @@ test('Redirecting a bunch does not cause a MaxListenersExceededWarning', async ( t.after(server.close.bind(server)) await once(server, 'listening') - process.emitWarning = assert.bind(null, false) + process.emitWarning = t.assert.fail.bind(t) const url = `http://localhost:${server.address().port}` const response = await fetch(url, { redirect: 'follow' }) - assert.deepStrictEqual(response.url, `${url}/${redirects - 1}`) + t.assert.deepStrictEqual(response.url, `${url}/${redirects - 1}`) }) test( diff --git a/test/fetch/issue-2009.js b/test/fetch/issue-2009.js index 14432e81cb2..4261b7134ae 100644 --- a/test/fetch/issue-2009.js +++ b/test/fetch/issue-2009.js @@ -1,14 +1,13 @@ 'use strict' const { test } = require('node:test') -const { tspl } = require('@matteo.collina/tspl') const { fetch } = require('../..') const { createServer } = require('node:http') const { once } = require('node:events') const { closeServerAsPromise } = require('../utils/node-http') test('issue 2009', async (t) => { - const { doesNotReject } = tspl(t, { plan: 10 }) + t.plan(10) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.setHeader('a', 'b') @@ -21,7 +20,7 @@ test('issue 2009', async (t) => { await once(server, 'listening') for (let i = 0; i < 10; i++) { - await doesNotReject( + await t.assert.doesNotReject( fetch(`http://localhost:${server.address().port}`).then( async (resp) => { await resp.body.cancel('Some message') diff --git a/test/fetch/issue-2021.js b/test/fetch/issue-2021.js index b88db725dbe..bd605219d3e 100644 --- a/test/fetch/issue-2021.js +++ b/test/fetch/issue-2021.js @@ -1,7 +1,6 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') const { once } = require('node:events') const { createServer } = require('node:http') const { fetch } = require('../..') @@ -24,7 +23,7 @@ test('content-length header is removed on redirect', async (t) => { const body = 'a+b+c' - await assert.doesNotReject(fetch(`http://localhost:${server.address().port}/redirect`, { + await t.assert.doesNotReject(fetch(`http://localhost:${server.address().port}/redirect`, { method: 'POST', body, headers: { diff --git a/test/fetch/issue-2171.js b/test/fetch/issue-2171.js index 218997d5952..a8d9fbbef8b 100644 --- a/test/fetch/issue-2171.js +++ b/test/fetch/issue-2171.js @@ -4,7 +4,6 @@ const { fetch } = require('../..') const { once } = require('node:events') const { createServer } = require('node:http') const { test } = require('node:test') -const assert = require('node:assert') const { closeServerAsPromise } = require('../utils/node-http') test('error reason is forwarded - issue #2171', async (t) => { @@ -14,7 +13,7 @@ test('error reason is forwarded - issue #2171', async (t) => { await once(server, 'listening') const timeout = AbortSignal.timeout(100) - await assert.rejects( + await t.assert.rejects( fetch(`http://localhost:${server.address().port}`, { signal: timeout }), diff --git a/test/fetch/issue-2242.js b/test/fetch/issue-2242.js index 1c0fe1f4303..ede276f72ba 100644 --- a/test/fetch/issue-2242.js +++ b/test/fetch/issue-2242.js @@ -1,7 +1,6 @@ 'use strict' const { beforeEach, describe, it } = require('node:test') -const assert = require('node:assert') const { fetch } = require('../..') const nodeFetch = require('../../index-fetch') @@ -15,17 +14,17 @@ describe('Issue #2242', () => { beforeEach(() => { signal = AbortSignal.abort(reason) }) - it('rejects with that reason ', async () => { - await assert.rejects(fetch('http://localhost', { signal }), (err) => { - assert.strictEqual(err, reason) + it('rejects with that reason ', async (t) => { + await t.assert.rejects(fetch('http://localhost', { signal }), (err) => { + t.assert.strictEqual(err, reason) return true }) }) - it('rejects with that reason (from index-fetch)', async () => { - await assert.rejects( + it('rejects with that reason (from index-fetch)', async (t) => { + await t.assert.rejects( nodeFetch.fetch('http://localhost', { signal }), (err) => { - assert.strictEqual(err, reason) + t.assert.strictEqual(err, reason) return true } ) @@ -38,14 +37,14 @@ describe('Issue #2242', () => { beforeEach(() => { signal = AbortSignal.abort(undefined) }) - it('rejects with an `AbortError`', async () => { - await assert.rejects( + it('rejects with an `AbortError`', async (t) => { + await t.assert.rejects( fetch('http://localhost', { signal }), new DOMException('This operation was aborted', 'AbortError') ) }) - it('rejects with an `AbortError` (from index-fetch)', async () => { - await assert.rejects( + it('rejects with an `AbortError` (from index-fetch)', async (t) => { + await t.assert.rejects( nodeFetch.fetch('http://localhost', { signal }), new DOMException('This operation was aborted', 'AbortError') ) diff --git a/test/fetch/issue-2294-patch-method.js b/test/fetch/issue-2294-patch-method.js index 6223989c07c..868737d83ce 100644 --- a/test/fetch/issue-2294-patch-method.js +++ b/test/fetch/issue-2294-patch-method.js @@ -1,11 +1,10 @@ 'use strict' -const { tspl } = require('@matteo.collina/tspl') const { test, after } = require('node:test') const { Request } = require('../..') test('Using `patch` method emits a warning.', (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const { emitWarning } = process @@ -14,7 +13,7 @@ test('Using `patch` method emits a warning.', (t) => { }) process.emitWarning = (warning, options) => { - t.strictEqual(options.code, 'UNDICI-FETCH-patch') + t.assert.strictEqual(options.code, 'UNDICI-FETCH-patch') } // eslint-disable-next-line no-new diff --git a/test/fetch/issue-2318.js b/test/fetch/issue-2318.js index fe27ac7ec35..8d5f17c7451 100644 --- a/test/fetch/issue-2318.js +++ b/test/fetch/issue-2318.js @@ -1,17 +1,16 @@ 'use strict' const { test } = require('node:test') -const { tspl } = require('@matteo.collina/tspl') const { once } = require('node:events') const { createServer } = require('node:http') const { fetch } = require('../..') const { closeServerAsPromise } = require('../utils/node-http') test('Undici overrides user-provided `Host` header', async (t) => { - const { strictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - strictEqual(req.headers.host, `localhost:${server.address().port}`) + t.assert.strictEqual(req.headers.host, `localhost:${server.address().port}`) res.end() }).listen(0) diff --git a/test/fetch/issue-2828.js b/test/fetch/issue-2828.js index 98fd375b8e9..dc918cd7f97 100644 --- a/test/fetch/issue-2828.js +++ b/test/fetch/issue-2828.js @@ -4,10 +4,9 @@ const { once } = require('node:events') const { createServer } = require('node:http') const { test } = require('node:test') const { Agent, Request, fetch } = require('../..') -const { tspl } = require('@matteo.collina/tspl') test('issue #2828, dispatcher is allowed in RequestInit options', async (t) => { - const { deepStrictEqual } = tspl(t, { plan: 1 }) + t.plan(1) class CustomAgent extends Agent { dispatch (options, handler) { @@ -17,7 +16,7 @@ test('issue #2828, dispatcher is allowed in RequestInit options', async (t) => { } const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - deepStrictEqual(req.headers['x-my-header'], 'hello') + t.assert.deepStrictEqual(req.headers['x-my-header'], 'hello') res.end() }).listen(0) diff --git a/test/fetch/issue-2898-comment.js b/test/fetch/issue-2898-comment.js index d1d326b2c35..d3532d336d4 100644 --- a/test/fetch/issue-2898-comment.js +++ b/test/fetch/issue-2898-comment.js @@ -4,10 +4,9 @@ const { once } = require('node:events') const { createServer } = require('node:http') const { test } = require('node:test') const { Agent, Request, fetch } = require('../..') -const { tspl } = require('@matteo.collina/tspl') test('issue #2828, RequestInit dispatcher options overrides Request input dispatcher', async (t) => { - const { strictEqual } = tspl(t, { plan: 2 }) + t.plan(2) class CustomAgentA extends Agent { dispatch (options, handler) { @@ -24,8 +23,8 @@ test('issue #2828, RequestInit dispatcher options overrides Request input dispat } const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - strictEqual(req.headers['x-my-header-a'], undefined) - strictEqual(req.headers['x-my-header-b'], 'world') + t.assert.strictEqual(req.headers['x-my-header-a'], undefined) + t.assert.strictEqual(req.headers['x-my-header-b'], 'world') res.end() }).listen(0) diff --git a/test/fetch/issue-2898.js b/test/fetch/issue-2898.js index d6188ab696a..a5f43c71d77 100644 --- a/test/fetch/issue-2898.js +++ b/test/fetch/issue-2898.js @@ -1,6 +1,5 @@ 'use strict' -const assert = require('node:assert') const { once } = require('node:events') const { createServer } = require('node:http') const { test } = require('node:test') @@ -27,7 +26,7 @@ test('421 requests with a body work as expected', async (t) => { body }) - assert.deepStrictEqual(response.status, 421) - assert.deepStrictEqual(await response.text(), expected) + t.assert.deepStrictEqual(response.status, 421) + t.assert.deepStrictEqual(await response.text(), expected) } }) diff --git a/test/fetch/issue-3267.js b/test/fetch/issue-3267.js index 8b7515e62af..94814ea8a66 100644 --- a/test/fetch/issue-3267.js +++ b/test/fetch/issue-3267.js @@ -2,7 +2,6 @@ const { Headers } = require('../..') const { test } = require('node:test') -const assert = require('node:assert') test('Spreading a Headers object yields 0 symbols', (t) => { const baseHeaders = { 'x-foo': 'bar' } @@ -13,6 +12,6 @@ test('Spreading a Headers object yields 0 symbols', (t) => { ...requestHeaders } - assert.deepStrictEqual(headers, { 'x-foo': 'bar' }) - assert.doesNotThrow(() => new Headers(headers)) + t.assert.deepStrictEqual(headers, { 'x-foo': 'bar' }) + t.assert.doesNotThrow(() => new Headers(headers)) }) diff --git a/test/fetch/issue-3334.js b/test/fetch/issue-3334.js index 1fcfd0e86c7..cc0e3a12783 100644 --- a/test/fetch/issue-3334.js +++ b/test/fetch/issue-3334.js @@ -1,17 +1,16 @@ 'use strict' const { test } = require('node:test') -const { tspl } = require('@matteo.collina/tspl') const { once } = require('node:events') const { createServer } = require('node:http') const { fetch } = require('../..') test('a non-empty origin is not appended (issue #3334)', async (t) => { - const { strictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const origin = 'https://origin.example.com' const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - strictEqual(req.headers.origin, origin) + t.assert.strictEqual(req.headers.origin, origin) res.end() }).listen(0) diff --git a/test/fetch/issue-3616.js b/test/fetch/issue-3616.js index 2de5c63672d..81e39532722 100644 --- a/test/fetch/issue-3616.js +++ b/test/fetch/issue-3616.js @@ -1,7 +1,6 @@ 'use strict' const { createServer } = require('node:http') -const { tspl } = require('@matteo.collina/tspl') const { describe, test, after } = require('node:test') const { fetch } = require('../..') const { once } = require('node:events') @@ -16,7 +15,7 @@ describe('https://github.com/nodejs/undici/issues/3616', () => { for (const encoding of cases) { test(encoding, async t => { - t = tspl(t, { plan: 2 }) + t.plan(2) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { res.writeHead(200, { 'Content-Length': '0', @@ -35,14 +34,14 @@ describe('https://github.com/nodejs/undici/issues/3616', () => { await once(server, 'listening') const result = await fetch(`http://localhost:${server.address().port}/`) - t.ok(result.body.getReader()) + t.assert.ok(result.body.getReader()) process.on('uncaughtException', (reason) => { - t.fail('Uncaught Exception:', reason, encoding) + t.assert.fail('Uncaught Exception:', reason, encoding) }) await new Promise(resolve => setTimeout(resolve, 100)) - t.ok(true) + t.assert.ok(true) }) } }) diff --git a/test/fetch/issue-3624.js b/test/fetch/issue-3624.js index 279b55c9f5d..4b5a6e35311 100644 --- a/test/fetch/issue-3624.js +++ b/test/fetch/issue-3624.js @@ -1,6 +1,5 @@ 'use strict' -const assert = require('node:assert') const { test } = require('node:test') const { once } = require('node:events') const { createServer } = require('node:http') @@ -24,5 +23,5 @@ test('crlf is appended to formdata body (issue #3624)', async (t) => { method: 'POST' }) - assert((await response.text()).endsWith('\r\n')) + t.assert.ok((await response.text()).endsWith('\r\n')) }) diff --git a/test/fetch/issue-3630.js b/test/fetch/issue-3630.js index d40a5c64d99..029e14992a9 100644 --- a/test/fetch/issue-3630.js +++ b/test/fetch/issue-3630.js @@ -1,12 +1,11 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') const { Request, Agent } = require('../..') const { getRequestDispatcher } = require('../../lib/web/fetch/request') -test('Cloned request should inherit its dispatcher', () => { +test('Cloned request should inherit its dispatcher', (t) => { const agent = new Agent() const request = new Request('https://a', { dispatcher: agent }) - assert.strictEqual(getRequestDispatcher(request), agent) + t.assert.strictEqual(getRequestDispatcher(request), agent) }) diff --git a/test/fetch/issue-3767.js b/test/fetch/issue-3767.js index aa742aaffe6..b3223298f4d 100644 --- a/test/fetch/issue-3767.js +++ b/test/fetch/issue-3767.js @@ -4,16 +4,15 @@ const { once } = require('node:events') const { createServer } = require('node:http') const { test } = require('node:test') const { fetch } = require('../..') -const { tspl } = require('@matteo.collina/tspl') // https://github.com/nodejs/undici/issues/3767 test('referrerPolicy unsafe-url is respected', async (t) => { - const { completed, deepEqual } = tspl(t, { plan: 1 }) + t.plan(1) const referrer = 'https://google.com/hello/world' const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - deepEqual(req.headers.referer, referrer) + t.assert.deepEqual(req.headers.referer, referrer) res.end() }).listen(0) @@ -25,6 +24,4 @@ test('referrerPolicy unsafe-url is respected', async (t) => { referrer, referrerPolicy: 'unsafe-url' }) - - await completed }) diff --git a/test/fetch/issue-4105.js b/test/fetch/issue-4105.js index 8d4b480eca8..4050c175ae9 100644 --- a/test/fetch/issue-4105.js +++ b/test/fetch/issue-4105.js @@ -4,14 +4,16 @@ const { once } = require('node:events') const { createServer } = require('node:http') const { test } = require('node:test') const { fetch } = require('../..') -const { tspl } = require('@matteo.collina/tspl') const { PerformanceObserver } = require('node:perf_hooks') +const { createDeferredPromise } = require('../../lib/util/promise') const isAtLeastv22 = process.versions.node.split('.').map(Number)[0] >= 22 // https://github.com/nodejs/undici/issues/4105 test('markResourceTiming responseStatus is set', { skip: !isAtLeastv22 }, async (t) => { - const { completed, deepEqual } = tspl(t, { plan: 1 }) + t.plan(1) + + const promise = createDeferredPromise() const server = createServer((req, res) => { res.statusCode = 200 @@ -23,12 +25,13 @@ test('markResourceTiming responseStatus is set', { skip: !isAtLeastv22 }, async new PerformanceObserver(items => { items.getEntries().forEach(entry => { - deepEqual(entry.responseStatus, 200) + t.assert.strictEqual(entry.responseStatus, 200) + promise.resolve() }) }).observe({ type: 'resource', buffered: true }) const response = await fetch('http://localhost:3000') await response.text() - await completed + await promise.promise }) diff --git a/test/fetch/issue-rsshub-15532.js b/test/fetch/issue-rsshub-15532.js index 988e12ceb5c..e8c20c482a5 100644 --- a/test/fetch/issue-rsshub-15532.js +++ b/test/fetch/issue-rsshub-15532.js @@ -4,14 +4,13 @@ const { once } = require('node:events') const { createServer } = require('node:http') const { test } = require('node:test') const { fetch } = require('../..') -const { tspl } = require('@matteo.collina/tspl') // https://github.com/DIYgod/RSSHub/issues/15532 test('An invalid Origin header is not set', async (t) => { - const { deepStrictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - deepStrictEqual(req.headers.origin, undefined) + t.assert.deepStrictEqual(req.headers.origin, undefined) res.end() }).listen(0) diff --git a/test/fetch/iterators.js b/test/fetch/iterators.js index dd8c420b486..7e5ba8bbaea 100644 --- a/test/fetch/iterators.js +++ b/test/fetch/iterators.js @@ -1,7 +1,6 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') const { Headers, FormData } = require('../..') test('Implements " Iterator" properly', async (t) => { @@ -14,18 +13,18 @@ test('Implements " Iterator" properly', async (t) => { const IteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())) const iteratorProto = Object.getPrototypeOf(gen) - assert.ok(gen.constructor === IteratorPrototype.constructor) - assert.ok(gen.prototype === undefined) + t.assert.ok(gen.constructor === IteratorPrototype.constructor) + t.assert.ok(gen.prototype === undefined) // eslint-disable-next-line no-proto - assert.strictEqual(gen.__proto__[Symbol.toStringTag], 'Headers Iterator') + t.assert.strictEqual(gen.__proto__[Symbol.toStringTag], 'Headers Iterator') // https://github.com/node-fetch/node-fetch/issues/1119#issuecomment-100222049 - assert.ok(!(Headers.prototype[iterable] instanceof function * () {}.constructor)) + t.assert.ok(!(Headers.prototype[iterable] instanceof function * () {}.constructor)) // eslint-disable-next-line no-proto - assert.ok(gen.__proto__.next.__proto__ === Function.prototype) + t.assert.ok(gen.__proto__.next.__proto__ === Function.prototype) // https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object // "The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%." - assert.strictEqual(gen[Symbol.iterator], IteratorPrototype[Symbol.iterator]) - assert.strictEqual(Object.getPrototypeOf(iteratorProto), IteratorPrototype) + t.assert.strictEqual(gen[Symbol.iterator], IteratorPrototype[Symbol.iterator]) + t.assert.strictEqual(Object.getPrototypeOf(iteratorProto), IteratorPrototype) } }) @@ -38,18 +37,18 @@ test('Implements " Iterator" properly', async (t) => { const IteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())) const iteratorProto = Object.getPrototypeOf(gen) - assert.ok(gen.constructor === IteratorPrototype.constructor) - assert.ok(gen.prototype === undefined) + t.assert.ok(gen.constructor === IteratorPrototype.constructor) + t.assert.ok(gen.prototype === undefined) // eslint-disable-next-line no-proto - assert.strictEqual(gen.__proto__[Symbol.toStringTag], 'FormData Iterator') + t.assert.strictEqual(gen.__proto__[Symbol.toStringTag], 'FormData Iterator') // https://github.com/node-fetch/node-fetch/issues/1119#issuecomment-100222049 - assert.ok(!(Headers.prototype[iterable] instanceof function * () {}.constructor)) + t.assert.ok(!(Headers.prototype[iterable] instanceof function * () {}.constructor)) // eslint-disable-next-line no-proto - assert.ok(gen.__proto__.next.__proto__ === Function.prototype) + t.assert.ok(gen.__proto__.next.__proto__ === Function.prototype) // https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object // "The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%." - assert.strictEqual(gen[Symbol.iterator], IteratorPrototype[Symbol.iterator]) - assert.strictEqual(Object.getPrototypeOf(iteratorProto), IteratorPrototype) + t.assert.strictEqual(gen[Symbol.iterator], IteratorPrototype[Symbol.iterator]) + t.assert.strictEqual(Object.getPrototypeOf(iteratorProto), IteratorPrototype) } }) @@ -58,16 +57,16 @@ test('Implements " Iterator" properly', async (t) => { const headers = new Headers([['a', 'b'], ['c', 'd']]) const gen = headers.entries() - assert.strictEqual(typeof gen[Symbol.toStringTag], 'string') - assert.strictEqual(typeof gen[Symbol.iterator], 'function') + t.assert.strictEqual(typeof gen[Symbol.toStringTag], 'string') + t.assert.strictEqual(typeof gen[Symbol.iterator], 'function') }) await t.test('FormData', () => { const fd = new FormData() const gen = fd.entries() - assert.strictEqual(typeof gen[Symbol.toStringTag], 'string') - assert.strictEqual(typeof gen[Symbol.iterator], 'function') + t.assert.strictEqual(typeof gen[Symbol.toStringTag], 'string') + t.assert.strictEqual(typeof gen[Symbol.iterator], 'function') }) }) @@ -76,43 +75,43 @@ test('Implements " Iterator" properly', async (t) => { const headers = new Headers([['a', 'b'], ['c', 'd']]) const gen = headers.entries() - assert.strictEqual(gen.return, undefined) - assert.strictEqual(gen.throw, undefined) - assert.strictEqual(typeof gen.next, 'function') + t.assert.strictEqual(gen.return, undefined) + t.assert.strictEqual(gen.throw, undefined) + t.assert.strictEqual(typeof gen.next, 'function') }) await t.test('FormData', () => { const fd = new FormData() const gen = fd.entries() - assert.strictEqual(gen.return, undefined) - assert.strictEqual(gen.throw, undefined) - assert.strictEqual(typeof gen.next, 'function') + t.assert.strictEqual(gen.return, undefined) + t.assert.strictEqual(gen.throw, undefined) + t.assert.strictEqual(typeof gen.next, 'function') }) }) await t.test('Symbol.iterator', () => { // Headers const headerValues = new Headers([['a', 'b']]).entries()[Symbol.iterator]() - assert.deepStrictEqual(Array.from(headerValues), [['a', 'b']]) + t.assert.deepStrictEqual(Array.from(headerValues), [['a', 'b']]) // FormData const formdata = new FormData() formdata.set('a', 'b') const formdataValues = formdata.entries()[Symbol.iterator]() - assert.deepStrictEqual(Array.from(formdataValues), [['a', 'b']]) + t.assert.deepStrictEqual(Array.from(formdataValues), [['a', 'b']]) }) await t.test('brand check', () => { // Headers - assert.throws(() => { + t.assert.throws(() => { const gen = new Headers().entries() // eslint-disable-next-line no-proto gen.__proto__.next() }, TypeError) // FormData - assert.throws(() => { + t.assert.throws(() => { const gen = new FormData().entries() // eslint-disable-next-line no-proto gen.__proto__.next() diff --git a/test/fetch/long-lived-abort-controller.js b/test/fetch/long-lived-abort-controller.js index 22791803b63..176fdcdfdd4 100644 --- a/test/fetch/long-lived-abort-controller.js +++ b/test/fetch/long-lived-abort-controller.js @@ -5,7 +5,6 @@ const { fetch } = require('../../') const { once, setMaxListeners } = require('node:events') const { test } = require('node:test') const { closeServerAsPromise } = require('../utils/node-http') -const { strictEqual } = require('node:assert') test('long-lived-abort-controller', async (t) => { const server = http.createServer({ joinDuplicateHeaders: true }, (req, res) => { @@ -43,5 +42,5 @@ test('long-lived-abort-controller', async (t) => { await res.text() } - strictEqual(warningEmitted, false) + t.assert.strictEqual(warningEmitted, false) }) diff --git a/test/fetch/max-listeners.js b/test/fetch/max-listeners.js index 8537f477d41..2fa5fc7c346 100644 --- a/test/fetch/max-listeners.js +++ b/test/fetch/max-listeners.js @@ -2,7 +2,6 @@ const { setMaxListeners, getMaxListeners, defaultMaxListeners } = require('node:events') const { test } = require('node:test') -const assert = require('node:assert') const { Request } = require('../..') test('test max listeners', (t) => { @@ -12,5 +11,5 @@ test('test max listeners', (t) => { // eslint-disable-next-line no-new new Request('http://asd', { signal: controller.signal }) } - assert.strictEqual(getMaxListeners(controller.signal), Infinity) + t.assert.strictEqual(getMaxListeners(controller.signal), Infinity) }) diff --git a/test/fetch/pull-dont-push.js b/test/fetch/pull-dont-push.js index 7489b3fb0cd..7c32c16200c 100644 --- a/test/fetch/pull-dont-push.js +++ b/test/fetch/pull-dont-push.js @@ -1,7 +1,6 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') const { fetch } = require('../..') const { createServer } = require('node:http') const { once } = require('node:events') @@ -42,7 +41,7 @@ test('pull dont\'t push', async (t) => { await sleep(1000) socket.destroy() - assert.strictEqual(count < max, true) // the stream should be closed before the max + t.assert.strictEqual(count < max, true) // the stream should be closed before the max // consume the stream try { diff --git a/test/fetch/readable-stream-from.js b/test/fetch/readable-stream-from.js index f0ae52729e5..7b047d31eec 100644 --- a/test/fetch/readable-stream-from.js +++ b/test/fetch/readable-stream-from.js @@ -1,11 +1,10 @@ 'use strict' -const { deepStrictEqual } = require('node:assert') const { test } = require('node:test') const { Response } = require('../..') // https://github.com/nodejs/node/issues/56474 -test('ReadableStream empty enqueue then other enqueued', async () => { +test('ReadableStream empty enqueue then other enqueued', async (t) => { const iterable = { async * [Symbol.asyncIterator] () { yield '' @@ -15,10 +14,10 @@ test('ReadableStream empty enqueue then other enqueued', async () => { } const response = new Response(iterable) - deepStrictEqual(await response.text(), '34') + t.assert.deepStrictEqual(await response.text(), '34') }) -test('ReadableStream empty enqueue', async () => { +test('ReadableStream empty enqueue', async (t) => { const iterable = { async * [Symbol.asyncIterator] () { yield '' @@ -26,5 +25,5 @@ test('ReadableStream empty enqueue', async () => { } const response = new Response(iterable) - deepStrictEqual(await response.text(), '') + t.assert.deepStrictEqual(await response.text(), '') }) diff --git a/test/fetch/redirect-cross-origin-header.js b/test/fetch/redirect-cross-origin-header.js index 8f0d58587e7..3c0df8b6746 100644 --- a/test/fetch/redirect-cross-origin-header.js +++ b/test/fetch/redirect-cross-origin-header.js @@ -1,25 +1,24 @@ 'use strict' const { test } = require('node:test') -const { tspl } = require('@matteo.collina/tspl') const { createServer } = require('node:http') const { once } = require('node:events') const { fetch } = require('../..') test('Cross-origin redirects clear forbidden headers', async (t) => { - const { strictEqual } = tspl(t, { plan: 6 }) + t.plan(6) const server1 = createServer({ joinDuplicateHeaders: true }, (req, res) => { - strictEqual(req.headers.cookie, undefined) - strictEqual(req.headers.authorization, undefined) - strictEqual(req.headers['proxy-authorization'], undefined) + t.assert.strictEqual(req.headers.cookie, undefined) + t.assert.strictEqual(req.headers.authorization, undefined) + t.assert.strictEqual(req.headers['proxy-authorization'], undefined) res.end('redirected') }).listen(0) const server2 = createServer({ joinDuplicateHeaders: true }, (req, res) => { - strictEqual(req.headers.authorization, 'test') - strictEqual(req.headers.cookie, 'ddd=dddd') + t.assert.strictEqual(req.headers.authorization, 'test') + t.assert.strictEqual(req.headers.cookie, 'ddd=dddd') res.writeHead(302, { ...req.headers, @@ -47,5 +46,5 @@ test('Cross-origin redirects clear forbidden headers', async (t) => { }) const text = await res.text() - strictEqual(text, 'redirected') + t.assert.strictEqual(text, 'redirected') }) diff --git a/test/fetch/redirect.js b/test/fetch/redirect.js index 6d41ff30849..913ec7972e9 100644 --- a/test/fetch/redirect.js +++ b/test/fetch/redirect.js @@ -1,7 +1,6 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') const { createServer } = require('node:http') const { once } = require('node:events') const { fetch } = require('../..') @@ -26,8 +25,8 @@ test('Redirecting with a body does not cancel the current request - #1776', asyn await once(server, 'listening') const resp = await fetch(`http://localhost:${server.address().port}/redirect`) - assert.strictEqual(await resp.text(), '/redirect/') - assert.ok(resp.redirected) + t.assert.strictEqual(await resp.text(), '/redirect/') + t.assert.ok(resp.redirected) }) test('Redirecting with an empty body does not throw an error - #2027', async (t) => { @@ -47,8 +46,8 @@ test('Redirecting with an empty body does not throw an error - #2027', async (t) await once(server, 'listening') const resp = await fetch(`http://localhost:${server.address().port}/redirect`, { method: 'PUT', body: '' }) - assert.strictEqual(await resp.text(), '/redirect/') - assert.ok(resp.redirected) + t.assert.strictEqual(await resp.text(), '/redirect/') + t.assert.ok(resp.redirected) }) test('Redirecting with a body does not fail to write body - #2543', async (t) => { @@ -60,7 +59,7 @@ test('Redirecting with a body does not fail to write body - #2543', async (t) => } else { let body = '' req.on('data', (chunk) => { body += chunk }) - req.on('end', () => assert.strictEqual(body, 'body')) + req.on('end', () => t.assert.strictEqual(body, 'body')) res.write('ok') res.end() } @@ -73,6 +72,6 @@ test('Redirecting with a body does not fail to write body - #2543', async (t) => method: 'POST', body: 'body' }) - assert.strictEqual(await resp.text(), 'ok') - assert.ok(resp.redirected) + t.assert.strictEqual(await resp.text(), 'ok') + t.assert.ok(resp.redirected) }) diff --git a/test/fetch/referrrer-policy.js b/test/fetch/referrrer-policy.js index 612d8e29d0d..849aab98b6c 100644 --- a/test/fetch/referrrer-policy.js +++ b/test/fetch/referrrer-policy.js @@ -4,7 +4,6 @@ const { once } = require('node:events') const { createServer } = require('node:http') const { describe, test } = require('node:test') const { fetch } = require('../..') -const tspl = require('@matteo.collina/tspl') describe('referrer-policy', () => { ;[ @@ -71,7 +70,7 @@ describe('referrer-policy', () => { ] ].forEach(([title, responseReferrerPolicy, expectedReferrerPolicy, referrer]) => { test(title, async (t) => { - t = tspl(t, { plan: 1 }) + t.plan(1) const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { switch (res.req.url) { @@ -85,16 +84,16 @@ describe('referrer-policy', () => { case '/target': switch (expectedReferrerPolicy) { case 'no-referrer': - t.strictEqual(req.headers['referer'], undefined) + t.assert.strictEqual(req.headers['referer'], undefined) break case 'origin': - t.strictEqual(req.headers['referer'], `http://127.0.0.1:${port}/`) + t.assert.strictEqual(req.headers['referer'], `http://127.0.0.1:${port}/`) break case 'strict-origin-when-cross-origin': - t.strictEqual(req.headers['referer'], `http://127.0.0.1:${port}/index.html?test=1`) + t.assert.strictEqual(req.headers['referer'], `http://127.0.0.1:${port}/index.html?test=1`) break case 'unsafe-url': - t.strictEqual(req.headers['referer'], `http://127.0.0.1:${port}/index.html?test=1`) + t.assert.strictEqual(req.headers['referer'], `http://127.0.0.1:${port}/index.html?test=1`) break } res.writeHead(200, 'dummy', { 'Content-Type': 'text/plain' }) @@ -111,8 +110,6 @@ describe('referrer-policy', () => { referrer: referrer || `http://127.0.0.1:${port}/index.html?test=1` }) - await t.completed - server.closeAllConnections() server.closeIdleConnections() server.close() diff --git a/test/fetch/relative-url.js b/test/fetch/relative-url.js index b6e28bda7ea..8d665c4e3c4 100644 --- a/test/fetch/relative-url.js +++ b/test/fetch/relative-url.js @@ -1,7 +1,6 @@ 'use strict' const { test, afterEach } = require('node:test') -const assert = require('node:assert') const { createServer } = require('node:http') const { once } = require('node:events') const { @@ -15,35 +14,35 @@ const { closeServerAsPromise } = require('../utils/node-http') afterEach(() => setGlobalOrigin(undefined)) -test('setGlobalOrigin & getGlobalOrigin', () => { - assert.strictEqual(getGlobalOrigin(), undefined) +test('setGlobalOrigin & getGlobalOrigin', (t) => { + t.assert.strictEqual(getGlobalOrigin(), undefined) setGlobalOrigin('http://localhost:3000') - assert.deepStrictEqual(getGlobalOrigin(), new URL('http://localhost:3000')) + t.assert.deepStrictEqual(getGlobalOrigin(), new URL('http://localhost:3000')) setGlobalOrigin(undefined) - assert.strictEqual(getGlobalOrigin(), undefined) + t.assert.strictEqual(getGlobalOrigin(), undefined) setGlobalOrigin(new URL('http://localhost:3000')) - assert.deepStrictEqual(getGlobalOrigin(), new URL('http://localhost:3000')) + t.assert.deepStrictEqual(getGlobalOrigin(), new URL('http://localhost:3000')) - assert.throws(() => { + t.assert.throws(() => { setGlobalOrigin('invalid.url') }, TypeError) - assert.throws(() => { + t.assert.throws(() => { setGlobalOrigin('wss://invalid.protocol') }, TypeError) - assert.throws(() => setGlobalOrigin(true)) + t.assert.throws(() => setGlobalOrigin(true)) }) -test('Response.redirect', () => { - assert.throws(() => { +test('Response.redirect', (t) => { + t.assert.throws(() => { Response.redirect('/relative/path', 302) }, TypeError('Failed to parse URL from /relative/path')) - assert.doesNotThrow(() => { + t.assert.doesNotThrow(() => { setGlobalOrigin('http://localhost:3000') Response.redirect('/relative/path', 302) }) @@ -51,16 +50,16 @@ test('Response.redirect', () => { setGlobalOrigin('http://localhost:3000') const response = Response.redirect('/relative/path', 302) // See step #7 of https://fetch.spec.whatwg.org/#dom-response-redirect - assert.strictEqual(response.headers.get('location'), 'http://localhost:3000/relative/path') + t.assert.strictEqual(response.headers.get('location'), 'http://localhost:3000/relative/path') }) test('new Request', (t) => { - assert.throws( + t.assert.throws( () => new Request('/relative/path'), TypeError('Failed to parse URL from /relative/path') ) - assert.doesNotThrow(() => { + t.assert.doesNotThrow(() => { setGlobalOrigin('http://localhost:3000') // eslint-disable-next-line no-new new Request('/relative/path') @@ -68,15 +67,15 @@ test('new Request', (t) => { setGlobalOrigin('http://localhost:3000') const request = new Request('/relative/path') - assert.strictEqual(request.url, 'http://localhost:3000/relative/path') + t.assert.strictEqual(request.url, 'http://localhost:3000/relative/path') }) test('fetch', async (t) => { - await assert.rejects(fetch('/relative/path'), TypeError('Failed to parse URL from /relative/path')) + await t.assert.rejects(fetch('/relative/path'), TypeError('Failed to parse URL from /relative/path')) await t.test('Basic fetch', async (t) => { const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - assert.strictEqual(req.url, '/relative/path') + t.assert.strictEqual(req.url, '/relative/path') res.end() }).listen(0) @@ -84,12 +83,12 @@ test('fetch', async (t) => { t.after(closeServerAsPromise(server)) await once(server, 'listening') - await assert.doesNotReject(fetch('/relative/path')) + await t.assert.doesNotReject(fetch('/relative/path')) }) await t.test('fetch return', async (t) => { const server = createServer({ joinDuplicateHeaders: true }, (req, res) => { - assert.strictEqual(req.url, '/relative/path') + t.assert.strictEqual(req.url, '/relative/path') res.end() }).listen(0) @@ -99,6 +98,6 @@ test('fetch', async (t) => { const response = await fetch('/relative/path') - assert.strictEqual(response.url, `http://localhost:${server.address().port}/relative/path`) + t.assert.strictEqual(response.url, `http://localhost:${server.address().port}/relative/path`) }) }) diff --git a/test/fetch/request-inspect-custom.js b/test/fetch/request-inspect-custom.js index e2e60bdab7b..9fdcb0f6901 100644 --- a/test/fetch/request-inspect-custom.js +++ b/test/fetch/request-inspect-custom.js @@ -1,12 +1,11 @@ 'use strict' const { describe, it } = require('node:test') -const assert = require('node:assert') const util = require('node:util') const { Request } = require('../../') describe('Request custom inspection', () => { - it('should return a custom inspect output', () => { + it('should return a custom inspect output', (t) => { const request = new Request('https://example.com/api', { method: 'POST', headers: { @@ -17,6 +16,6 @@ describe('Request custom inspection', () => { const inspectedOutput = util.inspect(request) const expectedOutput = "Request {\n method: 'POST',\n url: 'https://example.com/api',\n headers: Headers { 'Content-Type': 'application/json' },\n destination: '',\n referrer: 'about:client',\n referrerPolicy: '',\n mode: 'cors',\n credentials: 'same-origin',\n cache: 'default',\n redirect: 'follow',\n integrity: '',\n keepalive: false,\n isReloadNavigation: false,\n isHistoryNavigation: false,\n signal: AbortSignal { aborted: false }\n}" - assert.strictEqual(inspectedOutput, expectedOutput) + t.assert.strictEqual(inspectedOutput, expectedOutput) }) }) diff --git a/test/fetch/request.js b/test/fetch/request.js index 1f4061b2ebe..51e92b5c061 100644 --- a/test/fetch/request.js +++ b/test/fetch/request.js @@ -3,8 +3,6 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') -const { tspl } = require('@matteo.collina/tspl') const { Request, Headers, @@ -13,154 +11,154 @@ const { test('arg validation', async (t) => { // constructor - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line new Request() }, TypeError) - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line new Request('http://asd', 0) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { const url = new URL('http://asd') url.password = 'asd' // eslint-disable-next-line new Request(url) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { const url = new URL('http://asd') url.username = 'asd' // eslint-disable-next-line new Request(url) }, TypeError) - assert.doesNotThrow(() => { + t.assert.doesNotThrow(() => { // eslint-disable-next-line new Request('http://asd', undefined) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line new Request('http://asd', { window: {} }) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line new Request('http://asd', { window: 1 }) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line new Request('http://asd', { mode: 'navigate' }) }) - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line new Request('http://asd', { referrerPolicy: 'agjhagna' }) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line new Request('http://asd', { mode: 'agjhagna' }) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line new Request('http://asd', { credentials: 'agjhagna' }) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line new Request('http://asd', { cache: 'agjhagna' }) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line new Request('http://asd', { method: 'agjhagnaöööö' }) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line new Request('http://asd', { method: 'TRACE' }) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Request.prototype.destination.toString() }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Request.prototype.referrer.toString() }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Request.prototype.referrerPolicy.toString() }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Request.prototype.mode.toString() }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Request.prototype.credentials.toString() }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Request.prototype.cache.toString() }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Request.prototype.redirect.toString() }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Request.prototype.integrity.toString() }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Request.prototype.keepalive.toString() }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Request.prototype.isReloadNavigation.toString() }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Request.prototype.isHistoryNavigation.toString() }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Request.prototype.signal.toString() }, TypeError) - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line no-unused-expressions Request.prototype.body }, TypeError) - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line no-unused-expressions Request.prototype.bodyUsed }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Request.prototype.clone.call(null) }, TypeError) - assert.doesNotThrow(() => { + t.assert.doesNotThrow(() => { Request.prototype[Symbol.toStringTag].charAt(0) }) @@ -171,7 +169,7 @@ test('arg validation', async (t) => { 'blob', 'formData' ]) { - await assert.rejects(async () => { + await t.assert.rejects(async () => { await new Request('http://localhost')[method].call({ blob () { return { @@ -185,104 +183,104 @@ test('arg validation', async (t) => { } }) -test('undefined window', () => { - assert.doesNotThrow(() => new Request('http://asd', { window: undefined })) +test('undefined window', (t) => { + t.assert.doesNotThrow(() => new Request('http://asd', { window: undefined })) }) -test('undefined body', () => { +test('undefined body', (t) => { const req = new Request('http://asd', { body: undefined }) - assert.strictEqual(req.body, null) + t.assert.strictEqual(req.body, null) }) -test('undefined method', () => { +test('undefined method', (t) => { const req = new Request('http://asd', { method: undefined }) - assert.strictEqual(req.method, 'GET') + t.assert.strictEqual(req.method, 'GET') }) -test('undefined headers', () => { +test('undefined headers', (t) => { const req = new Request('http://asd', { headers: undefined }) - assert.strictEqual([...req.headers.entries()].length, 0) + t.assert.strictEqual([...req.headers.entries()].length, 0) }) -test('undefined referrer', () => { +test('undefined referrer', (t) => { const req = new Request('http://asd', { referrer: undefined }) - assert.strictEqual(req.referrer, 'about:client') + t.assert.strictEqual(req.referrer, 'about:client') }) -test('undefined referrerPolicy', () => { +test('undefined referrerPolicy', (t) => { const req = new Request('http://asd', { referrerPolicy: undefined }) - assert.strictEqual(req.referrerPolicy, '') + t.assert.strictEqual(req.referrerPolicy, '') }) -test('undefined mode', () => { +test('undefined mode', (t) => { const req = new Request('http://asd', { mode: undefined }) - assert.strictEqual(req.mode, 'cors') + t.assert.strictEqual(req.mode, 'cors') }) -test('undefined credentials', () => { +test('undefined credentials', (t) => { const req = new Request('http://asd', { credentials: undefined }) - assert.strictEqual(req.credentials, 'same-origin') + t.assert.strictEqual(req.credentials, 'same-origin') }) -test('undefined cache', () => { +test('undefined cache', (t) => { const req = new Request('http://asd', { cache: undefined }) - assert.strictEqual(req.cache, 'default') + t.assert.strictEqual(req.cache, 'default') }) -test('undefined redirect', () => { +test('undefined redirect', (t) => { const req = new Request('http://asd', { redirect: undefined }) - assert.strictEqual(req.redirect, 'follow') + t.assert.strictEqual(req.redirect, 'follow') }) -test('undefined keepalive', () => { +test('undefined keepalive', (t) => { const req = new Request('http://asd', { keepalive: undefined }) - assert.strictEqual(req.keepalive, false) + t.assert.strictEqual(req.keepalive, false) }) -test('undefined integrity', () => { +test('undefined integrity', (t) => { const req = new Request('http://asd', { integrity: undefined }) - assert.strictEqual(req.integrity, '') + t.assert.strictEqual(req.integrity, '') }) -test('null integrity', () => { +test('null integrity', (t) => { const req = new Request('http://asd', { integrity: null }) - assert.strictEqual(req.integrity, 'null') + t.assert.strictEqual(req.integrity, 'null') }) -test('undefined signal', () => { +test('undefined signal', (t) => { const req = new Request('http://asd', { signal: undefined }) - assert.strictEqual(req.signal.aborted, false) + t.assert.strictEqual(req.signal.aborted, false) }) -test('pre aborted signal', () => { +test('pre aborted signal', (t) => { const ac = new AbortController() ac.abort('gwak') const req = new Request('http://asd', { signal: ac.signal }) - assert.strictEqual(req.signal.aborted, true) - assert.strictEqual(req.signal.reason, 'gwak') + t.assert.strictEqual(req.signal.aborted, true) + t.assert.strictEqual(req.signal.reason, 'gwak') }) test('post aborted signal', (t) => { - const { strictEqual } = tspl(t, { plan: 2 }) + t.plan(2) const ac = new AbortController() const req = new Request('http://asd', { signal: ac.signal }) - strictEqual(req.signal.aborted, false) + t.assert.strictEqual(req.signal.aborted, false) ac.signal.addEventListener('abort', () => { - strictEqual(req.signal.reason, 'gwak') + t.assert.strictEqual(req.signal.reason, 'gwak') }, { once: true }) ac.abort('gwak') }) -test('pre aborted signal cloned', () => { +test('pre aborted signal cloned', (t) => { const ac = new AbortController() ac.abort('gwak') const req = new Request('http://asd', { signal: ac.signal }).clone() - assert.strictEqual(req.signal.aborted, true) - assert.strictEqual(req.signal.reason, 'gwak') + t.assert.strictEqual(req.signal.aborted, true) + t.assert.strictEqual(req.signal.reason, 'gwak') }) -test('URLSearchParams body with Headers object - issue #1407', async () => { +test('URLSearchParams body with Headers object - issue #1407', async (t) => { const body = new URLSearchParams({ abc: 123 }) @@ -298,127 +296,127 @@ test('URLSearchParams body with Headers object - issue #1407', async () => { } ) - assert.strictEqual(request.headers.get('content-type'), 'application/x-www-form-urlencoded;charset=UTF-8') - assert.strictEqual(request.headers.get('authorization'), 'test') - assert.strictEqual(await request.text(), 'abc=123') + t.assert.strictEqual(request.headers.get('content-type'), 'application/x-www-form-urlencoded;charset=UTF-8') + t.assert.strictEqual(request.headers.get('authorization'), 'test') + t.assert.strictEqual(await request.text(), 'abc=123') }) test('post aborted signal cloned', (t) => { - const { strictEqual } = tspl(t, { plan: 2 }) + t.plan(2) const ac = new AbortController() const req = new Request('http://asd', { signal: ac.signal }).clone() - strictEqual(req.signal.aborted, false) + t.assert.strictEqual(req.signal.aborted, false) ac.signal.addEventListener('abort', () => { - strictEqual(req.signal.reason, 'gwak') + t.assert.strictEqual(req.signal.reason, 'gwak') }, { once: true }) ac.abort('gwak') }) test('Passing headers in init', async (t) => { // https://github.com/nodejs/undici/issues/1400 - await t.test('Headers instance', () => { + await t.test('Headers instance', (t) => { const req = new Request('http://localhost', { headers: new Headers({ key: 'value' }) }) - assert.strictEqual(req.headers.get('key'), 'value') + t.assert.strictEqual(req.headers.get('key'), 'value') }) - await t.test('key:value object', () => { + await t.test('key:value object', (t) => { const req = new Request('http://localhost', { headers: { key: 'value' } }) - assert.strictEqual(req.headers.get('key'), 'value') + t.assert.strictEqual(req.headers.get('key'), 'value') }) - await t.test('[key, value][]', () => { + await t.test('[key, value][]', (t) => { const req = new Request('http://localhost', { headers: [['key', 'value']] }) - assert.strictEqual(req.headers.get('key'), 'value') + t.assert.strictEqual(req.headers.get('key'), 'value') }) }) -test('Symbol.toStringTag', () => { +test('Symbol.toStringTag', (t) => { const req = new Request('http://localhost') - assert.strictEqual(req[Symbol.toStringTag], 'Request') - assert.strictEqual(Request.prototype[Symbol.toStringTag], 'Request') + t.assert.strictEqual(req[Symbol.toStringTag], 'Request') + t.assert.strictEqual(Request.prototype[Symbol.toStringTag], 'Request') }) -test('invalid RequestInit values', () => { +test('invalid RequestInit values', (t) => { /* eslint-disable no-new */ - assert.throws(() => { + t.assert.throws(() => { new Request('http://l', { mode: 'CoRs' }) }, TypeError, 'not exact case = error') - assert.throws(() => { + t.assert.throws(() => { new Request('http://l', { mode: 'random' }) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { new Request('http://l', { credentials: 'OMIt' }) }, TypeError, 'not exact case = error') - assert.throws(() => { + t.assert.throws(() => { new Request('http://l', { credentials: 'random' }) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { new Request('http://l', { cache: 'DeFaULt' }) }, TypeError, 'not exact case = error') - assert.throws(() => { + t.assert.throws(() => { new Request('http://l', { cache: 'random' }) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { new Request('http://l', { redirect: 'FOllOW' }) }, TypeError, 'not exact case = error') - assert.throws(() => { + t.assert.throws(() => { new Request('http://l', { redirect: 'random' }) }, TypeError) /* eslint-enable no-new */ }) -test('RequestInit.signal option', async () => { - assert.throws(() => { +test('RequestInit.signal option', async (t) => { + t.assert.throws(() => { // eslint-disable-next-line no-new new Request('http://asd', { signal: true }) }, TypeError) - await assert.rejects(fetch('http://asd', { + await t.assert.rejects(fetch('http://asd', { signal: false }), TypeError) }) // https://github.com/nodejs/undici/issues/2050 -test('set-cookie headers get cleared when passing a Request as first param', () => { +test('set-cookie headers get cleared when passing a Request as first param', (t) => { const req1 = new Request('http://localhost', { headers: { 'set-cookie': 'a=1' } }) - assert.deepStrictEqual([...req1.headers], [['set-cookie', 'a=1']]) + t.assert.deepStrictEqual([...req1.headers], [['set-cookie', 'a=1']]) const req2 = new Request(req1, { headers: {} }) - assert.deepStrictEqual([...req1.headers], [['set-cookie', 'a=1']]) - assert.deepStrictEqual([...req2.headers], []) - assert.deepStrictEqual(req2.headers.getSetCookie(), []) + t.assert.deepStrictEqual([...req1.headers], [['set-cookie', 'a=1']]) + t.assert.deepStrictEqual([...req2.headers], []) + t.assert.deepStrictEqual(req2.headers.getSetCookie(), []) }) // https://github.com/nodejs/undici/issues/2124 -test('request.referrer', () => { +test('request.referrer', (t) => { for (const referrer of ['about://client', 'about://client:1234']) { const request = new Request('http://a', { referrer }) - assert.strictEqual(request.referrer, 'about:client') + t.assert.strictEqual(request.referrer, 'about:client') } }) @@ -426,22 +424,22 @@ test('request.referrer', () => { test('Clone the set-cookie header when Request is passed as the first parameter and no header is passed.', (t) => { const request = new Request('http://localhost', { headers: { 'set-cookie': 'A' } }) const request2 = new Request(request) - assert.deepStrictEqual([...request.headers], [['set-cookie', 'A']]) + t.assert.deepStrictEqual([...request.headers], [['set-cookie', 'A']]) request2.headers.append('set-cookie', 'B') - assert.deepStrictEqual([...request.headers], [['set-cookie', 'A']]) - assert.strictEqual(request.headers.getSetCookie().join(', '), request.headers.get('set-cookie')) - assert.strictEqual(request2.headers.getSetCookie().join(', '), request2.headers.get('set-cookie')) + t.assert.deepStrictEqual([...request.headers], [['set-cookie', 'A']]) + t.assert.strictEqual(request.headers.getSetCookie().join(', '), request.headers.get('set-cookie')) + t.assert.strictEqual(request2.headers.getSetCookie().join(', '), request2.headers.get('set-cookie')) }) // Tests for optimization introduced in https://github.com/nodejs/undici/pull/2456 test('keys to object prototypes method', (t) => { const request = new Request('http://localhost', { method: 'hasOwnProperty' }) - assert(typeof request.method === 'string') + t.assert.ok(typeof request.method === 'string') }) // https://github.com/nodejs/undici/issues/2465 test('Issue#2465', async (t) => { - const { strictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const request = new Request('http://localhost', { body: new SharedArrayBuffer(0), method: 'POST' }) - strictEqual(await request.text(), '[object SharedArrayBuffer]') + t.assert.strictEqual(await request.text(), '[object SharedArrayBuffer]') }) diff --git a/test/fetch/resource-timing.js b/test/fetch/resource-timing.js index 4def7bf90e2..c060dba30cc 100644 --- a/test/fetch/resource-timing.js +++ b/test/fetch/resource-timing.js @@ -1,7 +1,6 @@ 'use strict' const { test } = require('node:test') -const { tspl } = require('@matteo.collina/tspl') const { createServer } = require('node:http') const { fetch } = require('../..') const { closeServerAsPromise } = require('../utils/node-http') @@ -12,23 +11,23 @@ const { } = require('node:perf_hooks') test('should create a PerformanceResourceTiming after each fetch request', (t, done) => { - const { strictEqual, ok, deepStrictEqual } = tspl(t, { plan: 8 }) + t.plan(8) const obs = new PerformanceObserver(list => { const expectedResourceEntryName = `http://localhost:${server.address().port}/` const entries = list.getEntries() - strictEqual(entries.length, 1) + t.assert.strictEqual(entries.length, 1) const [entry] = entries - strictEqual(entry.name, expectedResourceEntryName) - strictEqual(entry.entryType, 'resource') + t.assert.strictEqual(entry.name, expectedResourceEntryName) + t.assert.strictEqual(entry.entryType, 'resource') - ok(entry.duration >= 0) - ok(entry.startTime >= 0) + t.assert.ok(entry.duration >= 0) + t.assert.ok(entry.startTime >= 0) const entriesByName = list.getEntriesByName(expectedResourceEntryName) - strictEqual(entriesByName.length, 1) - deepStrictEqual(entriesByName[0], entry) + t.assert.strictEqual(entriesByName.length, 1) + t.assert.deepStrictEqual(entriesByName[0], entry) obs.disconnect() performance.clearResourceTimings() @@ -41,19 +40,19 @@ test('should create a PerformanceResourceTiming after each fetch request', (t, d res.end('ok') }).listen(0, async () => { const body = await fetch(`http://localhost:${server.address().port}`) - strictEqual('ok', await body.text()) + t.assert.strictEqual('ok', await body.text()) }) t.after(closeServerAsPromise(server)) }) test('should include encodedBodySize in performance entry', (t, done) => { - const { strictEqual } = tspl(t, { plan: 4 }) + t.plan(4) const obs = new PerformanceObserver(list => { const [entry] = list.getEntries() - strictEqual(entry.encodedBodySize, 2) - strictEqual(entry.decodedBodySize, 2) - strictEqual(entry.transferSize, 2 + 300) + t.assert.strictEqual(entry.encodedBodySize, 2) + t.assert.strictEqual(entry.decodedBodySize, 2) + t.assert.strictEqual(entry.transferSize, 2 + 300) obs.disconnect() performance.clearResourceTimings() @@ -66,30 +65,30 @@ test('should include encodedBodySize in performance entry', (t, done) => { res.end('ok') }).listen(0, async () => { const body = await fetch(`http://localhost:${server.address().port}`) - strictEqual('ok', await body.text()) + t.assert.strictEqual('ok', await body.text()) }) t.after(closeServerAsPromise(server)) }) test('timing entries should be in order', (t, done) => { - const { ok, strictEqual } = tspl(t, { plan: 13 }) + t.plan(13) const obs = new PerformanceObserver(list => { const [entry] = list.getEntries() - ok(entry.startTime > 0) - ok(entry.fetchStart >= entry.startTime) - ok(entry.domainLookupStart >= entry.fetchStart) - ok(entry.domainLookupEnd >= entry.domainLookupStart) - ok(entry.connectStart >= entry.domainLookupEnd) - ok(entry.connectEnd >= entry.connectStart) - ok(entry.requestStart >= entry.connectEnd) - ok(entry.responseStart >= entry.requestStart) - ok(entry.responseEnd >= entry.responseStart) - ok(entry.duration > 0) + t.assert.ok(entry.startTime > 0) + t.assert.ok(entry.fetchStart >= entry.startTime) + t.assert.ok(entry.domainLookupStart >= entry.fetchStart) + t.assert.ok(entry.domainLookupEnd >= entry.domainLookupStart) + t.assert.ok(entry.connectStart >= entry.domainLookupEnd) + t.assert.ok(entry.connectEnd >= entry.connectStart) + t.assert.ok(entry.requestStart >= entry.connectEnd) + t.assert.ok(entry.responseStart >= entry.requestStart) + t.assert.ok(entry.responseEnd >= entry.responseStart) + t.assert.ok(entry.duration > 0) - ok(entry.redirectStart === 0) - ok(entry.redirectEnd === 0) + t.assert.ok(entry.redirectStart === 0) + t.assert.ok(entry.redirectEnd === 0) obs.disconnect() performance.clearResourceTimings() @@ -102,20 +101,20 @@ test('timing entries should be in order', (t, done) => { res.end('ok') }).listen(0, async () => { const body = await fetch(`http://localhost:${server.address().port}/redirect`) - strictEqual('ok', await body.text()) + t.assert.strictEqual('ok', await body.text()) }) t.after(closeServerAsPromise(server)) }) test('redirect timing entries should be included when redirecting', (t, done) => { - const { ok, strictEqual } = tspl(t, { plan: 4 }) + t.plan(4) const obs = new PerformanceObserver(list => { const [entry] = list.getEntries() - ok(entry.redirectStart >= entry.startTime) - ok(entry.redirectEnd >= entry.redirectStart) - ok(entry.connectStart >= entry.redirectEnd) + t.assert.ok(entry.redirectStart >= entry.startTime) + t.assert.ok(entry.redirectEnd >= entry.redirectStart) + t.assert.ok(entry.connectStart >= entry.redirectEnd) obs.disconnect() performance.clearResourceTimings() @@ -134,7 +133,7 @@ test('redirect timing entries should be included when redirecting', (t, done) => res.end('ok') }).listen(0, async () => { const body = await fetch(`http://localhost:${server.address().port}/redirect`) - strictEqual('ok', await body.text()) + t.assert.strictEqual('ok', await body.text()) }) t.after(closeServerAsPromise(server)) diff --git a/test/fetch/response-inspect-custom.js b/test/fetch/response-inspect-custom.js index ca8a5a0fc1a..014c3414414 100644 --- a/test/fetch/response-inspect-custom.js +++ b/test/fetch/response-inspect-custom.js @@ -1,12 +1,11 @@ 'use strict' const { describe, it } = require('node:test') -const assert = require('node:assert') const util = require('node:util') const { Response } = require('../../') describe('Response custom inspection', () => { - it('should return a custom inspect output', () => { + it('should return a custom inspect output', (t) => { const response = new Response(null) const inspectedOutput = util.inspect(response, { depth: null, @@ -25,6 +24,6 @@ describe('Response custom inspection', () => { url: '' }` - assert.strictEqual(inspectedOutput, expectedOutput) + t.assert.strictEqual(inspectedOutput, expectedOutput) }) }) diff --git a/test/fetch/response-json.js b/test/fetch/response-json.js index 7dc6ad20c37..46878cc0d82 100644 --- a/test/fetch/response-json.js +++ b/test/fetch/response-json.js @@ -1,7 +1,6 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') const { Response } = require('../../') // https://github.com/web-platform-tests/wpt/pull/32825/ @@ -18,81 +17,81 @@ const INIT_TESTS = [ [{ headers: { 'x-foo': 'bar' } }, 200, '', APPLICATION_JSON, { 'x-foo': 'bar' }] ] -test('Check response returned by static json() with init', async () => { +test('Check response returned by static json() with init', async (t) => { for (const [init, expectedStatus, expectedStatusText, expectedContentType, expectedHeaders] of INIT_TESTS) { const response = Response.json('hello world', init) - assert.strictEqual(response.type, 'default', "Response's type is default") - assert.strictEqual(response.status, expectedStatus, "Response's status is " + expectedStatus) - assert.strictEqual(response.statusText, expectedStatusText, "Response's statusText is " + JSON.stringify(expectedStatusText)) - assert.strictEqual(response.headers.get('content-type'), expectedContentType, "Response's content-type is " + expectedContentType) + t.assert.strictEqual(response.type, 'default', "Response's type is default") + t.assert.strictEqual(response.status, expectedStatus, "Response's status is " + expectedStatus) + t.assert.strictEqual(response.statusText, expectedStatusText, "Response's statusText is " + JSON.stringify(expectedStatusText)) + t.assert.strictEqual(response.headers.get('content-type'), expectedContentType, "Response's content-type is " + expectedContentType) for (const key in expectedHeaders) { - assert.strictEqual(response.headers.get(key), expectedHeaders[key], "Response's header " + key + ' is ' + JSON.stringify(expectedHeaders[key])) + t.assert.strictEqual(response.headers.get(key), expectedHeaders[key], "Response's header " + key + ' is ' + JSON.stringify(expectedHeaders[key])) } const data = await response.json() - assert.strictEqual(data, 'hello world', "Response's body is 'hello world'") + t.assert.strictEqual(data, 'hello world', "Response's body is 'hello world'") } }) -test('Throws TypeError when calling static json() with an invalid status', () => { +test('Throws TypeError when calling static json() with an invalid status', (t) => { const nullBodyStatus = [204, 205, 304] for (const status of nullBodyStatus) { - assert.throws(() => { + t.assert.throws(() => { Response.json('hello world', { status }) }, TypeError, `Throws TypeError when calling static json() with a status of ${status}`) } }) -test('Check static json() encodes JSON objects correctly', async () => { +test('Check static json() encodes JSON objects correctly', async (t) => { const response = Response.json({ foo: 'bar' }) const data = await response.json() - assert.strictEqual(typeof data, 'object', "Response's json body is an object") - assert.strictEqual(data.foo, 'bar', "Response's json body is { foo: 'bar' }") + t.assert.strictEqual(typeof data, 'object', "Response's json body is an object") + t.assert.strictEqual(data.foo, 'bar', "Response's json body is { foo: 'bar' }") }) -test('Check static json() throws when data is not encodable', () => { - assert.throws(() => { +test('Check static json() throws when data is not encodable', (t) => { + t.assert.throws(() => { Response.json(Symbol('foo')) }, TypeError) }) -test('Check static json() throws when data is circular', () => { +test('Check static json() throws when data is circular', (t) => { const a = { b: 1 } a.a = a - assert.throws(() => { + t.assert.throws(() => { Response.json(a) }, TypeError) }) -test('Check static json() propagates JSON serializer errors', () => { +test('Check static json() propagates JSON serializer errors', (t) => { class CustomError extends Error { name = 'CustomError' } - assert.throws(() => { + t.assert.throws(() => { Response.json({ get foo () { throw new CustomError('bar') } }) }, CustomError) }) // note: these tests are not part of any WPTs -test('unserializable values', () => { - assert.throws(() => { +test('unserializable values', (t) => { + t.assert.throws(() => { Response.json(Symbol('symbol')) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Response.json(undefined) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Response.json() }, TypeError) }) -test('invalid init', () => { - assert.throws(() => { +test('invalid init', (t) => { + t.assert.throws(() => { Response.json(null, 3) }, TypeError) }) diff --git a/test/fetch/response.js b/test/fetch/response.js index 230e70061d0..5c7ce840d87 100644 --- a/test/fetch/response.js +++ b/test/fetch/response.js @@ -1,40 +1,38 @@ 'use strict' -const { test } = require('node:test') -const assert = require('node:assert') +const { describe, test } = require('node:test') const { setImmediate } = require('node:timers/promises') const { AsyncLocalStorage } = require('node:async_hooks') -const { tspl } = require('@matteo.collina/tspl') const { Response, FormData } = require('../../') -test('arg validation', async () => { +test('arg validation', async (t) => { // constructor - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line new Response(null, 0) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line new Response(null, { status: 99 }) }, RangeError) - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line new Response(null, { status: 600 }) }, RangeError) - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line new Response(null, { status: '600' }) }, RangeError) - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line new Response(null, { statusText: '\u0000' @@ -42,7 +40,7 @@ test('arg validation', async () => { }, TypeError) for (const nullStatus of [204, 205, 304]) { - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line new Response(new ArrayBuffer(16), { status: nullStatus @@ -50,53 +48,53 @@ test('arg validation', async () => { }, TypeError) } - assert.doesNotThrow(() => { + t.assert.doesNotThrow(() => { Response.prototype[Symbol.toStringTag].charAt(0) }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Response.prototype.type.toString() }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Response.prototype.url.toString() }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Response.prototype.redirected.toString() }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Response.prototype.status.toString() }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Response.prototype.ok.toString() }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Response.prototype.statusText.toString() }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Response.prototype.headers.toString() }, TypeError) - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line no-unused-expressions Response.prototype.body }, TypeError) - assert.throws(() => { + t.assert.throws(() => { // eslint-disable-next-line no-unused-expressions Response.prototype.bodyUsed }, TypeError) - assert.throws(() => { + t.assert.throws(() => { Response.prototype.clone.call(null) }, TypeError) - await assert.rejects( + await t.assert.rejects( new Response('http://localhost').text.call({ blob () { return { @@ -108,24 +106,24 @@ test('arg validation', async () => { }), TypeError) }) -test('response clone', () => { +test('response clone', (t) => { // https://github.com/nodejs/undici/issues/1122 const response1 = new Response(null, { status: 201 }) const response2 = new Response(undefined, { status: 201 }) - assert.deepStrictEqual(response1.body, response1.clone().body) - assert.deepStrictEqual(response2.body, response2.clone().body) - assert.strictEqual(response2.body, null) + t.assert.deepStrictEqual(response1.body, response1.clone().body) + t.assert.deepStrictEqual(response2.body, response2.clone().body) + t.assert.strictEqual(response2.body, null) }) -test('Symbol.toStringTag', () => { +test('Symbol.toStringTag', (t) => { const resp = new Response() - assert.strictEqual(resp[Symbol.toStringTag], 'Response') - assert.strictEqual(Response.prototype[Symbol.toStringTag], 'Response') + t.assert.strictEqual(resp[Symbol.toStringTag], 'Response') + t.assert.strictEqual(Response.prototype[Symbol.toStringTag], 'Response') }) -test('async iterable body', async () => { +test('async iterable body', async (t) => { const asyncIterable = { async * [Symbol.asyncIterator] () { yield 'a' @@ -135,11 +133,11 @@ test('async iterable body', async () => { } const response = new Response(asyncIterable) - assert.strictEqual(await response.text(), 'abc') + t.assert.strictEqual(await response.text(), 'abc') }) // https://github.com/nodejs/node/pull/43752#issuecomment-1179678544 -test('Modifying headers using Headers.prototype.set', () => { +test('Modifying headers using Headers.prototype.set', (t) => { const response = new Response('body', { headers: { 'content-type': 'test/test', @@ -152,22 +150,22 @@ test('Modifying headers using Headers.prototype.set', () => { response.headers.set('content-type', 'application/wasm') response.headers.set('Content-Encoding', 'world/hello') - assert.strictEqual(response.headers.get('content-type'), 'application/wasm') - assert.strictEqual(response.headers.get('Content-Encoding'), 'world/hello') + t.assert.strictEqual(response.headers.get('content-type'), 'application/wasm') + t.assert.strictEqual(response.headers.get('Content-Encoding'), 'world/hello') response2.headers.delete('content-type') response2.headers.delete('Content-Encoding') - assert.strictEqual(response2.headers.get('content-type'), null) - assert.strictEqual(response2.headers.get('Content-Encoding'), null) + t.assert.strictEqual(response2.headers.get('content-type'), null) + t.assert.strictEqual(response2.headers.get('Content-Encoding'), null) }) // https://github.com/nodejs/node/issues/43838 -test('constructing a Response with a ReadableStream body', async (t) => { +describe('constructing a Response with a ReadableStream body', () => { const text = '{"foo":"bar"}' const uint8 = new TextEncoder().encode(text) - await t.test('Readable stream with Uint8Array chunks', async () => { + test('Readable stream with Uint8Array chunks', async (t) => { const readable = new ReadableStream({ start (controller) { controller.enqueue(uint8) @@ -179,12 +177,12 @@ test('constructing a Response with a ReadableStream body', async (t) => { const response2 = response1.clone() const response3 = response1.clone() - assert.strictEqual(await response1.text(), text) - assert.deepStrictEqual(await response2.arrayBuffer(), uint8.buffer) - assert.deepStrictEqual(await response3.json(), JSON.parse(text)) + t.assert.strictEqual(await response1.text(), text) + t.assert.deepStrictEqual(await response2.arrayBuffer(), uint8.buffer) + t.assert.deepStrictEqual(await response3.json(), JSON.parse(text)) }) - await t.test('.arrayBuffer() correctly clones multiple buffers', async () => { + test('.arrayBuffer() correctly clones multiple buffers', async (t) => { const buffer = Buffer.allocUnsafeSlow(2 * 1024 - 2) const readable = new ReadableStream({ start (controller) { @@ -196,10 +194,10 @@ test('constructing a Response with a ReadableStream body', async (t) => { }) const response = new Response(readable) - assert.deepStrictEqual(await response.arrayBuffer(), buffer.buffer) + t.assert.deepStrictEqual(await response.arrayBuffer(), buffer.buffer) }) - await t.test('Readable stream with non-Uint8Array chunks', async () => { + test('Readable stream with non-Uint8Array chunks', async (t) => { const readable = new ReadableStream({ start (controller) { controller.enqueue(text) // string @@ -209,10 +207,10 @@ test('constructing a Response with a ReadableStream body', async (t) => { const response = new Response(readable) - await assert.rejects(response.text(), TypeError) + await t.assert.rejects(response.text(), TypeError) }) - await t.test('Readable with ArrayBuffer chunk still throws', async () => { + test('Readable with ArrayBuffer chunk still throws', async (t) => { const readable = new ReadableStream({ start (controller) { controller.enqueue(uint8.buffer) @@ -225,51 +223,51 @@ test('constructing a Response with a ReadableStream body', async (t) => { const response3 = response1.clone() const response4 = response1.clone() - await assert.rejects(response1.arrayBuffer(), TypeError) - await assert.rejects(response2.text(), TypeError) - await assert.rejects(response3.json(), TypeError) - await assert.rejects(response4.blob(), TypeError) + await t.assert.rejects(response1.arrayBuffer(), TypeError) + await t.assert.rejects(response2.text(), TypeError) + await t.assert.rejects(response3.json(), TypeError) + await t.assert.rejects(response4.blob(), TypeError) }) }) // https://github.com/nodejs/undici/issues/2465 test('Issue#2465', async (t) => { - const { strictEqual } = tspl(t, { plan: 1 }) + t.plan(1) const response = new Response(new SharedArrayBuffer(0)) - strictEqual(await response.text(), '[object SharedArrayBuffer]') + t.assert.strictEqual(await response.text(), '[object SharedArrayBuffer]') }) -test('Check the Content-Type of invalid formData', async (t) => { - await t.test('_application/x-www-form-urlencoded', async (t) => { - const { rejects } = tspl(t, { plan: 1 }) +describe('Check the Content-Type of invalid formData', () => { + test('_application/x-www-form-urlencoded', async (t) => { + t.plan(1) const response = new Response('x=y', { headers: { 'content-type': '_application/x-www-form-urlencoded' } }) - await rejects(response.formData(), TypeError) + await t.assert.rejects(response.formData(), TypeError) }) - await t.test('_multipart/form-data', async (t) => { - const { rejects } = tspl(t, { plan: 1 }) + test('_multipart/form-data', async (t) => { + t.plan(1) const formData = new FormData() formData.append('x', 'y') const response = new Response(formData, { headers: { 'content-type': '_multipart/form-data' } }) - await rejects(response.formData(), TypeError) + await t.assert.rejects(response.formData(), TypeError) }) - await t.test('application/x-www-form-urlencoded_', async (t) => { - const { rejects } = tspl(t, { plan: 1 }) + test('application/x-www-form-urlencoded_', async (t) => { + t.plan(1) const response = new Response('x=y', { headers: { 'content-type': 'application/x-www-form-urlencoded_' } }) - await rejects(response.formData(), TypeError) + await t.assert.rejects(response.formData(), TypeError) }) - await t.test('multipart/form-data_', async (t) => { - const { rejects } = tspl(t, { plan: 1 }) + test('multipart/form-data_', async (t) => { + t.plan(1) const formData = new FormData() formData.append('x', 'y') const response = new Response(formData, { headers: { 'content-type': 'multipart/form-data_' } }) - await rejects(response.formData(), TypeError) + await t.assert.rejects(response.formData(), TypeError) }) }) -test('clone body garbage collection', async () => { +test('clone body garbage collection', async (t) => { if (typeof global.gc === 'undefined') { throw new Error('gc is not available. Run with \'--expose-gc\'.') } @@ -295,5 +293,5 @@ test('clone body garbage collection', async () => { global.gc() const cloneBody = ref.deref() - assert.equal(cloneBody, undefined, 'clone body was not garbage collected') + t.assert.strictEqual(cloneBody, undefined, 'clone body was not garbage collected') }) diff --git a/test/fetch/spread.js b/test/fetch/spread.js index ca05bea6e2a..12012614fc9 100644 --- a/test/fetch/spread.js +++ b/test/fetch/spread.js @@ -2,7 +2,6 @@ const undici = require('../..') const { test } = require('node:test') -const assert = require('node:assert') const { inspect } = require('node:util') test('spreading web classes yields empty objects', (t) => { @@ -11,7 +10,7 @@ test('spreading web classes yields empty objects', (t) => { new undici.Response(null), new undici.Request('http://a') ]) { - assert.deepStrictEqual({ ...object }, {}) + t.assert.deepStrictEqual({ ...object }, {}) } }) @@ -36,6 +35,6 @@ test('Objects only have an expected set of symbols on their prototypes', (t) => const symbols = Object.keys(Object.getOwnPropertyDescriptors(object.prototype)) .filter(v => typeof v === 'symbol') - assert(symbols.every(symbol => allowedSymbols.includes(symbol))) + t.assert.ok(symbols.every(symbol => allowedSymbols.includes(symbol))) } }) diff --git a/test/fetch/user-agent.js b/test/fetch/user-agent.js index 770f550725f..ad3749dd53d 100644 --- a/test/fetch/user-agent.js +++ b/test/fetch/user-agent.js @@ -1,7 +1,6 @@ 'use strict' const { test } = require('node:test') -const assert = require('node:assert') const events = require('node:events') const http = require('node:http') const undici = require('../../') @@ -23,6 +22,6 @@ test('user-agent defaults correctly', async (t) => { undici.fetch(url).then((body) => body.json()) ]) - assert.strictEqual(nodeBuildJSON.userAgentHeader, 'node') - assert.strictEqual(undiciJSON.userAgentHeader, 'undici') + t.assert.strictEqual(nodeBuildJSON.userAgentHeader, 'node') + t.assert.strictEqual(undiciJSON.userAgentHeader, 'undici') }) diff --git a/test/fetch/util.js b/test/fetch/util.js index a23194242e5..f5f23cb305b 100644 --- a/test/fetch/util.js +++ b/test/fetch/util.js @@ -1,27 +1,25 @@ 'use strict' const { describe, test } = require('node:test') -const assert = require('node:assert') -const { tspl } = require('@matteo.collina/tspl') const util = require('../../lib/web/fetch/util') const { HeadersList } = require('../../lib/web/fetch/headers') test('responseURL', (t) => { - const { ok } = tspl(t, { plan: 2 }) + t.plan(2) - ok(util.responseURL({ + t.assert.ok(util.responseURL({ urlList: [ new URL('http://asd'), new URL('http://fgh') ] })) - ok(!util.responseURL({ + t.assert.ok(!util.responseURL({ urlList: [] })) }) test('responseLocationURL', (t) => { - const { ok } = tspl(t, { plan: 3 }) + t.plan(3) const acceptHeaderList = new HeadersList() acceptHeaderList.append('Accept', '*/*') @@ -29,14 +27,14 @@ test('responseLocationURL', (t) => { const locationHeaderList = new HeadersList() locationHeaderList.append('Location', 'http://asd') - ok(!util.responseLocationURL({ + t.assert.ok(!util.responseLocationURL({ status: 200 })) - ok(!util.responseLocationURL({ + t.assert.ok(!util.responseLocationURL({ status: 301, headersList: acceptHeaderList })) - ok(util.responseLocationURL({ + t.assert.ok(util.responseLocationURL({ status: 301, headersList: locationHeaderList, urlList: [ @@ -47,15 +45,15 @@ test('responseLocationURL', (t) => { }) test('requestBadPort', (t) => { - const { strictEqual } = tspl(t, { plan: 3 }) + t.plan(3) - strictEqual('allowed', util.requestBadPort({ + t.assert.strictEqual('allowed', util.requestBadPort({ urlList: [new URL('https://asd')] })) - strictEqual('blocked', util.requestBadPort({ + t.assert.strictEqual('blocked', util.requestBadPort({ urlList: [new URL('http://asd:7')] })) - strictEqual('blocked', util.requestBadPort({ + t.assert.strictEqual('blocked', util.requestBadPort({ urlList: [new URL('https://asd:7')] })) }) @@ -63,7 +61,7 @@ test('requestBadPort', (t) => { // https://html.spec.whatwg.org/multipage/origin.html#same-origin // look at examples test('sameOrigin', async (t) => { - await t.test('first test', () => { + await t.test('first test', (t) => { const A = { protocol: 'https:', hostname: 'example.org', @@ -76,10 +74,10 @@ test('sameOrigin', async (t) => { port: '' } - assert.ok(util.sameOrigin(A, B)) + t.assert.ok(util.sameOrigin(A, B)) }) - await t.test('second test', () => { + await t.test('second test', (t) => { const A = { protocol: 'https:', hostname: 'example.org', @@ -92,28 +90,28 @@ test('sameOrigin', async (t) => { port: '420' } - assert.ok(!util.sameOrigin(A, B)) + t.assert.ok(!util.sameOrigin(A, B)) }) - await t.test('obviously shouldn\'t be equal', () => { - assert.ok(!util.sameOrigin( + await t.test('obviously shouldn\'t be equal', (t) => { + t.assert.ok(!util.sameOrigin( { protocol: 'http:', hostname: 'example.org' }, { protocol: 'https:', hostname: 'example.org' } )) - assert.ok(!util.sameOrigin( + t.assert.ok(!util.sameOrigin( { protocol: 'https:', hostname: 'example.org' }, { protocol: 'https:', hostname: 'example.com' } )) }) - await t.test('file:// urls', () => { + await t.test('file:// urls', (t) => { // urls with opaque origins should return true const a = new URL('file:///C:/undici') const b = new URL('file:///var/undici') - assert.ok(util.sameOrigin(a, b)) + t.assert.ok(util.sameOrigin(a, b)) }) }) @@ -144,18 +142,17 @@ test('isURLPotentiallyTrustworthy', (t) => { 'something:8080' ] - // t.plan(valid.length + invalid.length + 1) - const { ok } = tspl(t, { plan: valid.length + invalid.length + 1 }) - ok(!util.isURLPotentiallyTrustworthy('string')) + t.plan(valid.length + invalid.length + 1) + t.assert.ok(!util.isURLPotentiallyTrustworthy('string')) for (const url of valid) { const instance = new URL(url) - ok(util.isURLPotentiallyTrustworthy(instance), instance) + t.assert.ok(util.isURLPotentiallyTrustworthy(instance), instance) } for (const url of invalid) { const instance = new URL(url) - ok(!util.isURLPotentiallyTrustworthy(instance)) + t.assert.ok(!util.isURLPotentiallyTrustworthy(instance)) } }) @@ -203,6 +200,8 @@ describe('setRequestReferrerPolicyOnRedirect', () => { ] ].forEach(([title, responseReferrerPolicy, expected]) => { test(title, (t) => { + t.plan(1) + const request = { referrerPolicy: 'no-referrer, strict-origin-when-cross-origin' } @@ -211,8 +210,6 @@ describe('setRequestReferrerPolicyOnRedirect', () => { headersList: new HeadersList() } - const { strictEqual } = tspl(t, { plan: 1 }) - actualResponse.headersList.append('Connection', 'close') actualResponse.headersList.append('Location', 'https://some-location.com/redirect') if (responseReferrerPolicy) { @@ -220,7 +217,7 @@ describe('setRequestReferrerPolicyOnRedirect', () => { } util.setRequestReferrerPolicyOnRedirect(request, actualResponse) - strictEqual(request.referrerPolicy, expected) + t.assert.strictEqual(request.referrerPolicy, expected) }) }) }) @@ -228,55 +225,55 @@ describe('setRequestReferrerPolicyOnRedirect', () => { describe('urlHasHttpsScheme', () => { const { urlHasHttpsScheme } = util - test('should return false for http url', () => { - assert.strictEqual(urlHasHttpsScheme('http://example.com'), false) + test('should return false for http url', (t) => { + t.assert.strictEqual(urlHasHttpsScheme('http://example.com'), false) }) - test('should return true for https url', () => { - assert.strictEqual(urlHasHttpsScheme('https://example.com'), true) + test('should return true for https url', (t) => { + t.assert.strictEqual(urlHasHttpsScheme('https://example.com'), true) }) - test('should return false for http object', () => { - assert.strictEqual(urlHasHttpsScheme({ protocol: 'http:' }), false) + test('should return false for http object', (t) => { + t.assert.strictEqual(urlHasHttpsScheme({ protocol: 'http:' }), false) }) - test('should return true for https object', () => { - assert.strictEqual(urlHasHttpsScheme({ protocol: 'https:' }), true) + test('should return true for https object', (t) => { + t.assert.strictEqual(urlHasHttpsScheme({ protocol: 'https:' }), true) }) }) describe('isValidHeaderValue', () => { const { isValidHeaderValue } = util - test('should return true for valid string', () => { - assert.strictEqual(isValidHeaderValue('valid123'), true) - assert.strictEqual(isValidHeaderValue('va lid123'), true) - assert.strictEqual(isValidHeaderValue('va\tlid123'), true) + test('should return true for valid string', (t) => { + t.assert.strictEqual(isValidHeaderValue('valid123'), true) + t.assert.strictEqual(isValidHeaderValue('va lid123'), true) + t.assert.strictEqual(isValidHeaderValue('va\tlid123'), true) }) - test('should return false for string containing NUL', () => { - assert.strictEqual(isValidHeaderValue('invalid\0'), false) - assert.strictEqual(isValidHeaderValue('in\0valid'), false) - assert.strictEqual(isValidHeaderValue('\0invalid'), false) + test('should return false for string containing NUL', (t) => { + t.assert.strictEqual(isValidHeaderValue('invalid\0'), false) + t.assert.strictEqual(isValidHeaderValue('in\0valid'), false) + t.assert.strictEqual(isValidHeaderValue('\0invalid'), false) }) - test('should return false for string containing CR', () => { - assert.strictEqual(isValidHeaderValue('invalid\r'), false) - assert.strictEqual(isValidHeaderValue('in\rvalid'), false) - assert.strictEqual(isValidHeaderValue('\rinvalid'), false) + test('should return false for string containing CR', (t) => { + t.assert.strictEqual(isValidHeaderValue('invalid\r'), false) + t.assert.strictEqual(isValidHeaderValue('in\rvalid'), false) + t.assert.strictEqual(isValidHeaderValue('\rinvalid'), false) }) - test('should return false for string containing LF', () => { - assert.strictEqual(isValidHeaderValue('invalid\n'), false) - assert.strictEqual(isValidHeaderValue('in\nvalid'), false) - assert.strictEqual(isValidHeaderValue('\ninvalid'), false) + test('should return false for string containing LF', (t) => { + t.assert.strictEqual(isValidHeaderValue('invalid\n'), false) + t.assert.strictEqual(isValidHeaderValue('in\nvalid'), false) + t.assert.strictEqual(isValidHeaderValue('\ninvalid'), false) }) - test('should return false for string with leading TAB', () => { - assert.strictEqual(isValidHeaderValue('\tinvalid'), false) + test('should return false for string with leading TAB', (t) => { + t.assert.strictEqual(isValidHeaderValue('\tinvalid'), false) }) - test('should return false for string with trailing TAB', () => { - assert.strictEqual(isValidHeaderValue('invalid\t'), false) + test('should return false for string with trailing TAB', (t) => { + t.assert.strictEqual(isValidHeaderValue('invalid\t'), false) }) - test('should return false for string with leading SPACE', () => { - assert.strictEqual(isValidHeaderValue(' invalid'), false) + test('should return false for string with leading SPACE', (t) => { + t.assert.strictEqual(isValidHeaderValue(' invalid'), false) }) - test('should return false for string with trailing SPACE', () => { - assert.strictEqual(isValidHeaderValue('invalid '), false) + test('should return false for string with trailing SPACE', (t) => { + t.assert.strictEqual(isValidHeaderValue('invalid '), false) }) }) @@ -308,8 +305,8 @@ describe('isOriginIPPotentiallyTrustworthy()', () => { ['127.255.255.255', true], ['128.255.255.255', false] ].forEach(([ip, expected]) => { - test(`${ip} is ${expected ? '' : 'not '}potentially trustworthy`, () => { - assert.strictEqual(util.isOriginIPPotentiallyTrustworthy(ip), expected) + test(`${ip} is ${expected ? '' : 'not '}potentially trustworthy`, (t) => { + t.assert.strictEqual(util.isOriginIPPotentiallyTrustworthy(ip), expected) }) }) })