Skip to content

Commit

Permalink
simple test and teardown logic
Browse files Browse the repository at this point in the history
  • Loading branch information
James Halliday committed Dec 17, 2011
1 parent 8ae5683 commit 460a528
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 1 deletion.
13 changes: 12 additions & 1 deletion index.js
Expand Up @@ -9,6 +9,10 @@ var upnode = module.exports = function (cons) {
up.conn = null;
up.remote = null;
up.queue = [];
up.close = function () {
up.closed = true;
up.emit('close');
};

var emitter = new EventEmitter;
Object.keys(EventEmitter.prototype).forEach(function (name) {
Expand All @@ -27,6 +31,8 @@ upnode.connect = function () {
};

function connect (up, cons) {
if (up.closed) return;

var argv = [].slice.call(arguments, 1).reduce(function (acc, arg) {
if (typeof arg === 'function') acc.cb = arg
else if (typeof arg === 'object') {
Expand Down Expand Up @@ -59,6 +65,10 @@ function connect (up, cons) {
var client = dnode(function (remote, conn) {
up.conn = conn;

up.on('close', function () {
conn.end();
});

conn.on('up', function (r) {
up.remote = r;
up.queue.forEach(function (fn) { fn(up.remote, up.conn) });
Expand Down Expand Up @@ -101,7 +111,8 @@ function connect (up, cons) {
up.conn = null;
stream.destroy();

if (alive) setTimeout(reconnect, opts.reconnect);
if (alive && !up.closed) setTimeout(reconnect, opts.reconnect);
if (pinger) clearInterval(pinger);
alive = false;
};
var pinger = null;
Expand Down
59 changes: 59 additions & 0 deletions test/simple.js
@@ -0,0 +1,59 @@
var upnode = require('../');
var dnode = require('dnode');
var test = require('tap').test;

test('simple', function (t) {
t.plan(5);

var port = Math.floor(Math.random() * 5e4 + 1e4);
var up = upnode.connect(port);

var messages = [];
var iv = setInterval(function () {
up(function (remote) {
remote.time(function (t) {
messages.push(t);
});
});
}, 250);

setTimeout(on, 500);
setTimeout(function () {
off();
}, 1000);
setTimeout(function () {
on();
}, 2000);
setTimeout(function () {
var r0 = messages.slice(0,3).reduce(function (acc, x) {
if (x > acc.max) acc.max = x;
if (x < acc.min) acc.min = x;
return acc;
}, { min : Infinity, max : -Infinity });
t.ok(r0.max < Date.now());
t.ok(r0.max > Date.now() - 5000);
t.ok(r0.max - r0.min < 10);

t.ok(messages[0] < messages[messages.length-1]);
t.ok(messages.length > 5);

off();
up.close();
clearInterval(iv);
t.end();
}, 3000);

var server;
function on () {
server = dnode(function (client, conn) {
this.time = function (cb) { cb(Date.now()) };
});
server.use(upnode.ping);
server.listen(port);
}

function off () {
server.end();
server.close();
}
});

0 comments on commit 460a528

Please sign in to comment.