From b504346f92b7e59942e6fdfd1da264762b300267 Mon Sep 17 00:00:00 2001 From: Sindre Sorhus Date: Wed, 25 Jul 2018 14:57:23 +0700 Subject: [PATCH] Minor code style tweaks --- source/as-promise.js | 14 +-- source/as-stream.js | 14 +-- source/assign-options.js | 10 +-- source/create.js | 8 +- source/deep-freeze.js | 8 +- source/get-response.js | 2 +- source/index.js | 18 +++- source/is-retry-on-network-error-allowed.js | 4 +- source/normalize-arguments.js | 14 ++- source/progress.js | 10 +-- source/request-as-event-emitter.js | 12 +-- source/timed-out.js | 43 +++++---- test/agent.js | 30 +++---- test/arguments.js | 38 ++++---- test/cache.js | 44 +++++----- test/cancel.js | 22 ++--- test/create.js | 6 +- test/error.js | 80 ++++++++--------- test/gzip.js | 72 ++++++++-------- test/headers.js | 14 +-- test/helpers.js | 26 +++--- test/hooks.js | 24 +++--- test/http.js | 42 ++++----- test/https.js | 9 +- test/json-parse.js | 66 +++++++------- test/post.js | 22 ++--- test/progress.js | 58 ++++++------- test/promise.js | 26 +++--- test/redirects.js | 96 ++++++++++----------- test/retry.js | 66 +++++++------- test/socket-destroyed.js | 4 +- test/stream.js | 34 ++++---- test/timeout.js | 72 ++++++++-------- test/unix-socket.js | 16 ++-- 34 files changed, 522 insertions(+), 502 deletions(-) diff --git a/source/as-promise.js b/source/as-promise.js index 1b4ff00b8..aa7b8a05e 100644 --- a/source/as-promise.js +++ b/source/as-promise.js @@ -17,29 +17,29 @@ module.exports = options => { cancelOnRequest = true; }); - emitter.on('request', req => { + emitter.on('request', request => { if (cancelOnRequest) { - req.abort(); + request.abort(); } - proxy.emit('request', req); + proxy.emit('request', request); const uploadComplete = () => { - req.emit('upload-complete'); + request.emit('upload-complete'); }; onCancel(() => { - req.abort(); + request.abort(); }); if (is.nodeStream(options.body)) { options.body.once('end', uploadComplete); - options.body.pipe(req); + options.body.pipe(request); options.body = undefined; return; } - req.end(options.body, uploadComplete); + request.end(options.body, uploadComplete); }); emitter.on('response', async response => { diff --git a/source/as-stream.js b/source/as-stream.js index 501da2bad..e878b41c6 100644 --- a/source/as-stream.js +++ b/source/as-stream.js @@ -26,30 +26,30 @@ module.exports = options => { const emitter = requestAsEventEmitter(options); - emitter.on('request', req => { - proxy.emit('request', req); + emitter.on('request', request => { + proxy.emit('request', request); const uploadComplete = () => { - req.emit('upload-complete'); + request.emit('upload-complete'); }; if (is.nodeStream(options.body)) { options.body.once('end', uploadComplete); - options.body.pipe(req); + options.body.pipe(request); return; } if (options.body) { - req.end(options.body, uploadComplete); + request.end(options.body, uploadComplete); return; } if (options.method === 'POST' || options.method === 'PUT' || options.method === 'PATCH') { input.once('end', uploadComplete); - input.pipe(req); + input.pipe(request); return; } - req.end(uploadComplete); + request.end(uploadComplete); }); emitter.on('response', response => { diff --git a/source/assign-options.js b/source/assign-options.js index 5127ff4b6..176876ce2 100644 --- a/source/assign-options.js +++ b/source/assign-options.js @@ -2,12 +2,12 @@ const extend = require('extend'); const is = require('@sindresorhus/is'); module.exports = (defaults, options = {}) => { - const opts = extend(true, {}, defaults, options); + const returnOptions = extend(true, {}, defaults, options); if (Reflect.has(options, 'headers')) { for (const [key, value] of Object.entries(options.headers)) { if (is.nullOrUndefined(value)) { - delete opts.headers[key]; + delete returnOptions.headers[key]; } } } @@ -15,13 +15,13 @@ module.exports = (defaults, options = {}) => { // Override these arrays because we don't want to extend them if (is.object(options.retry)) { if (Reflect.has(options.retry, 'methods')) { - opts.retry.methods = options.retry.methods; + returnOptions.retry.methods = options.retry.methods; } if (Reflect.has(options.retry, 'statusCodes')) { - opts.retry.statusCodes = options.retry.statusCodes; + returnOptions.retry.statusCodes = options.retry.statusCodes; } } - return opts; + return returnOptions; }; diff --git a/source/create.js b/source/create.js index a649373b0..2d09394de 100644 --- a/source/create.js +++ b/source/create.js @@ -6,13 +6,7 @@ const asPromise = require('./as-promise'); const normalizeArguments = require('./normalize-arguments'); const deepFreeze = require('./deep-freeze'); -const next = options => { - if (options.stream) { - return asStream(options); - } - - return asPromise(options); -}; +const next = options => options.stream ? asStream(options) : asPromise(options); const create = defaults => { if (!defaults.handler) { diff --git a/source/deep-freeze.js b/source/deep-freeze.js index 1d3d8f028..b4ded119d 100644 --- a/source/deep-freeze.js +++ b/source/deep-freeze.js @@ -1,12 +1,12 @@ 'use strict'; const is = require('@sindresorhus/is'); -module.exports = function deepFreeze(obj) { - for (const [key, value] of Object.entries(obj)) { +module.exports = function deepFreeze(object) { + for (const [key, value] of Object.entries(object)) { if (is.object(value)) { - deepFreeze(obj[key]); + deepFreeze(object[key]); } } - return Object.freeze(obj); + return Object.freeze(object); }; diff --git a/source/get-response.js b/source/get-response.js index fa133bae9..594e8975e 100644 --- a/source/get-response.js +++ b/source/get-response.js @@ -14,7 +14,7 @@ module.exports = (response, options, emitter, redirects) => { const percent = downloadBodySize ? downloaded / downloadBodySize : 0; - // Let flush() be responsible for emitting the last event + // Let `flush()` be responsible for emitting the last event if (percent < 1) { emitter.emit('downloadProgress', { percent, diff --git a/source/index.js b/source/index.js index f4573f845..435b676d8 100644 --- a/source/index.js +++ b/source/index.js @@ -14,8 +14,22 @@ const defaults = { options: { retry: { retries: 2, - methods: ['GET', 'PUT', 'HEAD', 'DELETE', 'OPTIONS', 'TRACE'], - statusCodes: [408, 413, 429, 502, 503, 504] + methods: [ + 'GET', + 'PUT', + 'HEAD', + 'DELETE', + 'OPTIONS', + 'TRACE' + ], + statusCodes: [ + 408, + 413, + 429, + 502, + 503, + 504 + ] }, cache: false, decompress: true, diff --git a/source/is-retry-on-network-error-allowed.js b/source/is-retry-on-network-error-allowed.js index 3826d0cff..f2c81e047 100644 --- a/source/is-retry-on-network-error-allowed.js +++ b/source/is-retry-on-network-error-allowed.js @@ -9,8 +9,8 @@ const WHITELIST = new Set([ 'EPIPE' ]); -module.exports = err => { - if (err && WHITELIST.has(err.code)) { +module.exports = error => { + if (error && WHITELIST.has(error.code)) { return true; } diff --git a/source/normalize-arguments.js b/source/normalize-arguments.js index d427da99c..b890f0a97 100644 --- a/source/normalize-arguments.js +++ b/source/normalize-arguments.js @@ -204,15 +204,13 @@ module.exports = (url, options, defaults) => { if (is.nullOrUndefined(hooks)) { options.hooks[hookEvent] = []; } else if (is.array(hooks)) { - hooks.forEach( - (hook, index) => { - if (!is.function_(hook)) { - throw new TypeError( - `Parameter \`hooks.${hookEvent}[${index}]\` must be a function, not ${is(hook)}` - ); - } + for (const [index, hook] of hooks.entries()) { + if (!is.function(hook)) { + throw new TypeError( + `Parameter \`hooks.${hookEvent}[${index}]\` must be a function, not ${is(hook)}` + ); } - ); + } } else { throw new TypeError(`Parameter \`hooks.${hookEvent}\` must be an array, not ${is(hooks)}`); } diff --git a/source/progress.js b/source/progress.js index adbd80464..cf1821f74 100644 --- a/source/progress.js +++ b/source/progress.js @@ -1,6 +1,6 @@ 'use strict'; module.exports = { - upload(req, emitter, uploadBodySize) { + upload(request, emitter, uploadBodySize) { const uploadEventFrequency = 150; let uploaded = 0; let progressInterval; @@ -11,11 +11,11 @@ module.exports = { total: uploadBodySize }); - req.once('error', () => { + request.once('error', () => { clearInterval(progressInterval); }); - req.once('response', () => { + request.once('response', () => { clearInterval(progressInterval); emitter.emit('uploadProgress', { @@ -25,7 +25,7 @@ module.exports = { }); }); - req.once('socket', socket => { + request.once('socket', socket => { const onSocketConnect = () => { progressInterval = setInterval(() => { if (socket.destroyed) { @@ -34,7 +34,7 @@ module.exports = { } const lastUploaded = uploaded; - const headersSize = req._header ? Buffer.byteLength(req._header) : 0; + const headersSize = request._header ? Buffer.byteLength(request._header) : 0; uploaded = socket.bytesWritten - headersSize; // Prevent the known issue of `bytesWritten` being larger than body size diff --git a/source/request-as-event-emitter.js b/source/request-as-event-emitter.js index 7631b5342..b0c32996d 100644 --- a/source/request-as-event-emitter.js +++ b/source/request-as-event-emitter.js @@ -106,13 +106,13 @@ module.exports = (options = {}) => { } }); - cacheReq.once('request', req => { + cacheReq.once('request', request => { let aborted = false; - req.once('abort', _ => { + request.once('abort', _ => { aborted = true; }); - req.once('error', error => { + request.once('error', error => { if (aborted) { return; } @@ -127,13 +127,13 @@ module.exports = (options = {}) => { }); }); - progress.upload(req, emitter, uploadBodySize); + progress.upload(request, emitter, uploadBodySize); if (options.gotTimeout) { - timedOut(req, options); + timedOut(request, options); } - emitter.emit('request', req); + emitter.emit('request', request); }); }; diff --git a/source/timed-out.js b/source/timed-out.js index aeb51343e..bffb0e2c2 100644 --- a/source/timed-out.js +++ b/source/timed-out.js @@ -26,23 +26,25 @@ function addTimeout(delay, callback, ...args) { }; } -module.exports = function (req, options) { - if (req[reentry]) { +module.exports = (request, options) => { + if (request[reentry]) { return; } - req[reentry] = true; + + request[reentry] = true; const {gotTimeout: delays, host, hostname} = options; const timeoutHandler = (delay, event) => { - req.abort(); - req.emit('error', new TimeoutError(delay, event, options)); + request.abort(); + request.emit('error', new TimeoutError(delay, event, options)); }; + const cancelers = []; const cancelTimeouts = () => { cancelers.forEach(cancelTimeout => cancelTimeout()); }; - req.on('error', cancelTimeouts); - req.once('response', response => { + request.on('error', cancelTimeouts); + request.once('response', response => { response.once('end', cancelTimeouts); }); @@ -54,16 +56,18 @@ module.exports = function (req, options) { ); cancelers.push(cancelTimeout); } + if (delays.socket !== undefined) { - req.setTimeout( + request.setTimeout( delays.socket, () => { timeoutHandler(delays.socket, 'socket'); } ); } - if (delays.lookup !== undefined && !req.socketPath && !net.isIP(hostname || host)) { - req.once('socket', socket => { + + if (delays.lookup !== undefined && !request.socketPath && !net.isIP(hostname || host)) { + request.once('socket', socket => { if (socket.connecting) { const cancelTimeout = addTimeout( delays.lookup, @@ -75,8 +79,9 @@ module.exports = function (req, options) { } }); } + if (delays.connect !== undefined) { - req.once('socket', socket => { + request.once('socket', socket => { if (socket.connecting) { const timeConnect = () => { const cancelTimeout = addTimeout( @@ -87,7 +92,8 @@ module.exports = function (req, options) { cancelers.push(cancelTimeout); return cancelTimeout; }; - if (req.socketPath || net.isIP(hostname || host)) { + + if (request.socketPath || net.isIP(hostname || host)) { socket.once('connect', timeConnect()); } else { socket.once('lookup', () => { @@ -97,8 +103,9 @@ module.exports = function (req, options) { } }); } + if (delays.send !== undefined) { - req.once('socket', socket => { + request.once('socket', socket => { const timeRequest = () => { const cancelTimeout = addTimeout( delays.send, @@ -108,24 +115,26 @@ module.exports = function (req, options) { cancelers.push(cancelTimeout); return cancelTimeout; }; + if (socket.connecting) { socket.once('connect', () => { - req.once('upload-complete', timeRequest()); + request.once('upload-complete', timeRequest()); }); } else { - req.once('upload-complete', timeRequest()); + request.once('upload-complete', timeRequest()); } }); } + if (delays.response !== undefined) { - req.once('upload-complete', () => { + request.once('upload-complete', () => { const cancelTimeout = addTimeout( delays.response, timeoutHandler, 'response' ); cancelers.push(cancelTimeout); - req.once('response', cancelTimeout); + request.once('response', cancelTimeout); }); } }; diff --git a/test/agent.js b/test/agent.js index d98c54eb0..78e3874cc 100644 --- a/test/agent.js +++ b/test/agent.js @@ -42,34 +42,39 @@ test.before('setup', async () => { // HTTPS Handlers - https.on('/', (req, res) => { - res.end('https'); + https.on('/', (request, response) => { + response.end('https'); }); - https.on('/httpsToHttp', (req, res) => { - res.writeHead(302, { + https.on('/httpsToHttp', (request, response) => { + response.writeHead(302, { location: http.url }); - res.end(); + response.end(); }); // HTTP Handlers - http.on('/', (req, res) => { - res.end('http'); + http.on('/', (request, response) => { + response.end('http'); }); - http.on('/httpToHttps', (req, res) => { - res.writeHead(302, { + http.on('/httpToHttps', (request, response) => { + response.writeHead(302, { location: https.url }); - res.end(); + response.end(); }); await http.listen(http.port); await https.listen(https.port); }); +test.after('cleanup', async () => { + await http.close(); + await https.close(); +}); + const createAgentSpy = Cls => { const agent = new Cls({keepAlive: true}); const spy = sinon.spy(agent, 'addRequest'); @@ -161,8 +166,3 @@ test('socket connect listener cleaned up after request', async t => { // Make sure to close all open sockets agent.destroy(); }); - -test.after('cleanup', async () => { - await http.close(); - await https.close(); -}); diff --git a/test/arguments.js b/test/arguments.js index 6ee1c363e..21a4b9353 100644 --- a/test/arguments.js +++ b/test/arguments.js @@ -9,34 +9,38 @@ let s; test.before('setup', async () => { s = await createServer(); - s.on('/', (req, res) => { - res.statusCode = 404; - res.end(); + s.on('/', (request, response) => { + response.statusCode = 404; + response.end(); }); - s.on('/test', (req, res) => { - res.end(req.url); + s.on('/test', (request, response) => { + response.end(request.url); }); - s.on('/?test=wow', (req, res) => { - res.end(req.url); + s.on('/?test=wow', (request, response) => { + response.end(request.url); }); - s.on('/stream', (req, res) => { - res.end('ok'); + s.on('/stream', (request, response) => { + response.end('ok'); }); await s.listen(s.port); }); +test.after('cleanup', async () => { + await s.close(); +}); + test('url is required', async t => { - const err = await t.throws(got()); - t.regex(err.message, /Parameter `url` must be a string or object, not undefined/); + const error = await t.throws(got()); + t.regex(error.message, /Parameter `url` must be a string or object, not undefined/); }); test('url should be utf-8 encoded', async t => { - const err = await t.throws(got(`${s.url}/%D2%E0%EB%EB%E8%ED`)); - t.regex(err.message, /Parameter `url` must contain valid UTF-8 character sequences/); + const error = await t.throws(got(`${s.url}/%D2%E0%EB%EB%E8%ED`)); + t.regex(error.message, /Parameter `url` must contain valid UTF-8 character sequences/); }); test('options are optional', async t => { @@ -78,8 +82,8 @@ test('overrides querystring from opts', async t => { }); test('should throw with auth in url string', async t => { - const err = await t.throws(got('https://test:45d3ps453@account.myservice.com/api/token')); - t.regex(err.message, /Basic authentication must be done with the `auth` option/); + const error = await t.throws(got('https://test:45d3ps453@account.myservice.com/api/token')); + t.regex(error.message, /Basic authentication must be done with the `auth` option/); }); test('does not throw with auth in url object', async t => { @@ -148,7 +152,3 @@ test('throws TypeError when known `hooks` array item is not a function', async t test('allows extra keys in `hooks`', async t => { await t.notThrows(() => got(`${s.url}/test`, {hooks: {extra: {}}})); }); - -test.after('cleanup', async () => { - await s.close(); -}); diff --git a/test/cache.js b/test/cache.js index fc122379a..a93b2a72c 100644 --- a/test/cache.js +++ b/test/cache.js @@ -8,44 +8,48 @@ test.before('setup', async () => { s = await createServer(); let noStoreIndex = 0; - s.on('/no-store', (req, res) => { - res.setHeader('Cache-Control', 'public, no-cache, no-store'); - res.end(noStoreIndex.toString()); + s.on('/no-store', (request, response) => { + response.setHeader('Cache-Control', 'public, no-cache, no-store'); + response.end(noStoreIndex.toString()); noStoreIndex++; }); let cacheIndex = 0; - s.on('/cache', (req, res) => { - res.setHeader('Cache-Control', 'public, max-age=60'); - res.end(cacheIndex.toString()); + s.on('/cache', (request, response) => { + response.setHeader('Cache-Control', 'public, max-age=60'); + response.end(cacheIndex.toString()); cacheIndex++; }); let status301Index = 0; - s.on('/301', (req, res) => { + s.on('/301', (request, response) => { if (status301Index === 0) { - res.setHeader('Cache-Control', 'public, max-age=60'); - res.setHeader('Location', s.url + '/302'); - res.statusCode = 301; + response.setHeader('Cache-Control', 'public, max-age=60'); + response.setHeader('Location', `${s.url}/302`); + response.statusCode = 301; } - res.end(); + response.end(); status301Index++; }); let status302Index = 0; - s.on('/302', (req, res) => { + s.on('/302', (request, response) => { if (status302Index === 0) { - res.setHeader('Cache-Control', 'public, max-age=60'); - res.setHeader('Location', s.url + '/cache'); - res.statusCode = 302; + response.setHeader('Cache-Control', 'public, max-age=60'); + response.setHeader('Location', `${s.url}/cache`); + response.statusCode = 302; } - res.end(); + response.end(); status302Index++; }); await s.listen(s.port); }); +test.after('cleanup', async () => { + await s.close(); +}); + test('Non cacheable responses are not cached', async t => { const endpoint = '/no-store'; const cache = new Map(); @@ -98,10 +102,6 @@ test('Cache error throws got.CacheError', async t => { const endpoint = '/no-store'; const cache = {}; - const err = await t.throws(got(s.url + endpoint, {cache})); - t.is(err.name, 'CacheError'); -}); - -test.after('cleanup', async () => { - await s.close(); + const error = await t.throws(got(s.url + endpoint, {cache})); + t.is(error.name, 'CacheError'); }); diff --git a/test/cancel.js b/test/cancel.js index cee546220..30410367a 100644 --- a/test/cancel.js +++ b/test/cancel.js @@ -10,20 +10,20 @@ async function createAbortServer() { const s = await createServer(); const ee = new EventEmitter(); ee.aborted = new Promise((resolve, reject) => { - s.on('/abort', async (req, res) => { + s.on('/abort', async (request, response) => { ee.emit('connection'); - req.on('aborted', resolve); - res.on('finish', reject.bind(null, new Error('Request finished instead of aborting.'))); + request.on('aborted', resolve); + response.on('finish', reject.bind(null, new Error('Request finished instead of aborting.'))); - await getStream(req); - res.end(); + await getStream(request); + response.end(); }); - s.on('/redirect', (req, res) => { - res.writeHead(302, { + s.on('/redirect', (request, response) => { + response.writeHead(302, { location: `${s.url}/abort` }); - res.end(); + response.end(); ee.emit('sentRedirect'); @@ -100,9 +100,9 @@ test('cancel immediately', async t => { const aborted = new Promise((resolve, reject) => { // We won't get an abort or even a connection // We assume no request within 1000ms equals a (client side) aborted request - s.on('/abort', (req, res) => { - res.on('finish', reject.bind(this, new Error('Request finished instead of aborting.'))); - res.end(); + s.on('/abort', (request, response) => { + response.on('finish', reject.bind(this, new Error('Request finished instead of aborting.'))); + response.end(); }); setTimeout(resolve, 1000); }); diff --git a/test/create.js b/test/create.js index b08b62a0a..17ccc2b3f 100644 --- a/test/create.js +++ b/test/create.js @@ -7,9 +7,9 @@ let s; test.before('setup', async () => { s = await createServer(); - s.on('/', (req, res) => { - req.resume(); - res.end(JSON.stringify(req.headers)); + s.on('/', (request, response) => { + request.resume(); + response.end(JSON.stringify(request.headers)); }); await s.listen(s.port); diff --git a/test/error.js b/test/error.js index 0ba0bfa6f..f9326e9b2 100644 --- a/test/error.js +++ b/test/error.js @@ -11,51 +11,55 @@ let s; test.before('setup', async () => { s = await createServer(); - s.on('/', (req, res) => { - res.statusCode = 404; - res.end('not'); + s.on('/', (request, response) => { + response.statusCode = 404; + response.end('not'); }); - s.on('/default-status-message', (req, res) => { - res.statusCode = 400; - res.end('body'); + s.on('/default-status-message', (request, response) => { + response.statusCode = 400; + response.end('body'); }); - s.on('/custom-status-message', (req, res) => { - res.statusCode = 400; - res.statusMessage = 'Something Exploded'; - res.end('body'); + s.on('/custom-status-message', (request, response) => { + response.statusCode = 400; + response.statusMessage = 'Something Exploded'; + response.end('body'); }); - s.on('/body', async (req, res) => { - const body = await getStream(req); - res.end(body); + s.on('/body', async (request, response) => { + const body = await getStream(request); + response.end(body); }); await s.listen(s.port); }); +test.after('cleanup', async () => { + await s.close(); +}); + test('properties', async t => { - const err = await t.throws(got(s.url)); - t.truthy(err); - t.truthy(err.response); - t.false({}.propertyIsEnumerable.call(err, 'response')); - t.false({}.hasOwnProperty.call(err, 'code')); - t.is(err.message, 'Response code 404 (Not Found)'); - t.is(err.host, `${s.host}:${s.port}`); - t.is(err.method, 'GET'); - t.is(err.protocol, 'http:'); - t.is(err.url, err.response.requestUrl); - t.is(err.headers.connection, 'close'); - t.is(err.response.body, 'not'); + const error = await t.throws(got(s.url)); + t.truthy(error); + t.truthy(error.response); + t.false({}.propertyIsEnumerable.call(error, 'response')); + t.false({}.hasOwnProperty.call(error, 'code')); + t.is(error.message, 'Response code 404 (Not Found)'); + t.is(error.host, `${s.host}:${s.port}`); + t.is(error.method, 'GET'); + t.is(error.protocol, 'http:'); + t.is(error.url, error.response.requestUrl); + t.is(error.headers.connection, 'close'); + t.is(error.response.body, 'not'); }); test('dns message', async t => { - const err = await t.throws(got('.com', {retry: 0})); - t.truthy(err); - t.regex(err.message, /getaddrinfo ENOTFOUND/); - t.is(err.host, '.com'); - t.is(err.method, 'GET'); + const error = await t.throws(got('.com', {retry: 0})); + t.truthy(error); + t.regex(error.message, /getaddrinfo ENOTFOUND/); + t.is(error.host, '.com'); + t.is(error.method, 'GET'); }); test('options.body error message', async t => { @@ -87,15 +91,15 @@ test('no plain object restriction on body', async t => { }); test('default status message', async t => { - const err = await t.throws(got(`${s.url}/default-status-message`)); - t.is(err.statusCode, 400); - t.is(err.statusMessage, 'Bad Request'); + const error = await t.throws(got(`${s.url}/default-status-message`)); + t.is(error.statusCode, 400); + t.is(error.statusMessage, 'Bad Request'); }); test('custom status message', async t => { - const err = await t.throws(got(`${s.url}/custom-status-message`)); - t.is(err.statusCode, 400); - t.is(err.statusMessage, 'Something Exploded'); + const error = await t.throws(got(`${s.url}/custom-status-message`)); + t.is(error.statusCode, 400); + t.is(error.statusMessage, 'Something Exploded'); }); test.serial('http.request error', async t => { @@ -118,7 +122,3 @@ test.serial('catch error in mimicResponse', async t => { await t.throws(proxiedGot(s.url), {message: 'Error in mimic-response'}); }); - -test.after('cleanup', async () => { - await s.close(); -}); diff --git a/test/gzip.js b/test/gzip.js index bb577fb11..f43bd1e2d 100644 --- a/test/gzip.js +++ b/test/gzip.js @@ -15,42 +15,46 @@ test.before('setup', async () => { s = await createServer(); gzipData = await util.promisify(zlib.gzip)(testContent); - s.on('/', (req, res) => { - res.statusCode = 200; - res.setHeader('Content-Type', 'text/plain'); - res.setHeader('Content-Encoding', 'gzip'); + s.on('/', (request, response) => { + response.statusCode = 200; + response.setHeader('Content-Type', 'text/plain'); + response.setHeader('Content-Encoding', 'gzip'); - if (req.method === 'HEAD') { - res.end(); + if (request.method === 'HEAD') { + response.end(); return; } - res.end(gzipData); + response.end(gzipData); }); - s.on('/corrupted', (req, res) => { - res.statusCode = 200; - res.setHeader('Content-Type', 'text/plain'); - res.setHeader('Content-Encoding', 'gzip'); - res.end('Not gzipped content'); + s.on('/corrupted', (request, response) => { + response.statusCode = 200; + response.setHeader('Content-Type', 'text/plain'); + response.setHeader('Content-Encoding', 'gzip'); + response.end('Not gzipped content'); }); - s.on('/missing-data', (req, res) => { - res.statusCode = 200; - res.setHeader('Content-Type', 'text/plain'); - res.setHeader('Content-Encoding', 'gzip'); - res.end(gzipData.slice(0, -1)); + s.on('/missing-data', (request, response) => { + response.statusCode = 200; + response.setHeader('Content-Type', 'text/plain'); + response.setHeader('Content-Encoding', 'gzip'); + response.end(gzipData.slice(0, -1)); }); - s.on('/uncompressed', (req, res) => { - res.statusCode = 200; - res.setHeader('Content-Type', 'text/plain'); - res.end(testContentUncompressed); + s.on('/uncompressed', (request, response) => { + response.statusCode = 200; + response.setHeader('Content-Type', 'text/plain'); + response.end(testContentUncompressed); }); await s.listen(s.port); }); +test.after('cleanup', async () => { + await s.close(); +}); + test('decompress content', async t => { t.is((await got(s.url)).body, testContent); }); @@ -60,17 +64,17 @@ test('decompress content - stream', async t => { }); test('handles gzip error', async t => { - const err = await t.throws(got(`${s.url}/corrupted`)); - t.is(err.message, 'incorrect header check'); - t.is(err.path, '/corrupted'); - t.is(err.name, 'ReadError'); + const error = await t.throws(got(`${s.url}/corrupted`)); + t.is(error.message, 'incorrect header check'); + t.is(error.path, '/corrupted'); + t.is(error.name, 'ReadError'); }); test('handles gzip error - stream', async t => { - const err = await t.throws(getStream(got.stream(`${s.url}/corrupted`))); - t.is(err.message, 'incorrect header check'); - t.is(err.path, '/corrupted'); - t.is(err.name, 'ReadError'); + const error = await t.throws(getStream(got.stream(`${s.url}/corrupted`))); + t.is(error.message, 'incorrect header check'); + t.is(error.path, '/corrupted'); + t.is(error.name, 'ReadError'); }); test('decompress option opts out of decompressing', async t => { @@ -96,11 +100,7 @@ test('ignore missing data', async t => { }); test('has url and requestUrl properties', async t => { - const res = await got(s.url); - t.truthy(res.url); - t.truthy(res.requestUrl); -}); - -test.after('cleanup', async () => { - await s.close(); + const response = await got(s.url); + t.truthy(response.url); + t.truthy(response.requestUrl); }); diff --git a/test/headers.js b/test/headers.js index d07c23d64..80b39e22d 100644 --- a/test/headers.js +++ b/test/headers.js @@ -12,14 +12,18 @@ let s; test.before('setup', async () => { s = await createServer(); - s.on('/', (req, res) => { - req.resume(); - res.end(JSON.stringify(req.headers)); + s.on('/', (request, response) => { + request.resume(); + response.end(JSON.stringify(request.headers)); }); await s.listen(s.port); }); +test.after('cleanup', async () => { + await s.close(); +}); + test('user-agent', async t => { const headers = (await got(s.url, {json: true})).body; t.is(headers['user-agent'], `${pkg.name}/${pkg.version} (https://github.com/sindresorhus/got)`); @@ -147,7 +151,3 @@ test('remove undefined value headers', async t => { const headers = JSON.parse(body); t.false(Reflect.has(headers, 'user-agent')); }); - -test.after('cleanup', async () => { - await s.close(); -}); diff --git a/test/helpers.js b/test/helpers.js index 6b74a67df..765af4c9e 100644 --- a/test/helpers.js +++ b/test/helpers.js @@ -7,28 +7,28 @@ let s; test.before('setup', async () => { s = await createServer(); - s.on('/', (req, res) => { - res.end('ok'); + s.on('/', (request, response) => { + response.end('ok'); }); - s.on('/404', (req, res) => { - res.statusCode = 404; - res.end('not found'); + s.on('/404', (request, response) => { + response.statusCode = 404; + response.end('not found'); }); await s.listen(s.port); }); +test.after('cleanup', async () => { + await s.close(); +}); + test('promise mode', async t => { t.is((await got.get(s.url)).body, 'ok'); - const err = await t.throws(got.get(`${s.url}/404`)); - t.is(err.response.body, 'not found'); + const error = await t.throws(got.get(`${s.url}/404`)); + t.is(error.response.body, 'not found'); - const err2 = await t.throws(got.get('.com', {retry: 0})); - t.truthy(err2); -}); - -test.after('cleanup', async () => { - await s.close(); + const error2 = await t.throws(got.get('.com', {retry: 0})); + t.truthy(error2); }); diff --git a/test/hooks.js b/test/hooks.js index 220bf97ce..20e559aef 100644 --- a/test/hooks.js +++ b/test/hooks.js @@ -7,15 +7,19 @@ let s; test.before('setup', async () => { s = await createServer(); - const echoHeaders = (req, res) => { - res.statusCode = 200; - res.write(JSON.stringify(req.headers)); - res.end(); + const echoHeaders = (request, response) => { + response.statusCode = 200; + response.write(JSON.stringify(request.headers)); + response.end(); }; s.on('/', echoHeaders); await s.listen(s.port); }); +test.after('cleanup', async () => { + await s.close(); +}); + test('beforeRequest receives normalized options', async t => { await got( s.url, @@ -34,7 +38,7 @@ test('beforeRequest receives normalized options', async t => { }); test('beforeRequest allows modifications', async t => { - const res = await got( + const response = await got( s.url, { json: true, @@ -47,11 +51,11 @@ test('beforeRequest allows modifications', async t => { } } ); - t.is(res.body.foo, 'bar'); + t.is(response.body.foo, 'bar'); }); test('beforeRequest awaits async function', async t => { - const res = await got( + const response = await got( s.url, { json: true, @@ -65,7 +69,7 @@ test('beforeRequest awaits async function', async t => { } } ); - t.is(res.body.foo, 'bar'); + t.is(response.body.foo, 'bar'); }); test('beforeRequest rejects when beforeRequest throws', async t => { @@ -99,7 +103,3 @@ test('beforeRequest rejects when beforeRequest rejects', async t => { } ); }); - -test.after('cleanup', async () => { - await s.close(); -}); diff --git a/test/http.js b/test/http.js index a62c0509b..bba92327f 100644 --- a/test/http.js +++ b/test/http.js @@ -8,31 +8,35 @@ let s; test.before('setup', async () => { s = await createServer(); - s.on('/', (req, res) => { - res.end('ok'); + s.on('/', (request, response) => { + response.end('ok'); }); - s.on('/empty', (req, res) => { - res.end(); + s.on('/empty', (request, response) => { + response.end(); }); - s.on('/304', (req, res) => { - res.statusCode = 304; - res.end(); + s.on('/304', (request, response) => { + response.statusCode = 304; + response.end(); }); - s.on('/404', (req, res) => { - res.statusCode = 404; - res.end('not'); + s.on('/404', (request, response) => { + response.statusCode = 404; + response.end('not'); }); - s.on('/?recent=true', (req, res) => { - res.end('recent'); + s.on('/?recent=true', (request, response) => { + response.end('recent'); }); await s.listen(s.port); }); +test.after('cleanup', async () => { + await s.close(); +}); + test('simple request', async t => { t.is((await got(s.url)).body, 'ok'); }); @@ -47,9 +51,9 @@ test('requestUrl response', async t => { }); test('error with code', async t => { - const err = await t.throws(got(`${s.url}/404`)); - t.is(err.statusCode, 404); - t.is(err.response.body, 'not'); + const error = await t.throws(got(`${s.url}/404`)); + t.is(error.statusCode, 404); + t.is(error.response.body, 'not'); }); test('status code 304 doesn\'t throw', async t => { @@ -65,8 +69,8 @@ test('doesn\'t throw on throwHttpErrors === false', async t => { }); test('invalid protocol throws', async t => { - const err = await t.throws(got('c:/nope.com', {json: true})); - t.is(err.constructor, got.UnsupportedProtocolError); + const error = await t.throws(got('c:/nope.com', {json: true})); + t.is(error.constructor, got.UnsupportedProtocolError); }); test('buffer on encoding === null', async t => { @@ -87,7 +91,3 @@ test('requestUrl response when sending url as param', async t => { test('response contains url', async t => { t.is((await got(s.url)).url, `${s.url}/`); }); - -test.after('cleanup', async () => { - await s.close(); -}); diff --git a/test/https.js b/test/https.js index aeb1f8cae..a02f8745c 100644 --- a/test/https.js +++ b/test/https.js @@ -36,11 +36,15 @@ test.before('setup', async () => { s = await createSSLServer({key, cert}); - s.on('/', (req, res) => res.end('ok')); + s.on('/', (request, response) => response.end('ok')); await s.listen(s.port); }); +test.after('cleanup', async () => { + await s.close(); +}); + test('make request to https server without ca', async t => { t.truthy((await got(s.url, {rejectUnauthorized: false})).body); }); @@ -62,6 +66,3 @@ test('protocol-less URLs default to HTTPS', async t => { t.true(requestUrl.startsWith('https://')); }); -test.after('cleanup', async () => { - await s.close(); -}); diff --git a/test/json-parse.js b/test/json-parse.js index dcc823f7d..9c112529f 100644 --- a/test/json-parse.js +++ b/test/json-parse.js @@ -7,36 +7,40 @@ let s; test.before('setup', async () => { s = await createServer(); - s.on('/', (req, res) => { - res.end('{"data":"dog"}'); + s.on('/', (request, response) => { + response.end('{"data":"dog"}'); }); - s.on('/invalid', (req, res) => { - res.end('/'); + s.on('/invalid', (request, response) => { + response.end('/'); }); - s.on('/no-body', (req, res) => { - res.statusCode = 200; - res.end(); + s.on('/no-body', (request, response) => { + response.statusCode = 200; + response.end(); }); - s.on('/non200', (req, res) => { - res.statusCode = 500; - res.end('{"data":"dog"}'); + s.on('/non200', (request, response) => { + response.statusCode = 500; + response.end('{"data":"dog"}'); }); - s.on('/non200-invalid', (req, res) => { - res.statusCode = 500; - res.end('Internal error'); + s.on('/non200-invalid', (request, response) => { + response.statusCode = 500; + response.end('Internal error'); }); - s.on('/headers', (req, res) => { - res.end(JSON.stringify(req.headers)); + s.on('/headers', (request, response) => { + response.end(JSON.stringify(request.headers)); }); await s.listen(s.port); }); +test.after('cleanup', async () => { + await s.close(); +}); + test('parses response', async t => { t.deepEqual((await got(s.url, {json: true})).body, {data: 'dog'}); }); @@ -47,28 +51,28 @@ test('not parses responses without a body', async t => { }); test('wraps parsing errors', async t => { - const err = await t.throws(got(`${s.url}/invalid`, {json: true})); - t.regex(err.message, /Unexpected token/); - t.true(err.message.includes(err.hostname), err.message); - t.is(err.path, '/invalid'); + const error = await t.throws(got(`${s.url}/invalid`, {json: true})); + t.regex(error.message, /Unexpected token/); + t.true(error.message.includes(error.hostname), error.message); + t.is(error.path, '/invalid'); }); test('parses non-200 responses', async t => { - const err = await t.throws(got(`${s.url}/non200`, {json: true})); - t.deepEqual(err.response.body, {data: 'dog'}); + const error = await t.throws(got(`${s.url}/non200`, {json: true})); + t.deepEqual(error.response.body, {data: 'dog'}); }); test('ignores errors on invalid non-200 responses', async t => { - const err = await t.throws(got(`${s.url}/non200-invalid`, {json: true})); - t.is(err.message, 'Response code 500 (Internal Server Error)'); - t.is(err.response.body, 'Internal error'); - t.is(err.path, '/non200-invalid'); + const error = await t.throws(got(`${s.url}/non200-invalid`, {json: true})); + t.is(error.message, 'Response code 500 (Internal Server Error)'); + t.is(error.response.body, 'Internal error'); + t.is(error.path, '/non200-invalid'); }); -test('should have statusCode in err', async t => { - const err = await t.throws(got(`${s.url}/invalid`, {json: true})); - t.is(err.constructor, got.ParseError); - t.is(err.statusCode, 200); +test('should have statusCode in error', async t => { + const error = await t.throws(got(`${s.url}/invalid`, {json: true})); + t.is(error.constructor, got.ParseError); + t.is(error.statusCode, 200); }); test('should set correct headers', async t => { @@ -76,7 +80,3 @@ test('should set correct headers', async t => { t.is(headers['content-type'], 'application/json'); t.is(headers.accept, 'application/json'); }); - -test.after('cleanup', async () => { - await s.close(); -}); diff --git a/test/post.js b/test/post.js index 7a4d5168a..3eabba6c1 100644 --- a/test/post.js +++ b/test/post.js @@ -8,22 +8,26 @@ let s; test.before('setup', async () => { s = await createServer(); - s.on('/', (req, res) => { - res.setHeader('method', req.method); - req.pipe(res); + s.on('/', (request, response) => { + response.setHeader('method', request.method); + request.pipe(response); }); - s.on('/headers', (req, res) => { - res.end(JSON.stringify(req.headers)); + s.on('/headers', (request, response) => { + response.end(JSON.stringify(request.headers)); }); - s.on('/empty', (req, res) => { - res.end(); + s.on('/empty', (request, response) => { + response.end(); }); await s.listen(s.port); }); +test.after('cleanup', async () => { + await s.close(); +}); + test('GET can have body', async t => { const {body, headers} = await got.get(s.url, {body: 'hi'}); t.is(body, 'hi'); @@ -143,7 +147,3 @@ test('throws when json body is not a plain object or array', async t => { test('throws when form body is not a plain object or array', async t => { await t.throws(got(`${s.url}`, {body: 'such=wow', form: true}), TypeError); }); - -test.after('cleanup', async () => { - await s.close(); -}); diff --git a/test/progress.js b/test/progress.js index a68fe8198..8526621e9 100644 --- a/test/progress.js +++ b/test/progress.js @@ -42,42 +42,46 @@ let s; test.before('setup', async () => { s = await createServer(); - s.on('/download', (req, res) => { - res.setHeader('content-length', file.length); + s.on('/download', (request, response) => { + response.setHeader('content-length', file.length); toReadableStream(file) .pipe(new SlowStream({maxWriteInterval: 50})) - .pipe(res); + .pipe(response); }); - s.on('/download/no-total', (req, res) => { - res.write('hello'); - res.end(); + s.on('/download/no-total', (request, response) => { + response.write('hello'); + response.end(); }); - s.on('/upload', (req, res) => { - req + s.on('/upload', (request, response) => { + request .pipe(new SlowStream({maxWriteInterval: 100})) - .on('end', () => res.end()); + .on('end', () => response.end()); }); await s.listen(s.port); }); +test.after('cleanup', async () => { + await s.close(); +}); + test('download progress', async t => { const events = []; - const res = await got(`${s.url}/download`, {encoding: null}) - .on('downloadProgress', e => events.push(e)); + const response = await got(`${s.url}/download`, {encoding: null}) + .on('downloadProgress', event => events.push(event)); - checkEvents(t, events, res.body.length); + checkEvents(t, events, response.body.length); }); test('download progress - missing total size', async t => { const events = []; await got(`${s.url}/download/no-total`) - .on('downloadProgress', e => events.push(e)); + .on('downloadProgress', event => events.push(event)); checkEvents(t, events); }); @@ -86,7 +90,7 @@ test('download progress - stream', async t => { const events = []; const stream = got.stream(`${s.url}/download`, {encoding: null}) - .on('downloadProgress', e => events.push(e)); + .on('downloadProgress', event => events.push(event)); await getStream(stream); @@ -97,7 +101,7 @@ test('upload progress - file', async t => { const events = []; await got.post(`${s.url}/upload`, {body: file}) - .on('uploadProgress', e => events.push(e)); + .on('uploadProgress', event => events.push(event)); checkEvents(t, events, file.length); }); @@ -109,7 +113,7 @@ test('upload progress - file stream', async t => { const events = []; await got.post(`${s.url}/upload`, {body: fs.createReadStream(path)}) - .on('uploadProgress', e => events.push(e)); + .on('uploadProgress', event => events.push(event)); checkEvents(t, events, file.length); }); @@ -124,7 +128,7 @@ test('upload progress - form data', async t => { const size = await util.promisify(body.getLength.bind(body))(); await got.post(`${s.url}/upload`, {body}) - .on('uploadProgress', e => events.push(e)); + .on('uploadProgress', event => events.push(event)); checkEvents(t, events, size); }); @@ -135,7 +139,7 @@ test('upload progress - json', async t => { const events = []; await got.post(`${s.url}/upload`, {body}) - .on('uploadProgress', e => events.push(e)); + .on('uploadProgress', event => events.push(event)); checkEvents(t, events, size); }); @@ -146,10 +150,10 @@ test('upload progress - stream with known body size', async t => { headers: {'content-length': file.length} }; - const req = got.stream.post(`${s.url}/upload`, options) - .on('uploadProgress', e => events.push(e)); + const request = got.stream.post(`${s.url}/upload`, options) + .on('uploadProgress', event => events.push(event)); - await getStream(toReadableStream(file).pipe(req)); + await getStream(toReadableStream(file).pipe(request)); checkEvents(t, events, file.length); }); @@ -157,10 +161,10 @@ test('upload progress - stream with known body size', async t => { test('upload progress - stream with unknown body size', async t => { const events = []; - const req = got.stream.post(`${s.url}/upload`) - .on('uploadProgress', e => events.push(e)); + const request = got.stream.post(`${s.url}/upload`) + .on('uploadProgress', event => events.push(event)); - await getStream(toReadableStream(file).pipe(req)); + await getStream(toReadableStream(file).pipe(request)); checkEvents(t, events); }); @@ -169,7 +173,7 @@ test('upload progress - no body', async t => { const events = []; await got.post(`${s.url}/upload`) - .on('uploadProgress', e => events.push(e)); + .on('uploadProgress', event => events.push(event)); t.deepEqual(events, [ { @@ -184,7 +188,3 @@ test('upload progress - no body', async t => { } ]); }); - -test.after('cleanup', async () => { - await s.close(); -}); diff --git a/test/promise.js b/test/promise.js index dbb7e5908..e02362ced 100644 --- a/test/promise.js +++ b/test/promise.js @@ -8,27 +8,27 @@ let s; test.before('setup', async () => { s = await createServer(); - s.on('/', (req, res) => { - res.statusCode = 200; - res.end(); + s.on('/', (request, response) => { + response.statusCode = 200; + response.end(); }); await s.listen(s.port); }); +test.after('cleanup', async () => { + await s.close(); +}); + test('should emit request event as promise', async t => { - await got(s.url, {json: true}).on('request', req => { - t.true(req instanceof ClientRequest); + await got(s.url, {json: true}).on('request', request => { + t.true(request instanceof ClientRequest); }); }); test('should emit response event as promise', async t => { - await got(s.url, {json: true}).on('response', res => { - t.true(res instanceof Transform); - t.true(res.readable); - t.is(res.statusCode, 200); + await got(s.url, {json: true}).on('response', response => { + t.true(response instanceof Transform); + t.true(response.readable); + t.is(response.statusCode, 200); }); }); - -test.after('cleanup', async () => { - await s.close(); -}); diff --git a/test/redirects.js b/test/redirects.js index 90eb5f421..7e675c219 100644 --- a/test/redirects.js +++ b/test/redirects.js @@ -40,95 +40,95 @@ test.before('setup', async () => { // HTTPS Handlers - https.on('/', (req, res) => { - res.end('https'); + https.on('/', (request, response) => { + response.end('https'); }); - https.on('/httpsToHttp', (req, res) => { - res.writeHead(302, { + https.on('/httpsToHttp', (request, response) => { + response.writeHead(302, { location: http.url }); - res.end(); + response.end(); }); // HTTP Handlers - http.on('/', (req, res) => { - res.end('reached'); + http.on('/', (request, response) => { + response.end('reached'); }); - http.on('/finite', (req, res) => { - res.writeHead(302, { + http.on('/finite', (request, response) => { + response.writeHead(302, { location: `${http.url}/` }); - res.end(); + response.end(); }); - http.on('/utf8-url-áé', (req, res) => { - res.end('reached'); + http.on('/utf8-url-áé', (request, response) => { + response.end('reached'); }); - http.on('/redirect-with-utf8-binary', (req, res) => { - res.writeHead(302, { + http.on('/redirect-with-utf8-binary', (request, response) => { + response.writeHead(302, { location: Buffer.from((new URL('/utf8-url-áé', http.url)).toString(), 'utf8').toString('binary') }); - res.end(); + response.end(); }); - http.on('/endless', (req, res) => { - res.writeHead(302, { + http.on('/endless', (request, response) => { + response.writeHead(302, { location: `${http.url}/endless` }); - res.end(); + response.end(); }); - http.on('/relative', (req, res) => { - res.writeHead(302, { + http.on('/relative', (request, response) => { + response.writeHead(302, { location: '/' }); - res.end(); + response.end(); }); - http.on('/seeOther', (req, res) => { - res.writeHead(303, { + http.on('/seeOther', (request, response) => { + response.writeHead(303, { location: '/' }); - res.end(); + response.end(); }); - http.on('/temporary', (req, res) => { - res.writeHead(307, { + http.on('/temporary', (request, response) => { + response.writeHead(307, { location: '/' }); - res.end(); + response.end(); }); - http.on('/permanent', (req, res) => { - res.writeHead(308, { + http.on('/permanent', (request, response) => { + response.writeHead(308, { location: '/' }); - res.end(); + response.end(); }); - http.on('/relativeQuery?bang', (req, res) => { - res.writeHead(302, { + http.on('/relativeQuery?bang', (request, response) => { + response.writeHead(302, { location: '/' }); - res.end(); + response.end(); }); - http.on('/httpToHttps', (req, res) => { - res.writeHead(302, { + http.on('/httpToHttps', (request, response) => { + response.writeHead(302, { location: https.url }); - res.end(); + response.end(); }); - http.on('/malformedRedirect', (req, res) => { - res.writeHead(302, { + http.on('/malformedRedirect', (request, response) => { + response.writeHead(302, { location: '/%D8' }); - res.end(); + response.end(); }); await http.listen(http.port); @@ -163,9 +163,9 @@ test('relative redirect works', async t => { }); test('throws on endless redirect', async t => { - const err = await t.throws(got(`${http.url}/endless`)); - t.is(err.message, 'Redirected 10 times. Aborting.'); - t.deepEqual(err.redirectUrls, new Array(10).fill(`${http.url}/endless`)); + const error = await t.throws(got(`${http.url}/endless`)); + t.is(error.message, 'Redirected 10 times. Aborting.'); + t.deepEqual(error.redirectUrls, new Array(10).fill(`${http.url}/endless`)); }); test('query in options are not breaking redirects', async t => { @@ -180,10 +180,10 @@ test('hostname+path in options are not breaking redirects', async t => { }); test('redirect only GET and HEAD requests', async t => { - const err = await t.throws(got(`${http.url}/relative`, {body: 'wow'})); - t.is(err.message, 'Response code 302 (Found)'); - t.is(err.path, '/relative'); - t.is(err.statusCode, 302); + const error = await t.throws(got(`${http.url}/relative`, {body: 'wow'})); + t.is(error.message, 'Response code 302 (Found)'); + t.is(error.path, '/relative'); + t.is(error.statusCode, 302); }); test('redirect on 303 response even with post, put, delete', async t => { @@ -220,6 +220,6 @@ test('redirect response contains utf8 with binary encoding', async t => { }); test('throws on malformed redirect URI', async t => { - const err = await t.throws(got(`${http.url}/malformedRedirect`)); - t.is(err.name, 'URIError'); + const error = await t.throws(got(`${http.url}/malformedRedirect`)); + t.is(error.name, 'URIError'); }); diff --git a/test/retry.js b/test/retry.js index 364097bbc..72807d2ec 100644 --- a/test/retry.js +++ b/test/retry.js @@ -17,9 +17,9 @@ test.before('setup', async () => { s.on('/long', () => {}); - s.on('/knock-twice', (req, res) => { + s.on('/knock-twice', (request, response) => { if (knocks++ === 1) { - res.end('who`s there?'); + response.end('who`s there?'); } }); @@ -27,56 +27,60 @@ test.before('setup', async () => { trys++; }); - s.on('/fifth', (req, res) => { + s.on('/fifth', (request, response) => { if (fifth++ === 5) { - res.end('who`s there?'); + response.end('who`s there?'); } }); - s.on('/500', (req, res) => { - res.statusCode = 500; - res.end(); + s.on('/500', (request, response) => { + response.statusCode = 500; + response.end(); }); - s.on('/measure413', (req, res) => { - res.writeHead(413, { + s.on('/measure413', (request, response) => { + response.writeHead(413, { 'Retry-After': retryAfterOn413 }); - res.end((Date.now() - lastTried413access).toString()); + response.end((Date.now() - lastTried413access).toString()); lastTried413access = Date.now(); }); - s.on('/413', (req, res) => { - res.writeHead(413, { + s.on('/413', (request, response) => { + response.writeHead(413, { 'Retry-After': retryAfterOn413 }); - res.end(); + response.end(); }); - s.on('/413withoutRetryAfter', (req, res) => { - res.statusCode = 413; - res.end(); + s.on('/413withoutRetryAfter', (request, response) => { + response.statusCode = 413; + response.end(); }); - s.on('/503', (req, res) => { - res.statusCode = 503; - res.end(); + s.on('/503', (request, response) => { + response.statusCode = 503; + response.end(); }); await s.listen(s.port); }); +test.after('cleanup', async () => { + await s.close(); +}); + test('works on timeout error', async t => { t.is((await got(`${s.url}/knock-twice`, {timeout: {socket: socketTimeout}})).body, 'who`s there?'); }); test('can be disabled with option', async t => { - const err = await t.throws(got(`${s.url}/try-me`, { + const error = await t.throws(got(`${s.url}/try-me`, { timeout: {socket: socketTimeout}, retry: 0 })); - t.truthy(err); + t.truthy(error); t.is(trys, 1); }); @@ -91,31 +95,31 @@ test('function gets iter count', async t => { }); test('falsy value prevents retries', async t => { - const err = await t.throws(got(`${s.url}/long`, { + const error = await t.throws(got(`${s.url}/long`, { timeout: {socket: socketTimeout}, retry: { retries: () => 0 } })); - t.truthy(err); + t.truthy(error); }); test('falsy value prevents retries #2', async t => { - const err = await t.throws(got(`${s.url}/long`, { + const error = await t.throws(got(`${s.url}/long`, { timeout: {socket: socketTimeout}, retry: { - retries: (iter, err) => { - t.truthy(err); + retries: (iter, error) => { + t.truthy(error); return false; } } })); - t.truthy(err); + t.truthy(error); }); test('custom retries', async t => { let tried = false; - const err = await t.throws(got(`${s.url}/500`, { + const error = await t.throws(got(`${s.url}/500`, { throwHttpErrors: true, retry: { retries: iter => { @@ -132,7 +136,7 @@ test('custom retries', async t => { ] } })); - t.is(err.statusCode, 500); + t.is(error.statusCode, 500); t.true(tried); }); @@ -203,7 +207,3 @@ test('doesn\'t retry if Retry-After header is greater than maxRetryAfter', async }); t.is(retryCount, 0); }); - -test.after('cleanup', async () => { - await s.close(); -}); diff --git a/test/socket-destroyed.js b/test/socket-destroyed.js index bb85cd309..659c324c3 100644 --- a/test/socket-destroyed.js +++ b/test/socket-destroyed.js @@ -4,11 +4,11 @@ import got from '../source'; const {Timer} = process.binding('timer_wrap'); test.serial('clear the progressInterval if the socket has been destroyed', async t => { - const err = await t.throws(got(`http://127.0.0.1:55555`, {retry: 0})); + const error = await t.throws(got(`http://127.0.0.1:55555`, {retry: 0})); const progressIntervalTimer = process._getActiveHandles().filter(handle => { // Check if the handle is a Timer that matches the `uploadEventFrequency` interval return handle instanceof Timer && handle._list.msecs === 150; }); t.is(progressIntervalTimer.length, 0); - t.is(err.code, 'ECONNREFUSED'); + t.is(error.code, 'ECONNREFUSED'); }); diff --git a/test/stream.js b/test/stream.js index 54b7b811b..5e1defaf6 100644 --- a/test/stream.js +++ b/test/stream.js @@ -11,32 +11,36 @@ let s; test.before('setup', async () => { s = await createServer(); - s.on('/', (req, res) => { - res.writeHead(200, { + s.on('/', (request, response) => { + response.writeHead(200, { unicorn: 'rainbow' }); - res.end('ok'); + response.end('ok'); }); - s.on('/post', (req, res) => { - req.pipe(res); + s.on('/post', (request, response) => { + request.pipe(response); }); - s.on('/redirect', (req, res) => { - res.writeHead(302, { + s.on('/redirect', (request, response) => { + response.writeHead(302, { location: s.url }); - res.end(); + response.end(); }); - s.on('/error', (req, res) => { - res.statusCode = 404; - res.end(); + s.on('/error', (request, response) => { + response.statusCode = 404; + response.end(); }); await s.listen(s.port); }); +test.after('cleanup', async () => { + await s.close(); +}); + test('option.json can not be used', t => { t.throws(() => { got.stream(s.url, {json: true}); @@ -117,8 +121,8 @@ test('piping works', async t => { test('proxying headers works', async t => { const server = await createServer(); - server.on('/', (req, res) => { - got.stream(s.url).pipe(res); + server.on('/', (request, response) => { + got.stream(s.url).pipe(response); }); await server.listen(server.port); @@ -128,7 +132,3 @@ test('proxying headers works', async t => { await server.close(); }); - -test.after('cleanup', async () => { - await s.close(); -}); diff --git a/test/timeout.js b/test/timeout.js index 309dfab28..f1af9edd0 100644 --- a/test/timeout.js +++ b/test/timeout.js @@ -9,7 +9,7 @@ import got from '../source'; import {createServer} from './helpers/server'; let s; -const reqDelay = 250; + const slowDataStream = () => { const slowStream = new stream.PassThrough(); let count = 0; @@ -22,11 +22,15 @@ const slowDataStream = () => { }, 100); return slowStream; }; -const reqTimeout = reqDelay - 10; + +const requestDelay = 250; +const requestTimeout = requestDelay - 10; + const errorMatcher = { instanceOf: got.TimeoutError, code: 'ETIMEDOUT' }; + const keepAliveAgent = new http.Agent({ keepAlive: true }); @@ -34,24 +38,24 @@ const keepAliveAgent = new http.Agent({ test.before('setup', async () => { s = await createServer(); - s.on('/', async (req, res) => { - req.on('data', () => {}); - req.on('end', async () => { - await delay(reqDelay); - res.end('OK'); + s.on('/', async (request, response) => { + request.on('data', () => {}); + request.on('end', async () => { + await delay(requestDelay); + response.end('OK'); }); }); - s.on('/download', async (req, res) => { - res.writeHead(200, { + s.on('/download', async (request, response) => { + response.writeHead(200, { 'transfer-encoding': 'chunked' }); - res.flushHeaders(); - slowDataStream().pipe(res); + response.flushHeaders(); + slowDataStream().pipe(response); }); - s.on('/prime', (req, res) => { - res.end('OK'); + s.on('/prime', (request, response) => { + response.end('OK'); }); await s.listen(s.port); @@ -73,7 +77,7 @@ test('timeout option (ETIMEDOUT)', async t => { test('timeout option as object (ETIMEDOUT)', async t => { await t.throws( got(s.url, { - timeout: {socket: reqDelay * 2.5, request: 1}, + timeout: {socket: requestDelay * 2.5, request: 1}, retry: 0 }), { @@ -86,13 +90,13 @@ test('timeout option as object (ETIMEDOUT)', async t => { test('socket timeout', async t => { await t.throws( got(s.url, { - timeout: {socket: reqTimeout}, + timeout: {socket: requestTimeout}, retry: 0 }), { instanceOf: got.TimeoutError, code: 'ETIMEDOUT', - message: `Timeout awaiting 'socket' for ${reqTimeout}ms` + message: `Timeout awaiting 'socket' for ${requestTimeout}ms` } ); }); @@ -118,8 +122,8 @@ test('send timeout (keepalive)', async t => { timeout: {send: 1}, retry: 0, body: slowDataStream() - }).on('request', req => { - req.once('socket', socket => { + }).on('request', request => { + request.once('socket', socket => { t.false(socket.connecting); socket.once('connect', () => { t.fail(`'connect' event fired, invalidating test`); @@ -148,7 +152,7 @@ test('response timeout', async t => { test('response timeout unaffected by slow upload', async t => { await got(s.url, { - timeout: {response: reqDelay * 2}, + timeout: {response: requestDelay * 2}, retry: 0, body: slowDataStream() }).on('request', request => { @@ -156,7 +160,7 @@ test('response timeout unaffected by slow upload', async t => { t.fail(`unexpected error: ${error}`); }); }); - await delay(reqDelay * 3); + await delay(requestDelay * 3); t.pass('no error emitted'); }); @@ -169,7 +173,7 @@ test('response timeout unaffected by slow download', async t => { t.fail(`unexpected error: ${error}`); }); }); - await delay(reqDelay * 3); + await delay(requestDelay * 3); t.pass('no error emitted'); }); @@ -180,8 +184,8 @@ test('response timeout (keepalive)', async t => { agent: keepAliveAgent, timeout: {response: 1}, retry: 0 - }).on('request', req => { - req.once('socket', socket => { + }).on('request', request => { + request.once('socket', socket => { t.false(socket.connecting); socket.once('connect', () => { t.fail(`'connect' event fired, invalidating test`); @@ -298,12 +302,12 @@ test('lookup timeout no error (keepalive)', async t => { test('request timeout', async t => { await t.throws( got(s.url, { - timeout: {request: reqTimeout}, + timeout: {request: requestTimeout}, retry: 0 }), { ...errorMatcher, - message: `Timeout awaiting 'request' for ${reqTimeout}ms` + message: `Timeout awaiting 'request' for ${requestTimeout}ms` } ); }); @@ -312,7 +316,7 @@ test('retries on timeout (ESOCKETTIMEDOUT)', async t => { let tried = false; await t.throws(got(s.url, { - timeout: reqTimeout, + timeout: requestTimeout, retry: { retries: () => { if (tried) { @@ -325,7 +329,7 @@ test('retries on timeout (ESOCKETTIMEDOUT)', async t => { } }), { ...errorMatcher, - message: `Timeout awaiting 'request' for ${reqTimeout}ms` + message: `Timeout awaiting 'request' for ${requestTimeout}ms` }); t.true(tried); @@ -363,14 +367,14 @@ test('no error emitted when timeout is not breached (stream)', async t => { const stream = got.stream(s.url, { retry: 0, timeout: { - request: reqDelay * 2 + request: requestDelay * 2 } }); stream.on('error', err => { t.fail(`error was emitted: ${err}`); }); await getStream(stream); - await delay(reqDelay * 3); + await delay(requestDelay * 3); t.pass(); }); @@ -378,15 +382,15 @@ test('no error emitted when timeout is not breached (promise)', async t => { await got(s.url, { retry: 0, timeout: { - request: reqDelay * 2 + request: requestDelay * 2 } - }).on('request', req => { + }).on('request', request => { // 'error' events are not emitted by the Promise interface, so attach // directly to the request object - req.on('error', err => { - t.fail(`error was emitted: ${err}`); + request.on('error', error => { + t.fail(`error was emitted: ${error}`); }); }); - await delay(reqDelay * 3); + await delay(requestDelay * 3); t.pass(); }); diff --git a/test/unix-socket.js b/test/unix-socket.js index 7e40801bd..769b1b1c2 100644 --- a/test/unix-socket.js +++ b/test/unix-socket.js @@ -12,17 +12,21 @@ if (process.platform !== 'win32') { test.before('setup', async () => { s = await createServer(); - s.on('/', (req, res) => { - res.end('ok'); + s.on('/', (request, response) => { + response.end('ok'); }); - s.on('/foo:bar', (req, res) => { - res.end('ok'); + s.on('/foo:bar', (request, response) => { + response.end('ok'); }); await s.listen(socketPath); }); + test.after('cleanup', async () => { + await s.close(); + }); + test('works', async t => { const url = format('http://unix:%s:%s', socketPath, '/'); t.is((await got(url)).body, 'ok'); @@ -37,8 +41,4 @@ if (process.platform !== 'win32') { const url = format('unix:%s:%s', socketPath, '/foo:bar'); t.is((await got(url)).body, 'ok'); }); - - test.after('cleanup', async () => { - await s.close(); - }); }