From b6a81a42975f3157d7d9064f56d4260473c0f679 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Sun, 22 Nov 2015 22:50:28 +0100 Subject: [PATCH] Use a .create_stream function, so other libraries can mock the stream if wanted Reference https://github.com/hdachev/fakeredis/pull/34 --- index.js | 12 +++++------- test/connection.spec.js | 19 ++++++++++++++++--- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/index.js b/index.js index a1c7d4d538..422bc41965 100644 --- a/index.js +++ b/index.js @@ -88,13 +88,14 @@ function RedisClient (options) { this.options = options; // Init parser once per instance this.init_parser(); - self.stream = net.createConnection(cnx_options); - self.install_stream_listeners(); + self.create_stream(); } util.inherits(RedisClient, events.EventEmitter); -RedisClient.prototype.install_stream_listeners = function () { +// Attention: the function name "create_stream" should not be changed, as other libraries need this to mock the stream (e.g. fakeredis) +RedisClient.prototype.create_stream = function () { var self = this; + this.stream = net.createConnection(this.connection_option); if (this.options.connect_timeout) { this.stream.setTimeout(this.connect_timeout, function () { @@ -479,10 +480,7 @@ var retry_connection = function (self) { self.retry_totaltime += self.retry_delay; self.attempts += 1; self.retry_delay = Math.round(self.retry_delay * self.retry_backoff); - - self.stream = net.createConnection(self.connection_option); - self.install_stream_listeners(); - + self.create_stream(); self.retry_timer = null; }; diff --git a/test/connection.spec.js b/test/connection.spec.js index 259c616a35..38fb705aa3 100644 --- a/test/connection.spec.js +++ b/test/connection.spec.js @@ -320,9 +320,22 @@ describe("connection tests", function () { }); }); - it("works with missing options object for new redis instances", function () { - // This is needed for libraries that have their own createClient function like fakeredis - client = new redis.RedisClient({ on: function () {}}); + it("fake the stream to mock redis", function () { + // This is needed for libraries that want to mock the stream like fakeredis + var temp = redis.RedisClient.prototype.create_stream; + var create_stream_string = String(temp); + redis.RedisClient.prototype.create_stream = function () { + this.connected = true; + this.ready = true; + }; + client = new redis.RedisClient(); + assert.strictEqual(client.stream, undefined); + assert.strictEqual(client.ready, true); + assert.strictEqual(client.connected, true); + client.end = function () {}; + assert(create_stream_string !== String(redis.RedisClient.prototype.create_stream)); + redis.RedisClient.prototype.create_stream = temp; + assert(create_stream_string === String(redis.RedisClient.prototype.create_stream)); }); it("throws on strange connection info", function () {