[Pkg-javascript-commits] [node-mocks-http] 01/296: Initial checkin

Thorsten Alteholz alteholz at moszumanska.debian.org
Mon Feb 8 18:13:15 UTC 2016


This is an automated email from the git hooks/post-receive script.

alteholz pushed a commit to branch master
in repository node-mocks-http.

commit dc8c57616b17f22718a3e8318d0e1af9f80ec2b8
Author: Howard Abrams <howard at howardabrams.com>
Date:   Fri Feb 17 23:17:03 2012 -0800

    Initial checkin
---
 .project                                           |  17 ++
 .settings/.jsdtscope                               |   7 +
 .../org.eclipse.wst.jsdt.ui.superType.container    |   1 +
 .settings/org.eclipse.wst.jsdt.ui.superType.name   |   1 +
 examples/express-route.js                          |  49 ++++
 lib/http-mock.js                                   |  12 +
 lib/mockRequest.js                                 | 137 +++++++++++
 lib/mockResponse.js                                | 254 +++++++++++++++++++++
 package.json                                       |  26 +++
 test/test-mockRequest.js                           | 100 ++++++++
 test/test-mockResponse.js                          | 121 ++++++++++
 11 files changed, 725 insertions(+)

diff --git a/.project b/.project
new file mode 100644
index 0000000..9d8f7bd
--- /dev/null
+++ b/.project
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>node-mocks-http</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
+	</natures>
+</projectDescription>
diff --git a/.settings/.jsdtscope b/.settings/.jsdtscope
new file mode 100644
index 0000000..ad160f0
--- /dev/null
+++ b/.settings/.jsdtscope
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+	<classpathentry kind="src" path=""/>
+	<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.JRE_CONTAINER"/>
+	<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.baseBrowserLibrary"/>
+	<classpathentry kind="output" path=""/>
+</classpath>
diff --git a/.settings/org.eclipse.wst.jsdt.ui.superType.container b/.settings/org.eclipse.wst.jsdt.ui.superType.container
new file mode 100644
index 0000000..3bd5d0a
--- /dev/null
+++ b/.settings/org.eclipse.wst.jsdt.ui.superType.container
@@ -0,0 +1 @@
+org.eclipse.wst.jsdt.launching.baseBrowserLibrary
\ No newline at end of file
diff --git a/.settings/org.eclipse.wst.jsdt.ui.superType.name b/.settings/org.eclipse.wst.jsdt.ui.superType.name
new file mode 100644
index 0000000..05bd71b
--- /dev/null
+++ b/.settings/org.eclipse.wst.jsdt.ui.superType.name
@@ -0,0 +1 @@
+Window
\ No newline at end of file
diff --git a/examples/express-route.js b/examples/express-route.js
new file mode 100644
index 0000000..0e5542a
--- /dev/null
+++ b/examples/express-route.js
@@ -0,0 +1,49 @@
+var httpMocks = require('../lib/http-mock');
+
+// Suppose we have the following magical Express incantation:
+//
+//     app.get('/user/:id', mod.aroute);
+//
+// And we have ourselves a function to answer that call:
+
+var aroute = function( request, response ) {
+
+    var id = request.params.id;
+    console.log("We have a '%s' request for %s (ID: %d)", 
+                request.method, request.url, id);
+
+    var body = { 
+            name: 'Bob Dog',
+            age: 42, 
+            email: 'bob at dog.com'
+    };
+    response.setHeader('Content-Type', 'application/json');
+    response.statusCode = 200;
+    response.send( JSON.stringify(body), 'utf8' );
+    response.end();
+};
+
+// -----------------------------------------------------------------
+//   In another file, we can now test that function, like so:
+
+exports['aroute - Simple testing'] = function(test) {
+    var request  = httpMocks.createRequest({
+        method: 'GET',
+        url: '/user/42',
+        params: { id: 42 }
+    });
+    var response = httpMocks.createResponse();
+    
+    aroute(request, response);
+    
+    var data = JSON.parse( response._getData() );
+    test.equal("Bob Dog", data.name);
+    test.equal(42, data.age);
+    test.equal("bob at dog.com", data.email);
+
+    test.equal(200, response.statusCode );
+    test.ok( response._isEndCalled());
+    test.ok( response._isJSON());
+    test.ok( response._isUTF8());
+    test.done();
+};
\ No newline at end of file
diff --git a/lib/http-mock.js b/lib/http-mock.js
new file mode 100644
index 0000000..e7b28f4
--- /dev/null
+++ b/lib/http-mock.js
@@ -0,0 +1,12 @@
+/**
+ * Module: http-mock
+ *
+ *   The interface for this entire module that just exposes the exported
+ *   functions from the other libraries.
+ */
+
+var request  = require('./mockRequest');
+var response = require('./mockResponse');
+
+exports.createRequest = request.createRequest;
+exports.createResponse= response.createResponse;
\ No newline at end of file
diff --git a/lib/mockRequest.js b/lib/mockRequest.js
new file mode 100644
index 0000000..43f94e7
--- /dev/null
+++ b/lib/mockRequest.js
@@ -0,0 +1,137 @@
+/**
+ * File: mockRequest
+ * 
+ * This file implements node.js's implementation of a 'request' object.
+ * This is actually closer to what Express offers the user, in that the
+ * body is really a parsed object of values.
+ * 
+ * @author Howard Abrams <howard.abrams at gmail.com>
+ */
+
+Provider = function(){};
+
+
+/**
+ * Function: _setParameter
+ *
+ *    Set parameters that the client can then get using the 'params'
+ *    key.
+ *
+ * Parameters:
+ *
+ *   key - The key. For instance, 'bob' would be accessed: request.params.bob
+ *   value - The value to return when accessed.
+ */
+
+Provider.prototype._setParameter = function( key, value ) {
+    this.params[key] = value;
+};
+
+/**
+ * Function: _setMethod
+ *
+ *    Sets the HTTP method that the client gets when the called the 'method'
+ *    property. This defaults to 'GET' if it is not set.
+ *
+ * Parameters:
+ *
+ *   method - The HTTP method, e.g. GET, POST, PUT, DELETE, etc.
+ *   
+ * Note: We don't validate the string. We just return it.
+ */
+
+Provider.prototype._setMethod = function( method ) {
+    this.method  = method;
+};
+
+/**
+ * Function: _setURL
+ *
+ *    Sets the URL value that the client gets when the called the 'url'
+ *    property.
+ *
+ * Parameters:
+ *
+ *   url - The request path, e.g. /my-route/452
+ *   
+ * Note: We don't validate the string. We just return it. Typically, these
+ * do not include hostname, port or that part of the URL.
+ */
+
+Provider.prototype._setURL = function( url ) {
+    this.url = url;
+};
+
+/**
+ * Function: _setBody
+ *
+ *    Sets the body that the client gets when the called the 'body'
+ *    parameter. This defaults to 'GET' if it is not set.
+ *
+ * Parameters:
+ *
+ *   body - An object representing the body.
+ *   
+ * If you expect the 'body' to come from a form, this typically means that
+ * it would be a flat object of properties and values, as in:
+ * 
+ * > {  name: 'Howard Abrams',
+ * >    age: 522
+ * > }
+ * 
+ * If the client is expecting a JSON object through a REST interface, then
+ * this object could be anything.
+ */
+
+Provider.prototype._setBody = function( body ) {
+    this.body = body;
+};
+
+/**
+ * Function: _addBody
+ *
+ *    Adds another body parameter the client gets when calling the 'body'
+ *    parameter with another property value, e.g. the name of a form element
+ *    that was passed in.
+ *
+ * Parameters:
+ *
+ *   key - The key. For instance, 'bob' would be accessed: request.params.bob
+ *   value - The value to return when accessed.
+ */
+
+Provider.prototype._addBody = function( key, value ) {
+    this.body[key] = value;
+};
+
+/**
+ * Function: createRequest
+ *
+ *    Creates a new mock 'request' instance. All values are reset to the
+ *    defaults. 
+ *
+ * Parameters:
+ *
+ *   options - An object of named parameters.
+ *
+ * Options:
+ *
+ *   method - The method value, see <mockRequest._setMethod>
+ *   url    - The url value, see <mockRequest._setURL>
+ *   params - The parameters, see <mockRequest._setParam>
+ *   body   - The body values, , see <mockRequest._setBody> 
+ */
+
+exports.createRequest = function(options){
+    var p = new Provider();
+    
+    if (!options) {
+        options = {};
+    }
+    
+    p.method = (options.method) ? options.method : 'GET';
+    p.url    = (options.url   ) ? options.url    : '';
+    p.params = (options.params) ? options.params : {};
+    p.body   = (options.body  ) ? options.body   : {};
+    return p;
+};
diff --git a/lib/mockResponse.js b/lib/mockResponse.js
new file mode 100644
index 0000000..99bf5b3
--- /dev/null
+++ b/lib/mockResponse.js
@@ -0,0 +1,254 @@
+/**
+ * File: mockResponse
+ * 
+ *  This file implements node.js's implementation of a 'response' object.
+ *  Like all good mocks, the response file that can be called and used in 
+ *  place of a real HTTP response object.
+ *  
+ * @author Howard Abrams <howard.abrams at gmail.com>
+ */
+
+Provider = function(){};
+
+/**
+ * Function: writeHead
+ *
+ *  The 'writeHead' function from node's HTTP API.
+ * 
+ * Parameters:
+ *
+ *  statusCode - A number to send as a the HTTP status
+ *  headers    - An object of properties that will be used for
+ *               the HTTP headers.
+ */
+Provider.prototype.writeHead = function( statusCode, phrase, headers ) {
+    if (this._endCalled) {
+        throw "The end() method has already been called.";
+    }
+    
+    this.statusCode = statusCode;
+    
+    // Note: Not sure if the headers given in this function overwrite
+    //       any headers specified earlier.
+    if (headers) {
+        this._reasonPhrase = phrase;
+        this._headers = headers;
+    }
+    else {
+        this._headers = phrase;
+    }
+};
+
+/**
+ *  Function: send
+ *
+ *  The 'send' function from node's HTTP API that returns data
+ *  to the client. Can be called multiple times.
+ * 
+ * Parameters:
+ *
+ *  data - The data to return. Must be a string. Appended to 
+ *         previous calls to data.
+ *  encoding - Optional encoding value.
+ */
+Provider.prototype.send = function( data, encoding ) {
+    this._data += data;
+    if (encoding) {
+        this._encoding = encoding;
+    }
+};
+
+
+/**
+ * Function: write
+ *
+ *    This function has the same behavior as the 'send' function.
+ *
+ * Parameters:
+ *
+ *  data - The data to return. Must be a string. Appended to 
+ *         previous calls to data.
+ *  encoding - Optional encoding value.
+ */
+
+Provider.prototype.write = function( data, encoding ) {
+    this.send(data, encoding);
+};
+
+/**
+ *  Function: end
+ *
+ *  The 'end' function from node's HTTP API that finishes
+ *  the connection request. This must be called.
+ * 
+ * Parameters:
+ *
+ *  data - Optional data to return. Must be a string. Appended to 
+ *         previous calls to <send>.
+ *  encoding - Optional encoding value.
+ */
+Provider.prototype.end = function( data, encoding ) {
+    this._endCalled = true;
+    if (data) {
+        this._data += data;
+    }
+    if (encoding) {
+        this._encoding = encoding;
+    }
+};
+
+
+/**
+ * Function: getHeader
+ *
+ *   Returns a particular header by name.
+ */
+Provider.prototype.getHeader = function(name) {
+    return this._headers[name];
+};
+
+/**
+ * Function: setHeader
+ *
+ *   Set a particular header by name.
+ */
+Provider.prototype.setHeader = function(name, value) {
+    return this._headers[name] = value;
+};
+
+/**
+ * Function: removeHeader
+ *
+ *   Removes an HTTP header by name.
+ */
+Provider.prototype.removeHeader = function(name) {
+    delete this._headers[name];
+};
+
+/**
+ * Function: setEncoding
+ *
+ *    Sets the encoding for the data. Generally 'utf8'.
+ *
+ * Parameters:
+ *
+ *   encoding - The string representing the encoding value.
+ */
+Provider.prototype.setEncoding = function(encoding) {
+    this._encoding = encoding;
+};
+
+
+//This mock object stores some state as well
+//as some test-analysis functions:
+
+/**
+* Function: _isEndCalled
+*
+*  Since the <end> function must be called, this function
+*  returns true if it has been called. False otherwise.
+*/
+Provider.prototype._isEndCalled = function() {
+ return this._endCalled;
+};
+
+
+/**
+ * Function: _getHeaders
+ *
+ *  Returns all the headers that were set. This may be an
+ *  empty object, but probably will have "Content-Type" set.
+ */
+Provider.prototype._getHeaders = function() {
+    return this._headers;
+};
+
+
+
+/**
+ * Function: _getData
+ *
+ *  The data sent to the user.
+ */
+Provider.prototype._getData = function() {
+    return this._data;
+};
+
+/**
+ * Function: _getStatusCode
+ *
+ *  The status code that was sent to the user.
+ */
+Provider.prototype._getStatusCode = function() {
+    return this.statusCode;
+};
+
+/**
+ * Function: _isJSON
+ *
+ *  Returns true if the data sent was defined as JSON.
+ *  It doesn't validate the data that was sent.
+ */
+Provider.prototype._isJSON = function() {
+    return (this._headers["Content-Type"] == "application/json");
+};
+
+/**
+ * Function: _isUTF8
+ *
+ *    If the encoding was set, and it was set to UTF-8, then this function
+ *    return true. False otherwise.
+ *    
+ * Returns:
+ *
+ *   False if the encoding wasn't set and wasn't set to "utf8".
+ */
+Provider.prototype._isUTF8 = function() {
+    if ( !this._encoding ) {
+        return false;
+    }
+    return ( this._encoding === "utf8" );
+};
+
+/**
+ * Function: _isDataLengthValid
+ *
+ *    If the Content-Length header was set, this will only return true if
+ *    the length is actually the length of the data that was set.
+ *
+ * Returns:
+ *
+ *   True if the "Content-Length" header was not set. Otherwise, it compares
+ *   it.
+ */
+Provider.prototype._isDataLengthValid = function() {
+    if (this._headers["Content-Length"]) {
+        return (this._headers["Content-Length"] == this._data.length);
+    }
+    return true;
+};
+
+/**
+ * Function: createResponse
+ *
+ *    Creates a new mock 'response' instance. All values are reset to the
+ *    defaults. 
+ *
+ * Parameters:
+ *
+ *   options - An object of named parameters.
+ *
+ * Options:
+ *
+ */
+
+exports.createResponse = function(options) {
+    var p = new Provider();
+    
+    p._endCalled = false;
+    p._data = "";
+    p.statusCode = -1;
+    p._headers = {};
+
+    return p;
+};
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..191abdd
--- /dev/null
+++ b/package.json
@@ -0,0 +1,26 @@
+{
+  "author": "Howard Abrams <howard.abrams at gmail.com> (http://www.github.com/howardabrams)",
+  "name": "node-mocks-http",
+  "description": "Mock 'http' objects for testing Express routing functions",
+  "version": "0.0.1",
+  "homepage": "http://www.github.com/howardabrams/node-mocks-http",
+  "keywords": [
+               "mock",
+               "stub",
+               "dummy",
+               "nodejs",
+               "js",
+               "testing",
+               "test",
+               "http",
+               "http mock"
+             ],
+    "repository": {
+    "type": "git",
+    "url": "git://github.com/howardabrams/node-mocks-http.git"
+  },
+  "main": "./lib/http-mock.js",
+  "engines": {
+    "node": ">=0.6"
+  }
+}
\ No newline at end of file
diff --git a/test/test-mockRequest.js b/test/test-mockRequest.js
new file mode 100644
index 0000000..ac53840
--- /dev/null
+++ b/test/test-mockRequest.js
@@ -0,0 +1,100 @@
+/**
+ * Test: test-mockRequest
+ *
+ *   Test cases for the <mockRequest> module.
+ */
+
+var httpMocks = require('../lib/http-mock');
+
+exports['params - Simple verification'] = function(test) {
+    var request = httpMocks.createRequest();
+    request._setParameter('id', 42);
+    test.equal(42, request.params.id);
+    test.done();
+};
+
+exports['params - Unset value'] = function(test) {
+    var request = httpMocks.createRequest();
+    test.equal(undefined, request.params.id);
+    test.done();
+};
+
+
+exports['method - Default value'] = function(test) {
+    var request = httpMocks.createRequest();
+    test.equal('GET', request.method);
+    test.done();
+};
+
+exports['method - Setting a POST'] = function(test) {
+    var request = httpMocks.createRequest();
+    request._setMethod('POST');
+    test.equal('POST', request.method);
+    test.done();
+};
+
+exports['url - Default value'] = function(test) {
+    var request = httpMocks.createRequest();
+    test.equal('', request.url);
+    test.done();
+};
+
+exports['url - Setting a POST'] = function(test) {
+    var request = httpMocks.createRequest();
+    var expected = 'http://localhost:5732/blah';
+    request._setURL(expected);
+    test.equal(expected, request.url);
+    test.done();
+};
+
+exports['addBody - Simple verification'] = function(test) {
+    var request = httpMocks.createRequest();
+    
+    var username = 'bob';
+    request._addBody('user', username);
+    test.equal(username, request.body.user);
+    test.done();
+};
+
+exports['setBody - Simple verification'] = function(test) {
+    var request = httpMocks.createRequest();
+    
+    var username = 'bob';
+    request._setBody( { 'user': username } );
+    test.equal(username, request.body.user);
+    test.done();
+};
+
+exports['body - Unset value'] = function(test) {
+    var request = httpMocks.createRequest();
+    test.equal(undefined, request.body.user);
+    test.done();
+};
+
+
+exports['Object creation - All values set'] = function(test) {
+    
+    var methodValue = "PUT";
+    var idValue = 34;
+    var urlValue = 'http://localhost:6522/blingbling';
+    var usernameValue = "mittens";
+    
+    var request = httpMocks.createRequest({
+        method: methodValue,
+        url: urlValue,
+        params: {
+            id: idValue,
+            sort: 'asc'
+        },
+        body: {
+            username: usernameValue,
+            email: 'bob at dog.com'
+        }
+    });
+    
+    test.equal(methodValue, request.method);
+    test.equal(urlValue, request.url);
+    test.equal(idValue, request.params.id);
+    test.equal(usernameValue, request.body.username);
+    test.done();
+};
diff --git a/test/test-mockResponse.js b/test/test-mockResponse.js
new file mode 100644
index 0000000..eb2fdf1
--- /dev/null
+++ b/test/test-mockResponse.js
@@ -0,0 +1,121 @@
+/**
+ * Test: test-mockResponse
+ *
+ *   Test cases for the <mockResponse> module.
+ */
+
+var httpMocks = require('../lib/http-mock');
+
+exports['object - Simple verification'] = function( test ) {
+    var response = httpMocks.createResponse();
+    
+    response.send("Hello", 'utf8');
+    response.send("World");
+    test.equal("HelloWorld", response._getData());
+    test.ok( response._isUTF8());
+    test.ok(! response._isEndCalled());
+    test.done();
+};
+
+exports['object - Data Initialization'] = function( test ) {
+    var response = httpMocks.createResponse();
+    test.equal(-1, response.statusCode);
+    test.equal("", response._getData());
+    test.ok( ! response._isUTF8());
+    test.ok( ! response._isEndCalled());
+    test.done();
+};
+
+exports['end - Simple Verification'] = function(test) {
+    var response = httpMocks.createResponse();
+
+    response.send("Hello");
+    response.end("World");
+    
+    test.equal("HelloWorld", response._getData());
+
+    test.ok(response._isEndCalled());
+    test.done();
+};
+
+exports['end - No Data Called'] = function(test) {
+    var response = httpMocks.createResponse();
+
+    response.end("Hello World");
+    
+    test.equal("Hello World", response._getData());
+
+    test.ok(response._isEndCalled());
+    test.done();
+};
+
+exports['write - Simple verification'] = function( test ) {
+    var response = httpMocks.createResponse();
+    
+    response.write("Hello", 'utf8');
+    response.end("World");
+    
+    test.equal("HelloWorld", response._getData());
+
+    test.ok( response._isUTF8());
+    test.ok( response._isEndCalled());
+    test.done();
+};
+
+exports['setHeader - Simple verification'] = function(test) {
+    var response = httpMocks.createResponse();
+    
+    response.setHeader('foo', 'bar');
+    response.setHeader('bling', 'blang');
+    
+    test.equal('bar', response.getHeader('foo'));
+    test.equal('blang', response.getHeader('bling'));
+
+    response.removeHeader('bling');
+    test.ok( !response.getHeader('bling'));
+    
+    test.done();
+};
+
+exports['setHeader - Can not call after end'] = function(test) {
+    var response = httpMocks.createResponse();
+    
+    var body = 'hello world';
+    response.end(body);
+    
+    test.throws( function() {
+        response.setHead('Content-Length', body.length);
+    });
+    test.done();
+};
+
+exports['writeHead - Simple verification'] = function(test) {
+    var response = httpMocks.createResponse();
+    
+    var body = 'hello world';
+    response.writeHead(200, {
+      'Content-Length': body.length,
+      'Content-Type': 'text/plain' });
+    response.end(body);
+    
+    test.equal(200, response._getStatusCode() );
+    test.equal(body, response._getData() );
+    test.ok(response._isDataLengthValid() );
+    test.ok(response._isEndCalled());
+    test.ok(! response._isJSON());
+    test.done();
+};
+
+exports['writeHead - Can not call after end'] = function(test) {
+    var response = httpMocks.createResponse();
+    
+    var body = 'hello world';
+    response.end(body);
+    
+    test.throws( function() {
+        response.writeHead(200, {
+            'Content-Length': body.length,
+            'Content-Type': 'text/plain' });
+    });
+    test.done();
+};
\ No newline at end of file

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/node-mocks-http.git



More information about the Pkg-javascript-commits mailing list