Browse Source

Merge pull request #140 from sindresorhus/6.0.0

6.0.0 💥
http2
Vsevolod Strukchinsky 9 years ago
parent
commit
fc3c2a53b9
  1. 2
      .travis.yml
  2. 238
      index.js
  3. 21
      package.json
  4. 44
      readme.md
  5. 43
      test/_server.js
  6. 13
      test/arguments.js
  7. 13
      test/error.js
  8. 6
      test/gzip.js
  9. 8
      test/headers.js
  10. 14
      test/helpers.js
  11. 38
      test/helpers/server.js
  12. 6
      test/http.js
  13. 6
      test/https.js
  14. 6
      test/json.js
  15. 8
      test/post.js
  16. 6
      test/redirects.js
  17. 6
      test/retry.js
  18. 42
      test/stream.js
  19. 6
      test/unix-socket.js

2
.travis.yml

@ -3,6 +3,4 @@ language: node_js
node_js:
- '5'
- '4'
- '0.12'
- '0.10'
after_success: npm run coveralls

238
index.js

@ -1,36 +1,35 @@
'use strict';
var EventEmitter = require('events').EventEmitter;
var http = require('http');
var https = require('https');
var urlLib = require('url');
var querystring = require('querystring');
var objectAssign = require('object-assign');
var duplexify = require('duplexify');
var isStream = require('is-stream');
var readAllStream = require('read-all-stream');
var timedOut = require('timed-out');
var urlParseLax = require('url-parse-lax');
var lowercaseKeys = require('lowercase-keys');
var isRedirect = require('is-redirect');
var PinkiePromise = require('pinkie-promise');
var unzipResponse = require('unzip-response');
var createErrorClass = require('create-error-class');
var nodeStatusCodes = require('node-status-codes');
var isPlainObj = require('is-plain-obj');
var parseJson = require('parse-json');
const EventEmitter = require('events').EventEmitter;
const http = require('http');
const https = require('https');
const PassThrough = require('stream').PassThrough;
const duplexer2 = require('@floatdrop/duplexer2');
const urlLib = require('url');
const querystring = require('querystring');
const isStream = require('is-stream');
const getStream = require('get-stream');
const timedOut = require('timed-out');
const urlParseLax = require('url-parse-lax');
const lowercaseKeys = require('lowercase-keys');
const isRedirect = require('is-redirect');
const unzipResponse = require('unzip-response');
const createErrorClass = require('create-error-class');
const nodeStatusCodes = require('node-status-codes');
const isPlainObj = require('is-plain-obj');
function requestAsEventEmitter(opts) {
opts = opts || {};
var ee = new EventEmitter();
var redirectCount = 0;
var retryCount = 0;
const ee = new EventEmitter();
let redirectCount = 0;
let retryCount = 0;
var get = function (opts) {
var fn = opts.protocol === 'https:' ? https : http;
const get = opts => {
const fn = opts.protocol === 'https:' ? https : http;
var req = fn.request(opts, function (res) {
var statusCode = res.statusCode;
const req = fn.request(opts, res => {
const statusCode = res.statusCode;
if (isRedirect(statusCode) && 'location' in res.headers && (opts.method === 'GET' || opts.method === 'HEAD')) {
res.resume();
@ -40,8 +39,8 @@ function requestAsEventEmitter(opts) {
return;
}
var redirectUrl = urlLib.resolve(urlLib.format(opts), res.headers.location);
var redirectOpts = objectAssign({}, opts, urlLib.parse(redirectUrl));
const redirectUrl = urlLib.resolve(urlLib.format(opts), res.headers.location);
const redirectOpts = Object.assign({}, opts, urlLib.parse(redirectUrl));
ee.emit('redirect', res, redirectOpts);
@ -49,14 +48,14 @@ function requestAsEventEmitter(opts) {
return;
}
// do not write ee.bind(...) instead of function - it will break gzip in Node.js 0.10
setImmediate(function () {
setImmediate(() => {
ee.emit('response', typeof unzipResponse === 'function' && req.method !== 'HEAD' ? unzipResponse(res) : res);
});
});
req.once('error', function (err) {
var backoff = opts.retries(++retryCount, err);
req.once('error', err => {
const backoff = opts.retries(++retryCount, err);
if (backoff) {
setTimeout(get, backoff, opts);
return;
@ -69,92 +68,79 @@ function requestAsEventEmitter(opts) {
timedOut(req, opts.timeout);
}
setImmediate(ee.emit.bind(ee), 'request', req);
setImmediate(() => ee.emit('request', req));
};
get(opts);
return ee;
}
function asCallback(opts, cb) {
var ee = requestAsEventEmitter(opts);
ee.on('request', function (req) {
if (isStream(opts.body)) {
opts.body.pipe(req);
opts.body = undefined;
return;
}
req.end(opts.body);
});
ee.on('response', function (res) {
readAllStream(res, opts.encoding, function (err, data) {
var statusCode = res.statusCode;
function asPromise(opts) {
return new Promise((resolve, reject) => {
const ee = requestAsEventEmitter(opts);
if (err) {
cb(new got.ReadError(err, opts), null, res);
ee.on('request', req => {
if (isStream(opts.body)) {
opts.body.pipe(req);
opts.body = undefined;
return;
}
if (statusCode < 200 || statusCode > 299) {
err = new got.HTTPError(statusCode, opts);
}
if (opts.json && statusCode !== 204) {
try {
data = parseJson(data);
} catch (e) {
e.fileName = urlLib.format(opts);
err = new got.ParseError(e, opts);
}
}
cb(err, data, res);
req.end(opts.body);
});
});
ee.on('error', cb);
}
function asPromise(opts) {
return new PinkiePromise(function (resolve, reject) {
asCallback(opts, function (err, data, response) {
if (response) {
response.body = data;
}
if (err) {
Object.defineProperty(err, 'response', {
value: response,
enumerable: false
ee.on('response', res => {
const stream = opts.encoding === null ? getStream.buffer(res) : getStream(res, opts);
stream
.catch(err => reject(new got.ReadError(err, opts)))
.then(data => {
const statusCode = res.statusCode;
res.body = data;
if (opts.json && statusCode !== 204) {
try {
res.body = JSON.parse(res.body);
} catch (e) {
throw new got.ParseError(e, opts, data);
}
}
if (statusCode < 200 || statusCode > 299) {
throw new got.HTTPError(statusCode, opts);
}
resolve(res);
})
.catch(err => {
Object.defineProperty(err, 'response', {value: res});
reject(err);
});
reject(err);
return;
}
resolve(response);
});
ee.on('error', reject);
});
}
function asStream(opts) {
var proxy = duplexify();
const input = new PassThrough();
const output = new PassThrough();
const proxy = duplexer2(input, output);
if (opts.json) {
throw new Error('got can not be used as stream when options.json is used');
}
if (opts.body) {
proxy.write = function () {
proxy.write = () => {
throw new Error('got\'s stream is not writable when options.body is used');
};
}
var ee = requestAsEventEmitter(opts);
const ee = requestAsEventEmitter(opts);
ee.on('request', function (req) {
ee.on('request', req => {
proxy.emit('request', req);
if (isStream.readable(opts.body)) {
@ -168,17 +154,17 @@ function asStream(opts) {
}
if (opts.method === 'POST' || opts.method === 'PUT' || opts.method === 'PATCH') {
proxy.setWritable(req);
input.pipe(req);
return;
}
req.end();
});
ee.on('response', function (res) {
var statusCode = res.statusCode;
ee.on('response', res => {
const statusCode = res.statusCode;
proxy.setReadable(res);
res.pipe(output);
if (statusCode < 200 || statusCode > 299) {
proxy.emit('error', new got.HTTPError(statusCode, opts), null, res);
@ -197,7 +183,7 @@ function asStream(opts) {
function normalizeArguments(url, opts) {
if (typeof url !== 'string' && typeof url !== 'object') {
throw new Error('Parameter `url` must be a string or object, not ' + typeof url);
throw new Error(`Parameter \`url\` must be a string or object, not ${typeof url}`);
}
if (typeof url === 'string') {
@ -208,25 +194,25 @@ function normalizeArguments(url, opts) {
}
}
opts = objectAssign(
opts = Object.assign(
{protocol: 'http:', path: '', retries: 5},
url,
opts
);
opts.headers = objectAssign({
opts.headers = Object.assign({
'user-agent': 'https://github.com/sindresorhus/got',
'accept-encoding': 'gzip,deflate'
}, lowercaseKeys(opts.headers));
var query = opts.query;
const query = opts.query;
if (query) {
if (typeof query !== 'string') {
opts.query = querystring.stringify(query);
}
opts.path = opts.path.split('?')[0] + '?' + opts.query;
opts.path = `${opts.path.split('?')[0]}?${opts.query}`;
delete opts.query;
}
@ -234,7 +220,7 @@ function normalizeArguments(url, opts) {
opts.headers.accept = 'application/json';
}
var body = opts.body;
let body = opts.body;
if (body) {
if (typeof body !== 'string' && !Buffer.isBuffer(body) && !isStream.readable(body) && !isPlainObj(body)) {
@ -249,7 +235,7 @@ function normalizeArguments(url, opts) {
}
if (opts.headers['content-length'] === undefined && opts.headers['transfer-encoding'] === undefined && !isStream.readable(body)) {
var length = typeof body === 'string' ? Buffer.byteLength(body) : body.length;
const length = typeof body === 'string' ? Buffer.byteLength(body) : body.length;
opts.headers['content-length'] = length;
}
}
@ -257,7 +243,7 @@ function normalizeArguments(url, opts) {
opts.method = opts.method || 'GET';
if (opts.hostname === 'unix') {
var matches = /(.+)\:(.+)/.exec(opts.path);
const matches = /(.+)\:(.+)/.exec(opts.path);
if (matches) {
opts.socketPath = matches[1];
@ -267,13 +253,13 @@ function normalizeArguments(url, opts) {
}
if (typeof opts.retries !== 'function') {
var retries = opts.retries;
const retries = opts.retries;
opts.retries = function backoff(iter) {
if (iter > retries) {
return 0;
}
var noise = Math.random() * 100;
const noise = Math.random() * 100;
return (1 << iter) * 1000 + noise;
};
}
@ -281,25 +267,15 @@ function normalizeArguments(url, opts) {
return opts;
}
function got(url, opts, cb) {
if (typeof opts === 'function') {
cb = opts;
opts = {};
}
if (cb) {
asCallback(normalizeArguments(url, opts), cb);
return null;
}
function got(url, opts) {
try {
return asPromise(normalizeArguments(url, opts));
} catch (error) {
return PinkiePromise.reject(error);
return Promise.reject(error);
}
}
var helpers = [
const helpers = [
'get',
'post',
'put',
@ -308,28 +284,17 @@ var helpers = [
'delete'
];
helpers.forEach(function (el) {
got[el] = function (url, opts, cb) {
if (typeof opts === 'function') {
cb = opts;
opts = {};
}
return got(url, objectAssign({}, opts, {method: el.toUpperCase()}), cb);
};
helpers.forEach(el => {
got[el] = (url, opts) => got(url, Object.assign({}, opts, {method: el.toUpperCase()}));
});
got.stream = function (url, opts, cb) {
if (cb || typeof opts === 'function') {
throw new Error('callback can not be used with stream mode');
}
got.stream = function (url, opts) {
return asStream(normalizeArguments(url, opts));
};
helpers.forEach(function (el) {
helpers.forEach(el => {
got.stream[el] = function (url, opts) {
return got.stream(url, objectAssign({}, opts, {method: el.toUpperCase()}));
return got.stream(url, Object.assign({}, opts, {method: el.toUpperCase()}));
};
});
@ -338,7 +303,7 @@ function stdError(error, opts) {
this.code = error.code;
}
objectAssign(this, {
Object.assign(this, {
message: error.message,
host: opts.host,
hostname: opts.hostname,
@ -349,13 +314,16 @@ function stdError(error, opts) {
got.RequestError = createErrorClass('RequestError', stdError);
got.ReadError = createErrorClass('ReadError', stdError);
got.ParseError = createErrorClass('ParseError', stdError);
got.ParseError = createErrorClass('ParseError', function (e, opts, data) {
stdError.call(this, e, opts);
this.message = `${e.message} in "${urlLib.format(opts)}": \n${data.slice(0, 77)}...`;
});
got.HTTPError = createErrorClass('HTTPError', function (statusCode, opts) {
stdError.call(this, {}, opts);
this.statusCode = statusCode;
this.statusMessage = nodeStatusCodes[this.statusCode];
this.message = 'Response code ' + this.statusCode + ' (' + this.statusMessage + ')';
this.message = `Response code ${this.statusCode} (${this.statusMessage})`;
});
got.MaxRedirectsError = createErrorClass('MaxRedirectsError', function (statusCode, opts) {

21
package.json

@ -1,6 +1,6 @@
{
"name": "got",
"version": "5.3.0",
"version": "6.0.0-rc1",
"description": "Simplified HTTP/HTTPS requests",
"license": "MIT",
"repository": "sindresorhus/got",
@ -17,7 +17,7 @@
}
],
"engines": {
"node": ">=0.10.0"
"node": ">=4"
},
"browser": {
"unzip-response": false
@ -45,35 +45,30 @@
"fetch"
],
"dependencies": {
"create-error-class": "^2.0.0",
"duplexify": "^3.2.0",
"create-error-class": "^3.0.0",
"@floatdrop/duplexer2": "^0.1.4",
"get-stream": "^1.1.0",
"is-plain-obj": "^1.0.0",
"is-redirect": "^1.0.0",
"is-stream": "^1.0.0",
"lowercase-keys": "^1.0.0",
"node-status-codes": "^1.0.0",
"object-assign": "^4.0.1",
"parse-json": "^2.1.0",
"pinkie-promise": "^2.0.0",
"read-all-stream": "^3.0.0",
"timed-out": "^2.0.0",
"unzip-response": "^1.0.0",
"url-parse-lax": "^1.0.0"
},
"devDependencies": {
"ava": "^0.5.0",
"ava": "^0.9.0",
"coveralls": "^2.11.4",
"get-port": "^2.0.0",
"into-stream": "^2.0.0",
"nyc": "^3.2.2",
"nyc": "^5.0.1",
"pem": "^1.4.4",
"pify": "^2.3.0",
"tempfile": "^1.1.1",
"xo": "*"
},
"xo": {
"ignores": [
"test/**"
]
"esnext": true
}
}

44
readme.md

@ -19,6 +19,8 @@ Created because [`request`](https://github.com/mikeal/request) is bloated *(seve
## Install
**WARNING: Node.JS 4.x or higher required for got@6.0.0 and above.** For older Node.JS versions use got@5.
```
$ npm install --save got
```
@ -29,13 +31,6 @@ $ npm install --save got
```js
const got = require('got');
// Callback mode
got('todomvc.com', (error, body, response) => {
console.log(body);
//=> '<!doctype html> ...'
});
// Promise mode
got('todomvc.com')
.then(response => {
console.log(response.body);
@ -46,7 +41,7 @@ got('todomvc.com')
//=> 'Internal server error ...'
});
// Stream mode
// Streams
got.stream('todomvc.com').pipe(fs.createWriteStream('index.html'));
// For POST, PUT and PATCH methods got.stream returns a WritableStream
@ -58,7 +53,9 @@ fs.createReadStream('index.html').pipe(got.stream.post('todomvc.com'));
It's a `GET` request by default, but can be changed in `options`.
#### got(url, [options], [callback])
#### got(url, [options])
Return a Promise, that resolves to `response` object with `body` property.
##### url
@ -125,23 +122,10 @@ Number of request retries when network errors happens. Delays between retries co
Option accepts `function` with `retry` and `error` arguments. Function must return delay in milliseconds (`0` return value cancels retry).
##### callback(error, data, response)
Function to be called when error or data are received. If omitted, a promise will be returned.
###### error
`Error` object with HTTP status code as `statusCode` property.
###### data
The data you requested.
###### response
#### Streams
The [response object](http://nodejs.org/api/http.html#http_http_incomingmessage).
When in stream mode, you can listen for events:
`stream` method will return Duplex stream with additional events:
##### .on('request', request)
@ -267,18 +251,6 @@ got('todomvc.com', {
```
## Node.js 0.10.x
It is a known issue with old good Node 0.10.x [`http.Agent`](https://nodejs.org/docs/v0.10.39/api/http.html#http_class_http_agent) and `agent.maxSockets`, which is set to `5`. This can cause low performance and in rare cases deadlocks. To avoid this you can set it manually:
```js
require('http').globalAgent.maxSockets = Infinity;
require('https').globalAgent.maxSockets = Infinity;
```
This should only ever be done if you have Node version 0.10.x and at the top-level app layer.
## Related
- [gh-got](https://github.com/sindresorhus/gh-got) - Convenience wrapper for interacting with the GitHub API

43
test/_server.js

@ -1,43 +0,0 @@
'use strict';
var http = require('http');
var https = require('https');
var pify = require('pify');
var getPort = require('get-port');
var Promise = require('pinkie-promise');
var host = exports.host = 'localhost';
exports.createServer = function () {
return getPort().then(function (port) {
var s = http.createServer(function (req, resp) {
s.emit(req.url, req, resp);
});
s.host = host;
s.port = port;
s.url = 'http://' + host + ':' + port;
s.protocol = 'http';
s.listen = pify(s.listen, Promise);
s.close = pify(s.close, Promise);
return s;
});
};
exports.createSSLServer = function (opts) {
return getPort().then(function (port) {
var s = https.createServer(opts, function (req, resp) {
s.emit(req.url, req, resp);
});
s.host = host;
s.port = port;
s.url = 'https://' + host + ':' + port;
s.protocol = 'https';
s.listen = pify(s.listen, Promise);
s.close = pify(s.close, Promise);
return s;
});
};

13
test/arguments.js

@ -1,10 +1,10 @@
import test from 'ava';
import got from '../';
import {createServer} from './_server';
import {createServer} from './helpers/server';
let s;
test.before('setup', async t => {
test.before('setup', async () => {
s = await createServer();
s.on('/', (req, res) => {
@ -36,13 +36,6 @@ test('options are optional', async t => {
t.is((await got(`${s.url}/test`)).body, '/test');
});
test('options are optional', t => {
got(`${s.url}/test`, function (err, data) {
t.is(data, '/test');
t.end();
});
});
test('accepts url.parse object as first argument', async t => {
t.is((await got({hostname: s.host, port: s.port, path: '/test'})).body, '/test');
});
@ -64,6 +57,6 @@ test('accepts url.parse object as first argument', async t => {
t.is((await got({hostname: s.host, port: s.port, path: '/test'})).body, '/test');
});
test.after('cleanup', async t => {
test.after('cleanup', async () => {
await s.close();
});

13
test/error.js

@ -1,10 +1,10 @@
import test from 'ava';
import got from '../';
import {createServer} from './_server';
import {createServer} from './helpers/server';
let s;
test.before('setup', async t => {
test.before('setup', async () => {
s = await createServer();
s.on('/', (req, res) => {
@ -43,13 +43,6 @@ test('dns message', async t => {
});
test('options.body error message', async t => {
try {
got(s.url, {body: () => {}}, () => {});
t.fail('Exception was not thrown');
} catch (err) {
t.regexTest(/options.body must be a ReadableStream, string, Buffer or plain Object/, err.message);
}
try {
await got(s.url, {body: () => {}});
t.fail('Exception was not thrown');
@ -58,6 +51,6 @@ test('options.body error message', async t => {
}
});
test.after('cleanup', async t => {
test.after('cleanup', async () => {
await s.close();
});

6
test/gzip.js

@ -1,13 +1,13 @@
import zlib from 'zlib';
import test from 'ava';
import got from '../';
import {createServer} from './_server';
import {createServer} from './helpers/server';
const testContent = 'Compressible response content.\n';
let s;
test.before('setup', async t => {
test.before('setup', async () => {
s = await createServer();
s.on('/', (req, res) => {
@ -56,6 +56,6 @@ test('do not break HEAD responses', async t => {
t.is((await got.head(s.url)).body, '');
});
test.after('cleanup', async t => {
test.after('cleanup', async () => {
await s.close();
});

8
test/headers.js

@ -1,10 +1,10 @@
import test from 'ava';
import got from '../';
import {createServer} from './_server';
import {createServer} from './helpers/server';
let s;
test.before('setup', async t => {
test.before('setup', async () => {
s = await createServer();
s.on('/', (req, res) => {
@ -29,7 +29,7 @@ test('accept header with json option', async t => {
let headers = (await got(s.url, {json: true})).body;
t.is(headers.accept, 'application/json');
headers = (await got(s.url, {headers: {'accept': ''}, json: true})).body;
headers = (await got(s.url, {headers: {accept: ''}, json: true})).body;
t.is(headers.accept, '');
});
@ -48,6 +48,6 @@ test('zero content-length', async t => {
t.is(headers['content-length'], '0');
});
test.after('cleanup', async t => {
test.after('cleanup', async () => {
await s.close();
});

14
test/helpers.js

@ -1,10 +1,10 @@
import test from 'ava';
import got from '../';
import {createServer} from './_server';
import {createServer} from './helpers/server';
let s;
test.before('setup', async t => {
test.before('setup', async () => {
s = await createServer();
s.on('/', (req, res) => {
@ -19,14 +19,6 @@ test.before('setup', async t => {
await s.listen(s.port);
});
test('callback mode', t => {
got.get(s.url, function (err, body) {
t.ifError(err);
t.is(body, 'ok');
t.end();
});
});
test('promise mode', async t => {
t.is((await got.get(s.url)).body, 'ok');
@ -45,6 +37,6 @@ test('promise mode', async t => {
}
});
test.after('cleanup', async t => {
test.after('cleanup', async () => {
await s.close();
});

38
test/helpers/server.js

@ -0,0 +1,38 @@
'use strict';
const http = require('http');
const https = require('https');
const pify = require('pify');
const getPort = require('get-port');
const host = exports.host = 'localhost';
exports.createServer = function () {
return getPort().then(port => {
const s = http.createServer((req, resp) => s.emit(req.url, req, resp));
s.host = host;
s.port = port;
s.url = `http://${host}:${port}`;
s.protocol = 'http';
s.listen = pify(s.listen, Promise);
s.close = pify(s.close, Promise);
return s;
});
};
exports.createSSLServer = function (opts) {
return getPort().then(port => {
const s = https.createServer(opts, (req, resp) => s.emit(req.url, req, resp));
s.host = host;
s.port = port;
s.url = `https://${host}:${port}`;
s.protocol = 'https';
s.listen = pify(s.listen, Promise);
s.close = pify(s.close, Promise);
return s;
});
};

6
test/http.js

@ -1,10 +1,10 @@
import test from 'ava';
import got from '../';
import {createServer} from './_server';
import {createServer} from './helpers/server';
let s;
test.before('setup', async t => {
test.before('setup', async () => {
s = await createServer();
s.on('/', (req, res) => {
@ -70,6 +70,6 @@ test('query option', async t => {
t.is((await got(s.url, {query: 'recent=true'})).body, 'recent');
});
test.after('cleanup', async t => {
test.after('cleanup', async () => {
await s.close();
});

6
test/https.js

@ -2,7 +2,7 @@ import test from 'ava';
import pem from 'pem';
import pify from 'pify';
import got from '../';
import {createSSLServer} from './_server';
import {createSSLServer} from './helpers/server';
let s;
let key;
@ -12,7 +12,7 @@ let caRootCert;
const pemP = pify(pem, Promise);
test.before('setup', async t => {
test.before('setup', async () => {
const caKeys = await pemP.createCertificate({days: 1, selfSigned: true});
caRootKey = caKeys.serviceKey;
@ -58,6 +58,6 @@ test('make request to https server with ca', async t => {
t.is(body, 'ok');
});
test.after('cleanup', async t => {
test.after('cleanup', async () => {
await s.close();
});

6
test/json.js

@ -1,10 +1,10 @@
import test from 'ava';
import got from '../';
import {createServer} from './_server';
import {createServer} from './helpers/server';
let s;
test.before('setup', async t => {
test.before('setup', async () => {
s = await createServer();
s.on('/', (req, res) => {
@ -73,6 +73,6 @@ test('catches errors on invalid non-200 responses', async t => {
}
});
test.after('cleanup', async t => {
test.after('cleanup', async () => {
await s.close();
});

8
test/post.js

@ -1,13 +1,11 @@
/**/
import test from 'ava';
import intoStream from 'into-stream';
import got from '../';
import {createServer} from './_server';
import {createServer} from './helpers/server';
let s;
test.before('setup', async t => {
test.before('setup', async () => {
s = await createServer();
s.on('/', (req, res) => {
@ -111,6 +109,6 @@ test('content-type header is not overriden when object in options.body', async t
t.is(body['content-type'], 'doge');
});
test.after('cleanup', async t => {
test.after('cleanup', async () => {
await s.close();
});

6
test/redirects.js

@ -1,10 +1,10 @@
import test from 'ava';
import got from '../';
import {createServer} from './_server';
import {createServer} from './helpers/server';
let s;
test.before('setup', async t => {
test.before('setup', async () => {
s = await createServer();
s.on('/', (req, res) => {
@ -78,6 +78,6 @@ test('redirect only GET and HEAD requests', async t => {
}
});
test.after('cleanup', async t => {
test.after('cleanup', async () => {
await s.close();
});

6
test/retry.js

@ -1,13 +1,13 @@
import test from 'ava';
import got from '../';
import {createServer} from './_server';
import {createServer} from './helpers/server';
let s;
let trys = 0;
let knocks = 0;
let fifth = 0;
test.before('setup', async t => {
test.before('setup', async () => {
s = await createServer();
s.on('/long', () => {});
@ -69,6 +69,6 @@ test('falsy value prevent retries', async t => {
}
});
test.after('cleanup', async t => {
test.after('cleanup', async () => {
await s.close();
});

42
test/stream.js

@ -1,11 +1,11 @@
import test from 'ava';
import got from '../';
import intoStream from 'into-stream';
import {createServer} from './_server';
import {createServer} from './helpers/server';
let s;
test.before('setup', async t => {
test.before('setup', async () => {
s = await createServer();
s.on('/', (req, res) => {
@ -35,22 +35,9 @@ test('option.json can not be used', t => {
t.throws(() => {
got.stream(s.url, {json: true});
}, 'got can not be used as stream when options.json is used');
t.end();
});
test('callback can not be used', t => {
t.throws(() => {
got.stream(s.url, {json: true}, () => {});
}, 'callback can not be used with stream mode');
t.throws(() => {
got.stream(s.url, () => {});
}, 'callback can not be used with stream mode');
t.end();
});
test('returns readable stream', t => {
test.cb('returns readable stream', t => {
got.stream(s.url)
.on('data', data => {
t.is(data.toString(), 'ok');
@ -58,25 +45,25 @@ test('returns readable stream', t => {
});
});
test('returns writeable stream', t => {
t.plan(1);
test.cb('returns writeable stream', t => {
got.stream.post(`${s.url}/post`)
.on('data', data => {
t.is(data.toString(), 'wow');
t.end();
})
.end('wow');
});
test('throws on write to stream with body specified', t => {
test.cb('throws on write to stream with body specified', t => {
t.throws(() => {
got.stream(s.url, {body: 'wow'}).write('wow');
}, 'got\'s stream is not writable when options.body is used');
// wait for request to end
setTimeout(t.end.bind(t), 10);
setTimeout(t.end, 10);
});
test('have request event', t => {
test.cb('have request event', t => {
got.stream(s.url)
.on('request', req => {
t.ok(req);
@ -84,7 +71,7 @@ test('have request event', t => {
});
});
test('have redirect event', t => {
test.cb('have redirect event', t => {
got.stream(`${s.url}/redirect`)
.on('redirect', res => {
t.is(res.headers.location, s.url);
@ -92,7 +79,7 @@ test('have redirect event', t => {
});
});
test('have response event', t => {
test.cb('have response event', t => {
got.stream(s.url)
.on('response', res => {
t.is(res.statusCode, 200);
@ -100,7 +87,7 @@ test('have response event', t => {
});
});
test('have error event', t => {
test.cb('have error event', t => {
got.stream(`${s.url}/error`, {retries: 0})
.on('response', () => {
t.fail('response event should not be emitted');
@ -113,7 +100,7 @@ test('have error event', t => {
});
});
test('have error event', t => {
test.cb('have error event', t => {
got.stream('.com', {retries: 0})
.on('response', () => {
t.fail('response event should not be emitted');
@ -124,15 +111,14 @@ test('have error event', t => {
});
});
test('accepts option.body as Stream', t => {
test.cb('accepts option.body as Stream', t => {
got.stream(`${s.url}/post`, {body: intoStream(['wow'])})
.on('data', chunk => {
t.is(chunk.toString(), 'wow');
t.end();
});
});
test.after('cleanup', async t => {
test.after('cleanup', async () => {
await s.close();
});

6
test/unix-socket.js

@ -2,13 +2,13 @@ import {format} from 'util';
import tempfile from 'tempfile';
import test from 'ava';
import got from '../';
import {createServer} from './_server';
import {createServer} from './helpers/server';
const socketPath = tempfile('.socket');
let s;
test.before('setup', async t => {
test.before('setup', async () => {
s = await createServer();
s.on('/', (req, res) => {
@ -28,6 +28,6 @@ test('protocol-less works', async t => {
t.is((await got(url)).body, 'ok');
});
test.after('cleanup', async t => {
test.after('cleanup', async () => {
await s.close();
});

Loading…
Cancel
Save