Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

ported test to mocha + fixes

  • Loading branch information...
commit 8c35f04cdc5d4e833a9ac325c22cf6cc9f4670ab 1 parent 1813716
@kilianc kilianc authored
View
1  .gitignore
@@ -8,3 +8,4 @@ npm-debug.log
*.out
*.o
*.tmp
+coverage.html
View
2  .travis.yml
@@ -2,7 +2,7 @@ language: node_js
node_js:
- 0.4
- 0.6
- - 0.7
+ - 0.8
notifications:
email:
View
18 Makefile
@@ -0,0 +1,18 @@
+REPORTER = spec
+
+test:
+ @NODE_ENV=test ./node_modules/.bin/mocha test-mocha/*.test.js $(OPT) --colors --reporter $(REPORTER)
+
+test-bail:
+ $(MAKE) test OPT=--bail
+
+test-cov:
+ $(MAKE) lib-cov
+ @NSSOCKET_COV=1 $(MAKE) test REPORTER=html-cov > coverage.html
+ @open -g coverage.html
+
+lib-cov:
+ @rm -rf lib-cov
+ @jscoverage lib lib-cov
+
+.PHONY: test test-bail test-cov lib-cov
View
3  index.js
@@ -0,0 +1,3 @@
+module.exports = process.env.NSSSOCKET_COV
+ ? require('./lib-cov/nssocket')
+ : require('./lib/nssocket')
View
20 lib/common.js
@@ -12,8 +12,8 @@ var fs = require('fs'),
exports.createSocket = function (options) {
options = options || {};
options.type = options.type || 'tcp4';
-
- return options.type === 'tls'
+
+ return options.type === 'tls'
? exports.createTlsSocket(options)
: new net.Socket(options);
};
@@ -27,29 +27,29 @@ exports.createSocket = function (options) {
//
exports.createTlsSocket = function(options) {
var self = this;
-
- //
+
+ //
// Setup the TLS connection over the existing TCP connection:
- //
+ //
// 1. Create a new instance of `net.Socket`.
// 2. Create a new set of credentials with `options`.
// 3. Create the TLS pair
// 4. Pipe the TLS pair to the TCP socket
- //
+ //
var socket = new net.Stream({ type: 'tcp4' });
-
+
function setupTlsPipe () {
var sslcontext = crypto.createCredentials(options),
pair = tls.createSecurePair(sslcontext, false),
cleartext = pipe(pair, socket);
-
+
pair.on('secure', function() {
var verifyError = pair.ssl.verifyError();
if (verifyError) {
cleartext.authorized = false;
cleartext.authorizationError = verifyError;
- }
+ }
else {
cleartext.authorized = true;
}
@@ -70,7 +70,7 @@ exports.createTlsSocket = function(options) {
//
// helper function for createTlsSocket
-//
+//
function pipe(pair, socket) {
pair.encrypted.pipe(socket);
socket.pipe(pair.encrypted);
View
141 lib/nssocket.js
@@ -14,11 +14,11 @@ var net = require('net'),
//
// ### function NsSocket (socket, options)
-// #### @socket {Object} TCP or TLS 'socket' either from a 'connect' 'new' or from a server
+// #### @socket {Object} TCP or TLS 'socket' either from a 'connect' 'new' or from a server
// #### @options {Object} Options for this NsSocket
// NameSpace Socket, NsSocket, is a thin wrapper above TLS/TCP.
// It provides automatic buffering and name space based data emits.
-//
+//
var NsSocket = exports.NsSocket = function (socket, options) {
if (!(this instanceof NsSocket)) {
return new NsSocket(socket, options);
@@ -32,18 +32,18 @@ var NsSocket = exports.NsSocket = function (socket, options) {
options = socket;
socket = common.createSocket(options);
}
-
+
//
// Options should be
//
- // {
+ // {
// type : 'tcp' or 'tls',
// delimiter : '::', delimiter that separates between segments
// msgLength : 3 //number of segments in a complete message
// }
//
- options = options || {};
-
+ options = options || {};
+
var self = this,
startName;
@@ -52,7 +52,7 @@ var NsSocket = exports.NsSocket = function (socket, options) {
//
this.socket = socket;
this.connected = options.connected || socket.writable && socket.readable || false;
-
+
//
// Setup reconnect options.
//
@@ -63,7 +63,7 @@ var NsSocket = exports.NsSocket = function (socket, options) {
interval: options.retryInterval || 5000,
wait: options.retryInterval || 5000
};
-
+
//
// Setup default instance variables.
//
@@ -102,37 +102,38 @@ exports.createServer = function createServer(options, connectionListener) {
connectionListener = options;
options = {};
}
-
+
options.type = options.type || 'tcp4';
options.delimiter = options.delimiter || '::';
-
+
function onConnection (socket) {
+
//
// Incoming socket connections cannot reconnect
// by definition.
//
options.reconnect = false;
connectionListener(new NsSocket(socket, options));
- }
-
+ }
+
return options.type === 'tls'
? tls.createServer(options, onConnection)
: net.createServer(options, onConnection);
};
+// exports.createConnection = exports.connect = function connect(options, port, host, callback) {
+// return new NsSocket(options).connect(port, port, host, callback);
+// };
+
//
// ### function send (data, callback)
// #### @event {Array|string} The array (or string) that holds the event name
-// #### @data {Literal|Object} The data to be sent with the event.
+// #### @data {Literal|Object|Buffer} The data to be sent with the event.
// #### @callback {Function} the callback function when send is done sending
// The send function follows write/send rules for TCP/TLS/UDP
// in that the callback is called when sending is complete, not when delivered
//
NsSocket.prototype.send = function send(event, data, callback) {
- var dataType = typeof data,
- header = new Buffer(9),
- message;
-
// if we aren't connected/socketed, then error
if (!this.socket || !this.connected) {
return this.emit('error', new Error('NsSocket: sending on a bad socket'));
@@ -143,13 +144,33 @@ NsSocket.prototype.send = function send(event, data, callback) {
event = event.split(this._delimiter);
}
- event = Buffer(JSON.stringify(event));
-
+ var dataType = typeof data
if (dataType === 'undefined' || dataType === 'function') {
callback = data;
data = null;
}
+ var message = this.createMessage(event, data);
+
+ // now actually write to the socket
+ if (this.socket.cleartext) {
+ this.socket.cleartext.write(message, callback);
+ } else {
+ this.socket.write(message, callback);
+ }
+};
+
+//
+// ### function _createMessage (event, data)
+// #### @event {Array|string} The array (or string) that holds the event name
+// #### @data {Literal|Object|Buffer} The data to be sent with the event.
+// Returns a packaged binary message ready to be written to the socket.
+//
+NsSocket.prototype.createMessage = function _createMessage(event, data) {
+ var header = new Buffer(9);
+
+ event = Buffer(JSON.stringify(event));
+
if (Buffer.isBuffer(data)) {
header.writeInt8(1, 8);
} else {
@@ -160,15 +181,8 @@ NsSocket.prototype.send = function send(event, data, callback) {
header.writeUInt32BE(event.length, 0);
header.writeUInt32BE(data.length, 4);
- message = Buffer.concat([header, event, data], 9 + event.length + data.length);
-
- // now actually write to the socket
- if (this.socket.cleartext) {
- this.socket.cleartext.write(message, callback);
- } else {
- this.socket.write(message, callback);
- }
-};
+ return Buffer.concat([header, event, data], 9 + event.length + data.length);
+}
//
// ### function data (event, callback)
@@ -180,7 +194,7 @@ NsSocket.prototype.data = function (event, callback) {
if (typeof event === 'string') {
event = event.split(this._delimiter);
}
-
+
this.on(['data'].concat(event), callback);
};
@@ -198,13 +212,13 @@ NsSocket.prototype.dataOnce = function (event, callback) {
if (typeof event === 'string') {
event = event.split(this._delimiter);
}
-
+
this.once(['data'].concat(event), callback);
};
-//
+//
// ### function setIdle (time, callback)
-// #### @time {Integer} how often to emit idle
+// #### @time {Integer} how often to emit idle
// Set the idle/timeout timer
//
NsSocket.prototype.setIdle = function setIdle(time) {
@@ -229,9 +243,9 @@ NsSocket.prototype.destroy = function destroy() {
// do nothing on errors
}
}
-
+
// clear buffer
- this.data = '';
+ // this.data = '';
this.emit('destroy');
};
@@ -252,15 +266,15 @@ NsSocket.prototype.end = function end() {
hadErr = true;
return;
}
-
+
this.socket = null;
}
-
+
return this.emit('close', hadErr || undefined);
};
//
-// ### function connect (port[, host, callback])
+// ### function connect (port[, host, callback])
// A passthrough to the underlying socket's connect function
//
NsSocket.prototype.connect = function connect(/*port, host, callback*/) {
@@ -292,11 +306,11 @@ NsSocket.prototype.connect = function connect(/*port, host, callback*/) {
this.port = port || this.port;
this.host = host || this.host;
args = this.port ? [this.port, this.host] : [this.host];
-
+
if (callback) {
args.push(callback);
}
-
+
if (['tcp4', 'tls'].indexOf(this._type) === -1) {
return this.emit('error', new Error('Unknown Socket Type'));
}
@@ -312,17 +326,18 @@ NsSocket.prototype.connect = function connect(/*port, host, callback*/) {
this.connected = true;
this.socket.connect.apply(this.socket, args);
+ return this;
};
//
// ### function reconnect ()
-// Attempts to reconnect the current socket on `close` or `error`.
+// Attempts to reconnect the current socket on `close` or `error`.
// This instance will attempt to reconnect until `this.retry.max` is reached,
// with an interval increasing by powers of 10.
//
NsSocket.prototype.reconnect = function reconnect() {
var self = this;
-
+
//
// Helper function containing the core reconnect logic
//
@@ -332,9 +347,9 @@ NsSocket.prototype.reconnect = function reconnect() {
// with this instance.
//
self.retry.waiting = true;
- self.socket.removeAllListeners();
+ self.socket && self.socket.destroy();
self.socket = common.createSocket(self._options);
-
+
//
// Cleanup reconnect logic once the socket connects
//
@@ -342,14 +357,14 @@ NsSocket.prototype.reconnect = function reconnect() {
self.retry.waiting = false;
self.retry.retries = 0;
});
-
+
//
// Attempt to reconnect the socket
//
self._setup();
self.connect();
}
-
+
//
// Helper function which attempts to retry if
// it is less than the maximum
@@ -359,10 +374,10 @@ NsSocket.prototype.reconnect = function reconnect() {
if (self.retry.retries >= self.retry.max) {
return self.emit('error', new Error('Did not reconnect after maximum retries: ' + self.retry.max));
}
-
+
doReconnect();
}
-
+
this.retry.wait = this.retry.interval * Math.pow(10, this.retry.retries);
setTimeout(tryReconnect, this.retry.wait);
};
@@ -374,16 +389,16 @@ NsSocket.prototype.reconnect = function reconnect() {
NsSocket.prototype._setup = function () {
var self = this,
startName;
-
//
- // Because of how the code node.js `tls` module works, we have
- // to separate some bindings. The main difference is on
+ // Because of how the code node.js `tls` module works, we have
+ // to separate some bindings. The main difference is on
// connection, some socket activities.
//
if (this._type === 'tcp4') {
startName = 'connect';
this.socket.on('data', this._onData.bind(this));
+ // this.socket.on('data', );
// create a stub for the setKeepAlive functionality
this.setKeepAlive = function () {
@@ -393,6 +408,7 @@ NsSocket.prototype._setup = function () {
else if (this._type === 'tls') {
startName = 'secureConnection';
this.socket.once('connect', function () {
+ console.log('secureConnection')
self.socket.cleartext.on('data', self._onData.bind(self));
});
@@ -423,7 +439,7 @@ NsSocket.prototype._setup = function () {
this.socket.on('timeout', this._onIdle.bind(this));
};
-//
+//
// ### @private function _onStart ()
// Emits a start event when the underlying socket finish connecting
// might be used to do other activities.
@@ -439,7 +455,9 @@ NsSocket.prototype._onStart = function _onStart() {
// We assume messages arrive in order.
//
NsSocket.prototype._onData = function _onData(chunk) {
- ~this._incomingMessageLength ? this._fetchHeader(chunk) : this._fetchBody(chunk);
+ ~this._messageLength
+ ? this._fetchBody(chunk)
+ : this._fetchHeader(chunk);
};
//
@@ -448,10 +466,8 @@ NsSocket.prototype._onData = function _onData(chunk) {
// Buffers and parse the header of the message
//
NsSocket.prototype._fetchHeader = function _fetchHeader(chunk) {
- var header
-
if (this._bufferJoiner.length + chunk.length >= 9) {
- header = this._bufferJoiner.add(chunk).join();
+ var header = this._bufferJoiner.add(chunk).join();
this._eventLength = header.readUInt32BE(0);
this._messageLength = header.readUInt32BE(4);
this._messagetype = header.readInt8(8);
@@ -482,7 +498,7 @@ NsSocket.prototype._fetchBody = function _fetchBody(chunk) {
this.emit(['data'].concat(event), data);
if (chunkLength - bytesLeft) {
- process.nextTick(this._fetchHeader.bind(this, chunk.slice(bytesLeft)));
+ this._fetchHeader(chunk.slice(bytesLeft));
}
return;
@@ -503,7 +519,7 @@ NsSocket.prototype._onClose = function _onClose(hadError) {
else {
this.emit('close');
}
-
+
this.connected = false;
if (this._reconnect) {
this.reconnect();
@@ -517,16 +533,16 @@ NsSocket.prototype._onClose = function _onClose(hadError) {
//
NsSocket.prototype._onError = function _onError(error) {
this.connected = false;
-
+
if (!this._reconnect) {
return this.emit('error', error || new Error('An Unknown Error occured'));
}
-
+
this.reconnect();
};
-//
-// ### @private function _onIdle ()
+//
+// ### @private function _onIdle ()
// #### Emits the idle event (based on timeout)
//
NsSocket.prototype._onIdle = function _onIdle() {
@@ -534,5 +550,4 @@ NsSocket.prototype._onIdle = function _onIdle() {
if (this._timeout) {
this.socket.setTimeout(this._timeout);
}
-};
-
+};
View
11 package.json
@@ -16,14 +16,15 @@
"eventemitter2": "0.4.x"
},
"devDependencies": {
- "vows": "0.6.x"
+ "vows": "0.6.x",
+ "mocha": "1.3.x",
+ "chai": "1.0.x"
},
- "main": "./lib/nssocket",
+ "main": "./",
"engines": {
"node": ">= 0.7.x"
},
"scripts": {
- "test": "vows test/*-test.js --spec"
+ "test": "make test"
}
-}
-
+}
View
62 test-mocha/buffer-tcp.test.js
@@ -0,0 +1,62 @@
+var net = require('net'),
+ fs = require ('fs'),
+ expect = require('chai').expect,
+ NsSocket = require('../lib/nssocket').NsSocket
+
+var trollface = fs.readFileSync('test-mocha/fixtures/trollface.jpg')
+var TCP_PORT = 5467
+
+describe('nssocket/tcp/buffer', function () {
+ before(function (done) {
+ var self = this
+ this.outbound = new NsSocket({
+ type : 'tcp4',
+ delimiter: '/'
+ })
+ this.server = net.createServer(function (inbound) {
+ self.inbound = inbound
+ done()
+ })
+ this.server.listen(TCP_PORT, function (stream) {
+ self.outbound.connect(TCP_PORT)
+ })
+ })
+ after(function () {
+ this.server.close()
+ this.outbound.end()
+ this.inbound.end()
+ })
+ describe('#send()', function () {
+ it('should correctly receive multi messages chunks / json', testMulti(5, { foo: 'bar' }))
+ it('should correctly receive multi messages chunks / buffer', testMulti(5, Buffer('foo:bar')))
+ it('should correctly receive multi messages chunks / large buffer', testMulti(5, trollface))
+ })
+})
+
+function testMulti(n, data) {
+ return function (done) {
+ var self = this
+ var message = self.outbound.createMessage('test::multi', data)
+ var buffer = Buffer.concat(arrayOf(message, n), message.length * n)
+
+ function onMessage(data) {
+ n --
+ expect(data).to.be.eql(data)
+ if (!n) {
+ self.outbound.undata('binary', onMessage)
+ done()
+ }
+ }
+
+ self.outbound.data('test::multi', onMessage)
+ self.inbound.write(buffer)
+ }
+}
+
+function arrayOf(what, howmany) {
+ var arr = []
+ for (var i = 0; i < howmany; i++) {
+ arr.push(what)
+ }
+ return arr
+}
View
63 test-mocha/buffer-tls.test.js
@@ -0,0 +1,63 @@
+var tls = require('tls'),
+ fs = require ('fs'),
+ expect = require('chai').expect,
+ NsSocket = require('../lib/nssocket').NsSocket
+
+var trollface = fs.readFileSync('test-mocha/fixtures/trollface.jpg')
+var TCP_PORT = 5467
+
+describe('nssocket/tls/buffer', function () {
+ before(function (done) {
+ var self = this
+ this.outbound = new NsSocket({ type : 'tls', delimiter: '/' })
+ this.server = tls.createServer({
+ key: fs.readFileSync('test-mocha/fixtures/ryans-key.pem'),
+ cert: fs.readFileSync('test-mocha/fixtures/ryans-cert.pem'),
+ ca: fs.readFileSync('test-mocha/fixtures/ryans-csr.pem')
+ }, function (inbound) {
+ self.inbound = inbound
+ done()
+ })
+ this.server.listen(TCP_PORT, function (stream) {
+ self.outbound.connect(TCP_PORT)
+ })
+ })
+ after(function () {
+ this.server.close()
+ this.inbound.end()
+ this.outbound.end()
+ })
+ describe('#send()', function () {
+ it('should correctly receive multi messages chunks / json', testMulti(5, { foo: 'bar' }))
+ it('should correctly receive multi messages chunks / buffer', testMulti(5, Buffer('foo:bar')))
+ it('should correctly receive multi messages chunks / large buffer', testMulti(5, trollface))
+ })
+})
+
+function testMulti(n, data) {
+ return function (done) {
+ var self = this
+ var message = self.outbound.createMessage('test::multi', data)
+ var buffer = Buffer.concat(arrayOf(message, n), message.length * n)
+
+ function onMessage(data) {
+ n --
+ expect(data).to.be.eql(data)
+ if (!n) {
+ self.outbound.undata('binary', onMessage)
+ done()
+ }
+ }
+
+ self.outbound.data('test::multi', onMessage)
+ self.inbound.write(buffer)
+ }
+}
+
+function arrayOf(what, howmany) {
+ var arr = []
+ for (var i = 0; i < howmany; i++) {
+ arr.push(what)
+ }
+ return arr
+}
View
57 test-mocha/create-server.test.js
@@ -0,0 +1,57 @@
+/*
+ * create-server-test.js : namespace socket unit test for TLS.
+ *
+ * (C) 2011, Nodejitsu Inc.
+ *
+ */
+
+var net = require('net'),
+ tls = require('tls'),
+ fs = require ('fs'),
+ path = require('path'),
+ assert = require('chai').assert,
+ nssocket = require('../')
+
+var PORT = 9568
+var HOST = '127.0.0.1'
+var PIPE = path.join(__dirname, 'fixtures', 'nssocket.sock')
+var HOSTNAME = 'localhost'
+
+describe('nssocket/create-server', function () {
+ describe('#createServer()', function () {
+ before(function() {
+ try { fs.unlinkSync(PIPE) }
+ catch (err) {}
+ })
+ afterEach(function (done) {
+ this.server.close(done)
+ this.outbound.end()
+ this.inbound.end()
+ })
+ it('should create a full-duplex namespaced socket / (PORT)', testWith(PORT))
+ it('should create a full-duplex namespaced socket / (PORT, HOST)', testWith(PORT, HOST))
+ it('should create a full-duplex namespaced socket / (PORT, HOSTNAME)', testWith(PORT, HOSTNAME))
+ it('should create a full-duplex namespaced socket / (PIPE)', testWith(PIPE))
+ })
+})
+
+function testWith() {
+ var args = [].slice.call(arguments)
+
+ return function (done) {
+ var self = this
+ self.outbound = new nssocket.NsSocket()
+ self.server = nssocket.createServer(function (inbound) {
+ self.inbound = inbound
+ self.outbound.on(['data', 'here', 'is'], function (data) {
+ assert.deepEqual(this.event, ['data', 'here', 'is'])
+ assert.equal(data, 'something.')
+ done()
+ })
+ self.inbound.send(['here', 'is'], 'something.');
+ })
+ self.server.listen.apply(self.server, args.concat(function () {
+ self.outbound.connect.apply(self.outbound, args)
+ }))
+ }
+}
View
16 test-mocha/fixtures/ryans-cert.pem
@@ -0,0 +1,16 @@
+-----BEGIN CERTIFICATE-----
+MIICfzCCAegCCQCE5Xuxkur1mjANBgkqhkiG9w0BAQUFADCBgzELMAkGA1UEBhMC
+VVMxCzAJBgNVBAgMAk5ZMQswCQYDVQQHDAJOWTEVMBMGA1UECgwMSW50ZXJuZXQu
+Y29tMRgwFgYDVQQLDA9JbnRlcm5ldCBOaW5qYXMxDjAMBgNVBAMMBU51am9vMRkw
+FwYJKoZIhvcNAQkBFgpudUBqb28uY29tMB4XDTExMTAxMzIxNDgxOVoXDTExMTEx
+MjIxNDgxOVowgYMxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJOWTELMAkGA1UEBwwC
+TlkxFTATBgNVBAoMDEludGVybmV0LmNvbTEYMBYGA1UECwwPSW50ZXJuZXQgTmlu
+amFzMQ4wDAYDVQQDDAVOdWpvbzEZMBcGCSqGSIb3DQEJARYKbnVAam9vLmNvbTCB
+nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA2hKAVOtI/mNUpOkuHgBDaIu0EelR
+SdEc5GoqfIeH+59VkJqkIf+lAgRJk7PSJuwGY5Kzq6DwD/RStzk+S/Z+5h/61YQX
+D28SOf9d53+hSn6NpetOa0f9gL+ouc0MkSL9fOW8geD07Yv0N8XpdgiSQG6jp6Wd
+yo2R7xJaoBjRfP8CAwEAATANBgkqhkiG9w0BAQUFAAOBgQC7DFd1pWGVwzGGYAq0
+KkJYCJQoq6NgthHQ206U/3cFlelSG2NqbnjfAxPX1N7waT2FIa2yE/Ax6AMZDw8A
+v3hxwo+c0j5YzCBfFXXbP/8jZtWEUuj5bDa0rplqP1JwDa0JTqxuIdpgVANa8FLE
+NkLSqWOjovXCdekT/LaN84s5aw==
+-----END CERTIFICATE-----
View
12 test-mocha/fixtures/ryans-csr.pem
@@ -0,0 +1,12 @@
+-----BEGIN CERTIFICATE REQUEST-----
+MIIBxDCCAS0CAQAwgYMxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJOWTELMAkGA1UE
+BwwCTlkxFTATBgNVBAoMDEludGVybmV0LmNvbTEYMBYGA1UECwwPSW50ZXJuZXQg
+TmluamFzMQ4wDAYDVQQDDAVOdWpvbzEZMBcGCSqGSIb3DQEJARYKbnVAam9vLmNv
+bTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA2hKAVOtI/mNUpOkuHgBDaIu0
+EelRSdEc5GoqfIeH+59VkJqkIf+lAgRJk7PSJuwGY5Kzq6DwD/RStzk+S/Z+5h/6
+1YQXD28SOf9d53+hSn6NpetOa0f9gL+ouc0MkSL9fOW8geD07Yv0N8XpdgiSQG6j
+p6Wdyo2R7xJaoBjRfP8CAwEAAaAAMA0GCSqGSIb3DQEBBQUAA4GBADdnMH2brmA/
+pYWleVBOd1ZhkkXoTns0Lv0KNWpdjKT6mVxSsiiuKc8MBtWTFseM/kDxRm1VCjPL
+YcNZRtKVLOUn3cwwtYGJm9EMmvn0EzHr6p2IO6Z7JBETOHoJT9zXszbcvUFaRb+9
+7jTr6wsDY/raS3FdCBGp1nK8EVw8QT0r
+-----END CERTIFICATE REQUEST-----
View
15 test-mocha/fixtures/ryans-key.pem
@@ -0,0 +1,15 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIICXQIBAAKBgQDaEoBU60j+Y1Sk6S4eAENoi7QR6VFJ0Rzkaip8h4f7n1WQmqQh
+/6UCBEmTs9Im7AZjkrOroPAP9FK3OT5L9n7mH/rVhBcPbxI5/13nf6FKfo2l605r
+R/2Av6i5zQyRIv185byB4PTti/Q3xel2CJJAbqOnpZ3KjZHvElqgGNF8/wIDAQAB
+AoGAX9PnfumRvu/pXzp0oIxfEs7pR0GvDfANcTZSCz0HfYQL9qpt297aJOO7bWOE
+wsPPHux1dcMYGvqzan6GKJ1eL3OzGDWdgVgMGLlp0mZj74QWCJDyBrAKseNJc/vV
+YXqq2nfb44yLVvFzZnJmD59FpDVgEdUw/KtVoA7Qg3MNnlECQQD/ITXaukRiCHMk
+/yJBbcyt7hb/M3gdknr1ophCnwIcoKFrJUUzY0LF5NXbA7OMDgK7Fg63blc8KEEi
+L7gZYdBJAkEA2tDuTElF2awoY791vrfaOhIpMcqTtn/glojhO9XYDt3iAY+o6LW3
+o2FZxt+7jwoQSUxN68lwc+1MXc1IafRzBwJAZPNzJ9VEcbX+OclqeJFFyBzJpLls
+8eagGMn5jYL1hvZYaNkahLbmGP/vTvYr+WMh2X1k3Vgf1IHpI+nV4tU9YQJBANl0
+Mq07UCBO92CRf8kF2uhE7g1eXUdLc/0FkJgvHuU/Wf/lLZ3+IL5L27VI2JMBFEhT
+fUhqSsfaNj8t593sIXcCQQDtWaKRz2QPAjhtM29xVihOBVPppdXdm1jSk25EciJX
+x4lrUXyNTeyQif0Hezp4WaYhVOS8uRGYnKH9eJzXQ5Pv
+-----END RSA PRIVATE KEY-----
View
BIN  test-mocha/fixtures/trollface.jpg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
57 test-mocha/tcp-reconnect.test.js
@@ -0,0 +1,57 @@
+/*
+ * create-server-test.js : namespace socket unit test for TLS.
+ *
+ * (C) 2011, Nodejitsu Inc.
+ *
+ */
+
+var net = require('net'),
+ tls = require('tls'),
+ fs = require ('fs'),
+ path = require('path'),
+ assert = require('chai').assert,
+ nssocket = require('../')
+
+var TCP_PORT = 30105
+var TCP_OPTIONS = {
+ type : 'tcp4',
+ delimiter: '.}',
+ reconnect: true,
+ retryInterval: 200
+}
+
+describe('nssocket/tcp/reconnect', function () {
+ after(function (done) {
+ this.server.close(done)
+ this.receiver.end()
+ this.sender.end()
+ })
+ describe('client', function () {
+ it('should connect', function (done) {
+ var self = this
+ self.receiver = new nssocket.NsSocket(TCP_OPTIONS).connect(TCP_PORT)
+ self.server = nssocket.createServer(TCP_OPTIONS, done.bind(null, null))
+ setTimeout(function () {
+ self.server.listen(TCP_PORT)
+ }, 200)
+ })
+ it('should handle reconnection', function (done) {
+ var self = this
+ self.server.close()
+ self.receiver.end()
+ self.server = nssocket.createServer(TCP_OPTIONS, function (sender) {
+ self.sender = sender
+ done()
+ })
+ self.server.listen(TCP_PORT)
+ })
+ it('should be able to send after reconnection', function (done) {
+ this.receiver.once('data.}here.}is', function (data) {
+ assert.deepEqual(this.event, ['data', 'here', 'is'])
+ assert.equal(data, 'something.')
+ done()
+ })
+ this.sender.send('here.}is', 'something.')
+ })
+ })
+})
View
114 test-mocha/tcp.test.js
@@ -0,0 +1,114 @@
+/*
+ * create-server-test.js : namespace socket unit test for TLS.
+ *
+ * (C) 2011, Nodejitsu Inc.
+ *
+ */
+
+var net = require('net'),
+ tls = require('tls'),
+ fs = require ('fs'),
+ path = require('path'),
+ assert = require('chai').assert,
+ nssocket = require('../')
+
+var TCP_PORT = 30105
+var TCP_OPTIONS = {
+ type : 'tcp4',
+ delimiter: '.}',
+ reconnect: true,
+ retryInterval: 200
+}
+
+describe('nssocket/tcp', function () {
+ describe('#()', function () {
+ before(function () {
+ this.outbound = new nssocket.NsSocket(TCP_OPTIONS)
+ })
+ it('should create a wrapped socket', function () {
+ assert.instanceOf(this.outbound, nssocket.NsSocket)
+ })
+ it('should have the proper configuration settings', function () {
+ assert.equal(this.outbound._type, TCP_OPTIONS.type)
+ assert.equal(this.outbound._delimiter, TCP_OPTIONS.delimiter)
+ })
+ })
+ describe('#connect()', function () {
+ it('should actually connect', function (done) {
+ var self = this
+ self.server = nssocket.createServer(TCP_OPTIONS, function (inbound) {
+ self.inbound = inbound
+ done()
+ }).listen(TCP_PORT, function () {
+ self.outbound.connect(TCP_PORT)
+ })
+ })
+ })
+ describe('#setIdle()', function () {
+ it('should save idle timeout', function (done) {
+ this.outbound.once('idle', done)
+ this.outbound.setIdle(100)
+ })
+ })
+ describe('#createMessage()', function () {
+ it('should package json into binary messages', function () {
+ var rawMessage = this.outbound.createMessage(['foo', 'bar'], { content: 'foobar!' })
+ var eventLength = rawMessage.readUInt32BE(0)
+ var messageLength = rawMessage.readUInt32BE(4)
+ var messagetype = rawMessage.readInt8(8)
+ var event = JSON.parse(rawMessage.slice(9, eventLength + 9))
+ var data = JSON.parse(rawMessage.slice(9 + eventLength).toString())
+
+ assert.equal(messagetype, 0)
+ assert.deepEqual(event, ['foo', 'bar'])
+ assert.deepEqual(data, { content: 'foobar!' })
+ })
+ it('should package buffers into binary messages', function () {
+ var rawMessage = this.outbound.createMessage(['foo', 'bar'], Buffer('foo::bar'))
+ var eventLength = rawMessage.readUInt32BE(0)
+ var messageLength = rawMessage.readUInt32BE(4)
+ var messagetype = rawMessage.readInt8(8)
+ var event = JSON.parse(rawMessage.slice(9, eventLength + 9))
+ var data = rawMessage.slice(9 + eventLength).toString()
+
+ assert.equal(messagetype, 1)
+ assert.deepEqual(event, ['foo', 'bar'])
+ assert.equal(data.toString(), 'foo::bar')
+ })
+ })
+ describe('#on()', function () {
+ it('should handle namespaced events', function (done) {
+ var rawMessage = this.outbound.createMessage(['here', 'is'], 'something.')
+ this.inbound.once('data.}here.}is', function (data) {
+ assert.deepEqual(this.event, ['data', 'here', 'is'])
+ assert.equal(data, 'something.')
+ done()
+ })
+ this.outbound.socket.write(rawMessage)
+ })
+ })
+ describe('#send()', function () {
+ it('should package and send json messages', function (done) {
+ this.inbound.once('data.}hello.}world', function (data) {
+ assert.deepEqual(this.event, ['data', 'hello', 'world'])
+ assert.deepEqual(data, { content: 'foobar!' })
+ done()
+ })
+ this.outbound.send(['hello','world'], { content: 'foobar!' })
+ })
+ it('should package and send binary messages', function (done) {
+ this.inbound.once('data.}hello.}world', function (data) {
+ assert.deepEqual(this.event, ['data', 'hello', 'world'])
+ assert.equal(data.toString(), 'foo::bar')
+ done()
+ })
+ this.outbound.send(['hello','world'], Buffer('foo::bar'))
+ })
+ })
+ describe('#end()', function () {
+ it('should close the connection', function (done) {
+ this.outbound.on('close', done)
+ this.inbound.end()
+ })
+ })
+})
View
116 test-mocha/tls.text.js
@@ -0,0 +1,116 @@
+/*
+ * create-server-test.js : namespace socket unit test for TLS.
+ *
+ * (C) 2011, Nodejitsu Inc.
+ *
+ */
+
+var net = require('net'),
+ tls = require('tls'),
+ fs = require ('fs'),
+ path = require('path'),
+ assert = require('chai').assert,
+ nssocket = require('../')
+
+var TLS_PORT = 30105
+var TLS_OPTIONS = {
+ type: 'tls',
+ delimiter: '.}',
+ key: fs.readFileSync(path.join(__dirname, 'fixtures', 'ryans-key.pem')),
+ cert: fs.readFileSync(path.join(__dirname, 'fixtures', 'ryans-cert.pem')),
+ ca: fs.readFileSync(path.join(__dirname, 'fixtures', 'ryans-csr.pem'))
+}
+
+describe('nssocket/tls', function () {
+ describe('#()', function () {
+ before(function () {
+ this.outbound = new nssocket.NsSocket({ type: 'tls', delimiter: '.}' })
+ })
+ it('should create a wrapped socket', function () {
+ assert.instanceOf(this.outbound, nssocket.NsSocket)
+ })
+ it('should have the proper configuration settings', function () {
+ assert.equal(this.outbound._type, TLS_OPTIONS.type)
+ assert.equal(this.outbound._delimiter, TLS_OPTIONS.delimiter)
+ })
+ })
+ describe('#connect()', function () {
+ it('should actually connect', function (done) {
+ var self = this
+ self.server = nssocket.createServer(TLS_OPTIONS, function (inbound) {
+ self.inbound = inbound
+ // assert.ok(inbound.authorized, 'Certificate is not authorized (' + inbound.authorizationError + ')')
+ done()
+ }).listen(TLS_PORT, function () {
+ self.outbound.connect(TLS_PORT)
+ })
+ })
+ })
+ describe('#setIdle()', function () {
+ it('should save idle timeout', function (done) {
+ this.outbound.once('idle', done)
+ this.outbound.setIdle(100)
+ })
+ })
+ describe('#createMessage()', function () {
+ it('should package json into binary messages', function () {
+ var rawMessage = this.outbound.createMessage(['foo', 'bar'], { content: 'foobar!' })
+ var eventLength = rawMessage.readUInt32BE(0)
+ var messageLength = rawMessage.readUInt32BE(4)
+ var messagetype = rawMessage.readInt8(8)
+ var event = JSON.parse(rawMessage.slice(9, eventLength + 9))
+ var data = JSON.parse(rawMessage.slice(9 + eventLength).toString())
+
+ assert.equal(messagetype, 0)
+ assert.deepEqual(event, ['foo', 'bar'])
+ assert.deepEqual(data, { content: 'foobar!' })
+ })
+ it('should package buffers into binary messages', function () {
+ var rawMessage = this.outbound.createMessage(['foo', 'bar'], Buffer('foo::bar'))
+ var eventLength = rawMessage.readUInt32BE(0)
+ var messageLength = rawMessage.readUInt32BE(4)
+ var messagetype = rawMessage.readInt8(8)
+ var event = JSON.parse(rawMessage.slice(9, eventLength + 9))
+ var data = rawMessage.slice(9 + eventLength).toString()
+
+ assert.equal(messagetype, 1)
+ assert.deepEqual(event, ['foo', 'bar'])
+ assert.equal(data.toString(), 'foo::bar')
+ })
+ })
+ describe('#on()', function () {
+ it('should handle namespaced events', function (done) {
+ var rawMessage = this.outbound.createMessage(['here', 'is'], 'something.')
+ this.outbound.once('data.}here.}is', function (data) {
+ assert.deepEqual(this.event, ['data', 'here', 'is'])
+ assert.equal(data, 'something.')
+ done()
+ })
+ this.outbound.send(['here','is'], 'something.')
+ })
+ })
+ describe('#send()', function () {
+ it('should package and send json messages', function (done) {
+ this.inbound.once('data.}hello.}world', function (data) {
+ assert.deepEqual(this.event, ['data', 'hello', 'world'])
+ assert.deepEqual(data, { content: 'foobar!' })
+ done()
+ })
+ this.outbound.send(['hello','world'], { content: 'foobar!' })
+ })
+ it('should package and send binary messages', function (done) {
+ this.inbound.once('data.}hello.}world', function (data) {
+ assert.deepEqual(this.event, ['data', 'hello', 'world'])
+ assert.equal(data.toString(), 'foo::bar')
+ done()
+ })
+ this.outbound.send(['hello','world'], Buffer('foo::bar'))
+ })
+ })
+ describe('#end()', function () {
+ it('should close the connection', function (done) {
+ this.outbound.on('close', done)
+ this.inbound.end()
+ })
+ })
+})
View
4 test/create-server-test.js
@@ -4,7 +4,7 @@
* (C) 2011, Nodejitsu Inc.
*
*/
-
+
var assert = require('assert'),
fs = require('fs'),
net = require('net'),
@@ -23,7 +23,7 @@ function getBatch() {
topic: function () {
var outbound = new nssocket.NsSocket(),
server = nssocket.createServer(this.callback.bind(null, null, outbound));
-
+
server.listen.apply(server, args.concat(function () {
outbound.connect.apply(outbound, args);
}));
View
4 test/tls-test.js
@@ -4,7 +4,7 @@
* (C) 2011, Nodejitsu Inc.
*
*/
-
+
var assert = require('assert'),
fs = require('fs'),
net = require('net'),
@@ -66,7 +66,7 @@ vows.describe('nssocket/tls').addBatch({
assert.equal(this.event[0], 'data');
assert.equal(this.event[1], 'here');
assert.equal(this.event[2], 'is');
- assert.equal(data, 'something');
+ assert.equal(data, 'something.');
},
"once idle": {
topic: function (_, outbound, inbound) {
Please sign in to comment.
Something went wrong with that request. Please try again.