[Pkg-javascript-commits] [node-superagent] 02/07: Imported Upstream version 0.20.0+dfsg
Leo Iannacone
l3on-guest at moszumanska.debian.org
Sun Oct 12 13:00:28 UTC 2014
This is an automated email from the git hooks/post-receive script.
l3on-guest pushed a commit to branch master
in repository node-superagent.
commit d2b93c33c9116b27354cf0daf88f7b6efe71326f
Author: Leo Iannacone <l3on at ubuntu.com>
Date: Sun Oct 12 14:38:39 2014 +0200
Imported Upstream version 0.20.0+dfsg
---
.travis.yml | 1 -
History.md | 39 ++++++++
component.json | 2 +-
docs/head.html | 39 --------
docs/index.md | 219 --------------------------------------------
docs/tail.html | 2 -
lib/client.js | 35 ++++++-
lib/node/agent.js | 2 +-
lib/node/index.js | 111 +++++++++++++++++++---
lib/node/parsers/image.js | 10 ++
lib/node/parsers/index.js | 1 +
lib/node/response.js | 27 +++++-
package.json | 18 ++--
test/node/basic-auth.js | 12 ++-
test/node/basic.js | 62 +++++++++++++
test/node/exports.js | 6 +-
test/node/fixtures/test.png | Bin 0 -> 159 bytes
test/node/form.js | 2 +-
test/node/image.js | 34 +++++++
test/node/json.js | 13 +++
test/node/parsers.js | 51 ++++++++++-
test/node/query.js | 2 +-
test/node/toError.js | 1 +
23 files changed, 383 insertions(+), 306 deletions(-)
diff --git a/.travis.yml b/.travis.yml
index 4a83e22..18ae2d8 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -2,4 +2,3 @@ language: node_js
node_js:
- "0.11"
- "0.10"
- - "0.8"
diff --git a/History.md b/History.md
index ef2fd18..38c93c4 100644
--- a/History.md
+++ b/History.md
@@ -1,3 +1,42 @@
+0.20.0 / 2014-10-02
+==================
+
+ * Add toJSON() to request and response instances. (yields)
+ * Prevent HEAD requests from getting parsed. (gjohnson)
+ * Update debug. (TooTallNate)
+
+0.19.1 / 2014-09-24
+==================
+
+ * Fix basic auth issue when password is falsey value. (gjohnson)
+
+0.19.0 / 2014-09-24
+==================
+
+ * Add unset() to browser. (shesek)
+ * Prefer XHR over ActiveX. (omeid)
+ * Catch parse errors. (jacwright)
+ * Update qs dependency. (wercker)
+ * Add use() to node. (Financial-Times)
+ * Add response text to errors. (yields)
+ * Don't send empty cookie headers. (undoZen)
+ * Don't parse empty response bodies. (DveMac)
+ * Use hostname when setting cookie host. (prasunsultania)
+
+0.18.2 / 2014-07-12
+==================
+
+ * Handle parser errors. (kof)
+ * Ensure not to use default parsers when there is a user defined one. (kof)
+
+0.18.1 / 2014-07-05
+==================
+
+ * Upgrade cookiejar dependency (juanpin)
+ * Support image mime types (nebulade)
+ * Make .agent chainable (kof)
+ * Upgrade debug (TooTallNate)
+ * Fix docs (aheckmann)
0.18.0 / 2014-04-29
===================
diff --git a/component.json b/component.json
index e73ac67..e292599 100644
--- a/component.json
+++ b/component.json
@@ -2,7 +2,7 @@
"name": "superagent",
"repo": "visionmedia/superagent",
"description": "awesome http requests",
- "version": "0.18.0",
+ "version": "0.19.0",
"keywords": [
"http",
"ajax",
diff --git a/docs/head.html b/docs/head.html
deleted file mode 100644
index f16f0d4..0000000
--- a/docs/head.html
+++ /dev/null
@@ -1,39 +0,0 @@
-<!DOCTYPE html>
-<html>
- <head>
- <title>Superagent</title>
- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
- <style>
- body {
- font: 16px/1.6 "Helvetica Neue", arial, sans-serif;
- padding: 60px;
- }
- pre { font-size: 14px; line-height: 1.3 }
- code .init { color: #2F6FAD }
- code .string { color: #5890AD }
- code .keyword { color: #8A6343 }
- code .number { color: #2F6FAD }
- </style>
- <script>
- $(function(){
- $('code').each(function(){
- $(this).html(highlight($(this).text()));
- });
- });
-
- function highlight(js) {
- return js
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>')
- .replace(/('.*')/gm, '<span class="string">$1</span>')
- .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>')
- .replace(/(\d+)/gm, '<span class="number">$1</span>')
- .replace(/\bnew *(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>')
- .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>')
- }
- </script>
- </head>
- <body>
- <h1>Superagent</h1>
- <p>The superagent test suite.</p>
diff --git a/docs/index.md b/docs/index.md
deleted file mode 100644
index 486e5e2..0000000
--- a/docs/index.md
+++ /dev/null
@@ -1,219 +0,0 @@
-# SuperAgent
-
- Super Agent is light-weight progressive ajax API crafted for flexibility, readability, and a low learning curve after being frustrated with many of the existing request APIs.
-
- request
- .post('/api/pet')
- .data({ name: 'Manny', species: 'cat' })
- .set('X-API-Key', 'foobar')
- .set('Accept', 'application/json')
- .end(function(res){
- if (res.ok) {
- alert('yay got ' + JSON.stringify(res.body));
- } else {
- alert('Oh no! error ' + res.text);
- }
- });
-
-## Request basics
-
- A request can be initiated by invoking the appropriate method on the `request` object, then calling `.end()` to send the request. For example a simple GET request:
-
- request
- .get('/search')
- .end(function(res){
-
- });
-
- The __node__ client may also provide absolute urls:
-
- request
- .get('http://example.com/search')
- .end(function(res){
-
- });
-
- __DELETE__, __HEAD__, __POST__, __PUT__ and other __HTTP__ verbs may also be used, simply change the method name:
-
- request
- .head('/favicon.ico')
- .end(function(res){
-
- });
-
- __DELETE__ is a special-case, as it's a reserved word, so the method is named `.del()`:
-
- request
- .del('/user/1')
- .end(function(res){
-
- });
-
-### Crafting requests
-
- SuperAgent's flexible API gives you the granularity you need, _when_ you need, yet more concise variations help reduce the amount of code necessary. For example the following GET request:
-
- request
- .get('/search')
- .end(function(res){
-
- });
-
- Could also be defined as the following, where a callback is given to the HTTP verb method:
-
- request
- .get('/search', function(res){
-
- });
-
- Taking this further the default HTTP verb is __GET__ so the following works as well:
-
- request('/search', function(res){
-
- });
-
- This applies to more complicated requests as well, for example the following __GET__ request with a query-string can be written in the chaining manner:
-
- request
- .get('/search')
- .data({ query: 'tobi the ferret' })
- .end(function(res){
-
- });
-
- Or one may pass the query-string object to `.get()`:
-
- request
- .get('/search', { query: 'tobi the ferret' })
- .end(function(res){
-
- });
-
- Taking this even further the callback may be passed as well:
-
- request
- .get('/search', { query: 'tobi the ferret' }, function(res){
-
- });
-
-## Dealing with errors
-
- On a network error (e.g. connection refused or timeout), SuperAgent emits
- `error` unless you pass `.end()` a callback with two parameters. Then
- SuperAgent will invoke it with the error first, followed by a null response.
-
- request
- .get('http://wrongurl')
- .end(function(err, res){
- console.log('ERROR: ', err)
- });
-
- On HTTP errors instead, SuperAgent populates the response with flags
- indicating the error. See `Response status` below.
-
-## Setting header fields
-
- Setting header fields is simple, invoke `.set()` with a field name and value:
-
- request
- .get('/search')
- .set('API-Key', 'foobar')
- .set('Accept', 'application/json')
- .end(callback);
-
-## GET requests
-
- The `.data()` method accepts objects, which when used with the __GET__ method will form a query-string. The following will produce the path `/search?query=Manny&range=1..5&order=desc`.
-
- request
- .get('/search')
- .data({ query: 'Manny' })
- .data({ range: '1..5' })
- .data({ order: 'desc' })
- .end(function(res){
-
- });
-
- The `.data()` method accepts strings as well:
-
- request
- .get('/querystring')
- .data('search=Manny&range=1..5')
- .end(function(res){
-
- });
-
-### POST / PUT requests
-
- A typical JSON __POST__ request might look a little like the following, where we set the Content-Type header field appropriately, and "write" some data, in this case just a JSON string.
-
- request.post('/user')
- .set('Content-Type', 'application/json')
- .data('{"name":"tj","pet":"tobi"})
- .end(callback)
-
- Since JSON is undoubtably the most common, it's the _default_! The following example is equivalent to the previous.
-
- request.post('/user')
- .data({ name: 'tj', pet: 'tobi' })
- .end(callback)
-
- Or using multiple `.data()` calls:
-
- request.post('/user')
- .data({ name: 'tj' })
- .data({ pet: 'tobi' })
- .end(callback)
-
- SuperAgent formats are extensible, however by default "json" and "form" are supported. To send the data as `application/x-www-form-urlencoded` simply invoke `.type()` with "form-data", where the default is "json". This request will POST the body "name=tj&pet=tobi".
-
- request.post('/user')
- .type('form')
- .data({ name: 'tj' })
- .data({ pet: 'tobi' })
- .end(callback)
-
-## Response properties
-
- Many helpful flags and properties are set on the `Response` object, ranging from the response text, parsed response body, header fields, status flags and more.
-
-### Response text
-
- The `res.text` property contains the unparsed response body string.
-
-### Response body
-
- Much like SuperAgent can auto-serialize request data, it can also automatically parse it. When a parser is defined for the Content-Type, it is parsed, which by default includes "application/json" and "application/x-www-form-urlencoded". The parsed object is then available via `res.body`.
-
-### Response header fields
-
- The `res.header` contains an object of parsed header fields, lowercasing field names much like node does. For example `res.header['content-length']`.
-
-### Response Content-Type
-
- The Content-Type response header is special-cased, providing `res.contentType`, which is void of the charset (if any). For example the Content-Type of "text/html; charset=utf8" will provide "text/html" as `res.contentType`, and the `res.charset` property would then contain "utf8".
-
-### Response status
-
- The response status flags help determine if the request was a success, among other useful information, making SuperAgent ideal for interacting with RESTful web services. These flags are currently defined as:
-
- var type = status / 100 | 0;
-
- // status / class
- res.status = status;
- res.statusType = type;
-
- // basics
- res.info = 1 == type;
- res.ok = 2 == type;
- res.clientError = 4 == type;
- res.serverError = 5 == type;
- res.error = 4 == type || 5 == type;
-
- // sugar
- res.accepted = 202 == status;
- res.noContent = 204 == status || 1223 == status;
- res.badRequest = 400 == status;
- res.unauthorized = 401 == status;
- res.notAcceptable = 406 == status;
- res.notFound = 404 == status;
diff --git a/docs/tail.html b/docs/tail.html
deleted file mode 100644
index 1fd5f4f..0000000
--- a/docs/tail.html
+++ /dev/null
@@ -1,2 +0,0 @@
- </body>
-</html>
\ No newline at end of file
diff --git a/lib/client.js b/lib/client.js
index 5051d9b..2443f42 100644
--- a/lib/client.js
+++ b/lib/client.js
@@ -354,7 +354,7 @@ Response.prototype.setHeaderProperties = function(header){
Response.prototype.parseBody = function(str){
var parse = request.parse[this.type];
- return parse
+ return parse && str && str.length
? parse(str)
: null;
};
@@ -450,9 +450,16 @@ function Request(method, url) {
this.header = {};
this._header = {};
this.on('end', function(){
- var res = new Response(self);
- if ('HEAD' == method) res.text = null;
- self.callback(null, res);
+ try {
+ var res = new Response(self);
+ if ('HEAD' == method) res.text = null;
+ self.callback(null, res);
+ } catch(e) {
+ var err = new Error('Parser is unable to parse the response');
+ err.parse = true;
+ err.original = e;
+ self.callback(err);
+ }
});
}
@@ -546,6 +553,26 @@ Request.prototype.set = function(field, val){
};
/**
+ * Remove header `field`.
+ *
+ * Example:
+ *
+ * req.get('/')
+ * .unset('User-Agent')
+ * .end(callback);
+ *
+ * @param {String} field
+ * @return {Request} for chaining
+ * @api public
+ */
+
+Request.prototype.unset = function(field){
+ delete this._header[field.toLowerCase()];
+ delete this.header[field];
+ return this;
+};
+
+/**
* Get case-insensitive header `field` value.
*
* @param {String} field
diff --git a/lib/node/agent.js b/lib/node/agent.js
index 9ae2f1d..92afd74 100644
--- a/lib/node/agent.js
+++ b/lib/node/agent.js
@@ -49,7 +49,7 @@ Agent.prototype.saveCookies = function(res){
Agent.prototype.attachCookies = function(req){
var url = parse(req.url);
- var access = CookieAccess(url.host, url.pathname, 'https:' == url.protocol);
+ var access = CookieAccess(url.hostname, url.pathname, 'https:' == url.protocol);
var cookies = this.jar.getCookies(access).toValueString();
req.cookies = cookies;
};
diff --git a/lib/node/index.js b/lib/node/index.js
index a9351c7..34d662f 100644
--- a/lib/node/index.js
+++ b/lib/node/index.js
@@ -238,8 +238,9 @@ Request.prototype.part = util.deprecate(function(){
*/
Request.prototype.agent = function(agent){
- if (agent) this._agent = agent;
- return this._agent;
+ if (!arguments.length) return this._agent;
+ this._agent = agent;
+ return this;
};
/**
@@ -558,6 +559,7 @@ Request.prototype.abort = function(){
this._aborted = true;
this.clearTimeout();
this.req.abort();
+ this.emit('abort');
};
/**
@@ -621,6 +623,12 @@ Request.prototype.redirect = function(res){
/**
* Set Authorization field value with `user` and `pass`.
*
+ * Examples:
+ *
+ * .auth('tobi', 'learnboost')
+ * .auth('tobi:learnboost')
+ * .auth('tobi')
+ *
* @param {String} user
* @param {String} pass
* @return {Request} for chaining
@@ -628,8 +636,9 @@ Request.prototype.redirect = function(res){
*/
Request.prototype.auth = function(user, pass){
- if (pass) pass = ':' + pass;
- var str = new Buffer(user + (pass || '')).toString('base64');
+ if (1 === arguments.length) pass = '';
+ if (!~user.indexOf(':')) user = user + ':';
+ var str = new Buffer(user + pass).toString('base64');
return this.set('Authorization', 'Basic ' + str);
};
@@ -647,6 +656,15 @@ Request.prototype.ca = function(cert){
};
/**
+ * Allow for extension
+ */
+
+Request.prototype.use = function(fn) {
+ fn(this);
+ return this;
+};
+
+/**
* Return an http[s] request.
*
* @return {OutgoingMessage}
@@ -703,7 +721,7 @@ Request.prototype.request = function(){
this.query(url.query);
// add cookies
- req.setHeader('Cookie', this.cookies);
+ if (this.cookies) req.setHeader('Cookie', this.cookies);
// set default UA
req.setHeader('User-Agent', 'node-superagent/' + pkg.version);
@@ -800,6 +818,18 @@ Request.prototype.end = function(fn){
var type = type[0];
var multipart = 'multipart' == type;
var redirect = isRedirect(res.statusCode);
+ var parser = self._parser;
+
+ self.res = res;
+
+ if ('HEAD' == self.method) {
+ var response = new Response(self);
+ self.response = response;
+ response.redirects = self._redirectList;
+ self.emit('response', response);
+ self.emit('end');
+ return;
+ }
if (self.piped) {
res.on('end', function(){
@@ -822,12 +852,13 @@ Request.prototype.end = function(fn){
if (multipart) buffer = false;
// TODO: make all parsers take callbacks
- if (multipart) {
+ if (!parser && multipart) {
var form = new formidable.IncomingForm;
form.parse(res, function(err, fields, files){
if (err) return self.callback(err);
- var response = new Response(req, res);
+ var response = new Response(self);
+ self.response = response;
response.body = fields;
response.files = files;
response.redirects = self._redirectList;
@@ -837,6 +868,20 @@ Request.prototype.end = function(fn){
return;
}
+ // check for images, one more special treatment
+ if (!parser && isImage(mime)) {
+ exports.parse.image(res, function(err, obj){
+ if (err) return self.callback(err);
+ var response = new Response(self);
+ self.response = response;
+ response.body = obj;
+ response.redirects = self._redirectList;
+ self.emit('end');
+ self.callback(null, response);
+ });
+ return;
+ }
+
// by default only buffer text/*, json
// and messed up thing from hell
var text = isText(mime);
@@ -851,21 +896,27 @@ Request.prototype.end = function(fn){
if (buffer) parse = parse || exports.parse.text;
// explicit parser
- if (self._parser) parse = self._parser;
+ if (parser) parse = parser;
// parse
if (parse) {
- parse(res, function(err, obj){
- // TODO: handle error
- res.body = obj;
- });
+ try {
+ parse(res, function(err, obj){
+ if (err) self.callback(err);
+ res.body = obj;
+ });
+ } catch(err) {
+ self.callback(err);
+ return;
+ }
}
// unbuffered
if (!buffer) {
debug('unbuffered %s %s', self.method, self.url);
self.res = res;
- var response = new Response(self.req, self.res);
+ var response = new Response(self);
+ self.response = response;
response.redirects = self._redirectList;
self.emit('response', response);
if (multipart) return // allow multipart to handle end event
@@ -881,7 +932,8 @@ Request.prototype.end = function(fn){
res.on('end', function(){
debug('end %s %s', self.method, self.url);
// TODO: unless buffering emit earlier to stream
- var response = new Response(self.req, self.res);
+ var response = new Response(self);
+ self.response = response;
response.redirects = self._redirectList;
self.emit('response', response);
self.emit('end');
@@ -920,6 +972,21 @@ Request.prototype.end = function(fn){
};
/**
+ * To json.
+ *
+ * @return {Object}
+ * @api public
+ */
+
+Request.prototype.toJSON = function(){
+ return {
+ method: this.method,
+ url: this.url,
+ data: this._data
+ };
+};
+
+/**
* Expose `Request`.
*/
@@ -985,6 +1052,22 @@ function isText(mime) {
}
/**
+ * Check if `mime` is image
+ *
+ * @param {String} mime
+ * @return {Boolean}
+ * @api public
+ */
+
+function isImage(mime) {
+ var parts = mime.split('/');
+ var type = parts[0];
+ var subtype = parts[1];
+
+ return 'image' == type;
+}
+
+/**
* Check if we should follow the redirect `code`.
*
* @param {Number} code
diff --git a/lib/node/parsers/image.js b/lib/node/parsers/image.js
new file mode 100644
index 0000000..b3e0ebc
--- /dev/null
+++ b/lib/node/parsers/image.js
@@ -0,0 +1,10 @@
+module.exports = function(res, fn){
+ var data = []; // Binary data needs binary storage
+
+ res.on('data', function(chunk){
+ data.push(chunk);
+ });
+ res.on('end', function () {
+ fn(null, Buffer.concat(data));
+ });
+};
\ No newline at end of file
diff --git a/lib/node/parsers/index.js b/lib/node/parsers/index.js
index b47550e..61a98cd 100644
--- a/lib/node/parsers/index.js
+++ b/lib/node/parsers/index.js
@@ -2,3 +2,4 @@
exports['application/x-www-form-urlencoded'] = require('./urlencoded');
exports['application/json'] = require('./json');
exports.text = require('./text');
+exports.image = require('./image');
diff --git a/lib/node/response.js b/lib/node/response.js
index 291ef67..21615e6 100644
--- a/lib/node/response.js
+++ b/lib/node/response.js
@@ -19,8 +19,7 @@ module.exports = Response;
* - set flags (.ok, .error, etc)
* - parse header
*
- * @param {ClientRequest} req
- * @param {IncomingMessage} res
+ * @param {Request} req
* @param {Object} options
* @constructor
* @extends {Stream}
@@ -28,11 +27,12 @@ module.exports = Response;
* @api private
*/
-function Response(req, res, options) {
+function Response(req, options) {
Stream.call(this);
options = options || {};
- this.req = req;
- this.res = res;
+ var res = this.res = req.res;
+ this.request = req;
+ this.req = req.req;
this.links = {};
this.text = res.text;
this.body = res.body || {};
@@ -105,6 +105,7 @@ Response.prototype.toError = function(){
var msg = 'cannot ' + method + ' ' + path + ' (' + this.status + ')';
var err = new Error(msg);
err.status = this.status;
+ err.text = this.text;
err.method = method;
err.path = path;
@@ -201,3 +202,19 @@ Response.prototype.setStatusProperties = function(status){
this.forbidden = 403 == status;
this.notFound = 404 == status;
};
+
+/**
+ * To json.
+ *
+ * @return {Object}
+ * @api public
+ */
+
+Response.prototype.toJSON = function(){
+ return {
+ req: this.request.toJSON(),
+ header: this.header,
+ status: this.status,
+ text: this.text
+ };
+};
diff --git a/package.json b/package.json
index 527057e..437e8c2 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "superagent",
- "version": "0.18.0",
+ "version": "0.20.0",
"description": "elegant & feature rich browser / node HTTP with a fluent API",
"scripts": {
"test": "make test"
@@ -20,22 +20,22 @@
"url": "git://github.com/visionmedia/superagent.git"
},
"dependencies": {
- "qs": "0.6.6",
+ "qs": "1.2.0",
"formidable": "1.0.14",
- "mime": "1.2.5",
+ "mime": "1.2.11",
"component-emitter": "1.1.2",
- "methods": "0.0.1",
- "cookiejar": "1.3.2",
- "debug": "~0.7.2",
+ "methods": "1.0.1",
+ "cookiejar": "2.0.1",
+ "debug": "~2.0.0",
"reduce-component": "1.0.1",
"extend": "~1.2.1",
- "form-data": "0.1.2",
+ "form-data": "0.1.3",
"readable-stream": "1.0.27-1"
},
"devDependencies": {
"zuul": "~1.6.0",
"express": "3.5.0",
- "better-assert": "~0.1.0",
+ "better-assert": "~1.0.1",
"should": "3.1.3",
"mocha": "*"
},
@@ -51,6 +51,6 @@
},
"main": "./lib/node/index.js",
"engines": {
- "node": "*"
+ "node": ">= 0.8"
}
}
diff --git a/test/node/basic-auth.js b/test/node/basic-auth.js
index 818559e..751da21 100644
--- a/test/node/basic-auth.js
+++ b/test/node/basic-auth.js
@@ -5,12 +5,14 @@ var EventEmitter = require('events').EventEmitter
, assert = require('assert')
, app = express();
-app.use(express.basicAuth('tobi', 'learnboost'));
-
-app.get('/', function(req, res){
+app.get('/', express.basicAuth('tobi', 'learnboost'), function(req, res){
res.end('you win!');
});
+app.get('/again', express.basicAuth('tobi', ''), function(req, res){
+ res.end('you win again!');
+});
+
app.listen(3010);
describe('Basic auth', function(){
@@ -40,8 +42,8 @@ describe('Basic auth', function(){
describe('req.auth(user + ":" + pass)', function(){
it('should set authorization', function(done){
request
- .get('http://localhost:3010')
- .auth('tobi:learnboost')
+ .get('http://localhost:3010/again')
+ .auth('tobi')
.end(function(res){
res.status.should.eql(200);
done();
diff --git a/test/node/basic.js b/test/node/basic.js
index 1129ef7..41c160a 100644
--- a/test/node/basic.js
+++ b/test/node/basic.js
@@ -100,6 +100,37 @@ describe('request', function(){
})
})
+ describe('req.toJSON()', function(){
+ it('should describe the request', function(done){
+ request
+ .post(':5000/echo')
+ .send({ foo: 'baz' })
+ .end(function(res){
+ var obj = res.request.toJSON();
+ assert('POST' == obj.method);
+ assert(':5000/echo' == obj.url);
+ assert('baz' == obj.data.foo);
+ done();
+ });
+ })
+ })
+
+ describe('res.toJSON()', function(){
+ it('should describe the response', function(done){
+ request
+ .post(':5000/echo')
+ .send({ foo: 'baz' })
+ .end(function(res){
+ var obj = res.toJSON();
+ assert('object' == typeof obj.header);
+ assert('object' == typeof obj.req);
+ assert(200 == obj.status);
+ assert('{"foo":"baz"}' == obj.text);
+ done();
+ });
+ });
+ })
+
describe('res.error', function(){
it('should should be an Error object', function(done){
request
@@ -232,6 +263,7 @@ describe('request', function(){
request
.post('http://localhost:5000/echo')
.type('json')
+ .send('{"a": 1}')
.end(function(res){
res.should.be.json;
done();
@@ -426,6 +458,36 @@ describe('request', function(){
})
})
+ describe('.agent()', function(){
+ it('should return the defaut agent', function(done){
+ var req = request.post('http://localhost:5000/echo');
+ req.agent().should.equal(false);
+ done();
+ })
+ })
+
+ describe('.agent(undefined)', function(){
+ it('should set an agent to undefined and ensure it is chainable', function(done){
+ var req = request.get();
+ var ret = req.agent(undefined);
+ ret.should.equal(req);
+ assert(req.agent() === undefined);
+ done();
+ })
+ })
+
+ describe('.agent(new http.Agent())', function(){
+ it('should set passed agent', function(done){
+ var http = require('http');
+ var req = request.get();
+ var agent = new http.Agent();
+ var ret = req.agent(agent);
+ ret.should.equal(req);
+ req.agent().should.equal(agent)
+ done();
+ })
+ })
+
describe('with a content type other than application/json or text/*', function(){
it('should disable buffering', function(done){
request
diff --git a/test/node/exports.js b/test/node/exports.js
index 5038947..d25e45e 100644
--- a/test/node/exports.js
+++ b/test/node/exports.js
@@ -5,7 +5,7 @@ describe('exports', function(){
it('should expose Part', function(){
request.Part.should.be.a.function;
})
-
+
it('should expose .protocols', function(){
Object.keys(request.protocols)
.should.eql(['http:', 'https:']);
@@ -15,9 +15,9 @@ describe('exports', function(){
Object.keys(request.serialize)
.should.eql(['application/x-www-form-urlencoded', 'application/json']);
})
-
+
it('should expose .parse', function(){
Object.keys(request.parse)
- .should.eql(['application/x-www-form-urlencoded', 'application/json', 'text']);
+ .should.eql(['application/x-www-form-urlencoded', 'application/json', 'text', 'image']);
})
})
diff --git a/test/node/fixtures/test.png b/test/node/fixtures/test.png
new file mode 100644
index 0000000..7d2fe61
Binary files /dev/null and b/test/node/fixtures/test.png differ
diff --git a/test/node/form.js b/test/node/form.js
index c6d8ae9..ed9b57d 100644
--- a/test/node/form.js
+++ b/test/node/form.js
@@ -40,7 +40,7 @@ describe('req.send(Object) as "form"', function(){
.send({ age: '1' })
.end(function(res){
res.header['content-type'].should.equal('application/x-www-form-urlencoded');
- res.text.should.equal('name[first]=tobi&name[last]=holowaychuk&age=1');
+ res.text.should.equal('name%5Bfirst%5D=tobi&name%5Blast%5D=holowaychuk&age=1');
done();
});
})
diff --git a/test/node/image.js b/test/node/image.js
new file mode 100644
index 0000000..3a131c8
--- /dev/null
+++ b/test/node/image.js
@@ -0,0 +1,34 @@
+/* jshint indent: 2 */
+/* jshint laxcomma: true */
+
+var EventEmitter = require('events').EventEmitter
+ , fs = require('fs')
+ , request = require('../../')
+ , express = require('express')
+ , assert = require('assert')
+ , app = express();
+
+
+describe('res.body', function(){
+ 'use strict';
+
+ var img = fs.readFileSync(__dirname + '/fixtures/test.png');
+
+ app.get('/image', function(req, res){
+ res.writeHead(200, {'Content-Type': 'image/png' });
+ res.end(img, 'binary');
+ });
+
+ app.listen(3011);
+
+ describe('image/png', function(){
+ it('should parse the body', function(done){
+ request
+ .get('http://localhost:3011/image')
+ .end(function(res){
+ (res.body.length - img.length).should.equal(0);
+ done();
+ });
+ });
+ });
+});
diff --git a/test/node/json.js b/test/node/json.js
index ff03cba..695149f 100644
--- a/test/node/json.js
+++ b/test/node/json.js
@@ -77,4 +77,17 @@ describe('res.body', function(){
});
})
})
+
+ describe('HEAD requests', function(){
+ it('should not throw a parse error', function(done){
+ request
+ .head('http://localhost:3005/json')
+ .end(function(err, res){
+ assert(err === null);
+ assert(res.text === undefined)
+ assert(Object.keys(res.body).length === 0)
+ done();
+ });
+ });
+ });
})
diff --git a/test/node/parsers.js b/test/node/parsers.js
index c3855a0..b85c305 100644
--- a/test/node/parsers.js
+++ b/test/node/parsers.js
@@ -2,12 +2,21 @@
var request = require('../..')
, express = require('express')
, assert = require('better-assert')
+ , fs = require('fs')
, app = express();
app.get('/manny', function(req, res){
res.send('{"name":"manny"}');
});
+
+var img = fs.readFileSync(__dirname + '/fixtures/test.png');
+
+app.get('/image', function(req, res){
+ res.writeHead(200, {'Content-Type': 'image/png' });
+ res.end(img, 'binary');
+});
+
app.listen(3033);
describe('req.parse(fn)', function(){
@@ -22,4 +31,44 @@ describe('req.parse(fn)', function(){
done();
});
})
-})
\ No newline at end of file
+
+ it('should be the only parser', function(done){
+ request
+ .get('http://localhost:3033/image')
+ .parse(function(res, fn) {
+ res.on('data', function() {});
+ })
+ .end(function(res){
+ assert(res.ok);
+ assert(res.text === undefined);
+ res.body.should.eql({});
+ done();
+ });
+ })
+
+ it('should emit error if parser throws', function(done){
+ request
+ .get('http://localhost:3033/manny')
+ .parse(function() {
+ throw new Error('I am broken');
+ })
+ .on('error', function(err) {
+ err.message.should.equal('I am broken');
+ done();
+ })
+ .end();
+ })
+
+ it('should emit error if parser returns an error', function(done){
+ request
+ .get('http://localhost:3033/manny')
+ .parse(function(res, fn) {
+ fn(new Error('I am broken'));
+ })
+ .on('error', function(err) {
+ err.message.should.equal('I am broken');
+ done();
+ })
+ .end()
+ })
+})
diff --git a/test/node/query.js b/test/node/query.js
index 4c74467..40bdd62 100644
--- a/test/node/query.js
+++ b/test/node/query.js
@@ -111,7 +111,7 @@ describe('req.query(Object)', function(){
.del('http://localhost:3006/')
.query({ at: date })
.end(function(res){
- assert(String(date) == res.body.at);
+ assert(date.toISOString() == res.body.at);
done();
});
})
diff --git a/test/node/toError.js b/test/node/toError.js
index d6988a5..6647d33 100644
--- a/test/node/toError.js
+++ b/test/node/toError.js
@@ -21,6 +21,7 @@ describe('res.toError()', function(){
assert(err.method == 'GET');
assert(err.path == '/');
assert(err.message == 'cannot GET / (400)');
+ assert(err.text == 'invalid json');
done();
});
})
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/node-superagent.git
More information about the Pkg-javascript-commits
mailing list