1
0
mirror of https://github.com/redis/node-redis.git synced 2025-08-04 15:02:09 +03:00

test fixup

This commit is contained in:
Ruben Bridgewater
2017-05-06 08:16:19 +02:00
parent f1a7bcd735
commit b2613b2270
106 changed files with 2900 additions and 2967 deletions

View File

@@ -1,38 +1,34 @@
'use strict' 'use strict'
var Buffer = require('safe-buffer').Buffer const Buffer = require('safe-buffer').Buffer
var path = require('path') const path = require('path')
var RedisProcess = require('../test/lib/redis-process') const RedisProcess = require('../test/lib/redis-process')
var rp let rp
var clientNr = 0 let clientNr = 0
var redis = require('../index') const redis = require('../index')
var totalTime = 0 let totalTime = 0
var metrics = require('metrics') const metrics = require('metrics')
var tests = [] const tests = []
// var bluebird = require('bluebird');
// bluebird.promisifyAll(redis.RedisClient.prototype);
// bluebird.promisifyAll(redis.Multi.prototype);
function returnArg (name, def) { function returnArg (name, def) {
var matches = process.argv.filter(function (entry) { const matches = process.argv.filter((entry) => {
return entry.indexOf(name + '=') === 0 return entry.indexOf(`${name}=`) === 0
}) })
if (matches.length) { if (matches.length) {
return matches[0].substr(name.length + 1) return matches[0].substr(name.length + 1)
} }
return def return def
} }
var numClients = returnArg('clients', 1) const numClients = returnArg('clients', 1)
var runTime = returnArg('time', 2500) // ms const runTime = returnArg('time', 2500) // ms
var pipeline = returnArg('pipeline', 1) // number of concurrent commands const pipeline = returnArg('pipeline', 1) // number of concurrent commands
var versionsLogged = false let versionsLogged = false
var clientOptions = { const clientOptions = {
path: returnArg('socket') // '/tmp/redis.sock' path: returnArg('socket') // '/tmp/redis.sock'
} }
var smallStr, largeStr, smallBuf, largeBuf, veryLargeStr, veryLargeBuf, mgetArray
function lpad (input, len, chr) { function lpad (input, len, chr) {
var str = input.toString() let str = input.toString()
chr = chr || ' ' chr = chr || ' '
while (str.length < len) { while (str.length < len) {
str = chr + str str = chr + str
@@ -41,8 +37,8 @@ function lpad (input, len, chr) {
} }
metrics.Histogram.prototype.printLine = function () { metrics.Histogram.prototype.printLine = function () {
var obj = this.printObj() const obj = this.printObj()
return lpad((obj.mean / 1e6).toFixed(2), 6) + '/' + lpad((obj.max / 1e6).toFixed(2), 6) return `${lpad((obj.mean / 1e6).toFixed(2), 6)}/${lpad((obj.max / 1e6).toFixed(2), 6)}`
} }
function Test (args) { function Test (args) {
@@ -66,7 +62,7 @@ function Test (args) {
} }
Test.prototype.run = function (callback) { Test.prototype.run = function (callback) {
var i let i
this.callback = callback this.callback = callback
for (i = 0; i < numClients; i++) { for (i = 0; i < numClients; i++) {
this.newClient(i) this.newClient(i)
@@ -74,24 +70,22 @@ Test.prototype.run = function (callback) {
} }
Test.prototype.newClient = function (id) { Test.prototype.newClient = function (id) {
var self = this const self = this
var newClient const newClient = redis.createClient(this.clientOptions)
newClient = redis.createClient(this.clientOptions)
newClient.createTime = Date.now() newClient.createTime = Date.now()
newClient.on('connect', function () { newClient.on('connect', () => {
self.connectLatency.update(Date.now() - newClient.createTime) self.connectLatency.update(Date.now() - newClient.createTime)
}) })
newClient.on('ready', function () { newClient.on('ready', () => {
if (!versionsLogged) { if (!versionsLogged) {
console.log( console.log([
'clients: ' + numClients + `clients: ${numClients}`,
', NodeJS: ' + process.versions.node + `NodeJS: ${process.versions.node}`,
', Redis: ' + newClient.serverInfo.redis_version + `Redis: ${newClient.serverInfo.redis_version}`,
', connected by: ' + (clientOptions.path ? 'socket' : 'tcp') `connected by: ${clientOptions.path ? 'socket' : 'tcp'}`
) ].join(', '))
versionsLogged = true versionsLogged = true
} }
self.readyLatency.update(Date.now() - newClient.createTime) self.readyLatency.update(Date.now() - newClient.createTime)
@@ -102,7 +96,7 @@ Test.prototype.newClient = function (id) {
}) })
// If no redis server is running, start one // If no redis server is running, start one
newClient.on('error', function (err) { newClient.on('error', (err) => {
if (err.code === 'CONNECTION_BROKEN') { if (err.code === 'CONNECTION_BROKEN') {
throw err throw err
} }
@@ -110,8 +104,8 @@ Test.prototype.newClient = function (id) {
return return
} }
rp = true rp = true
var conf = '../test/conf/redis.conf' const conf = '../test/conf/redis.conf'
RedisProcess.start(function (err, Rp) { RedisProcess.start((err, Rp) => {
if (err) { if (err) {
throw err throw err
} }
@@ -123,13 +117,13 @@ Test.prototype.newClient = function (id) {
} }
Test.prototype.onClientsReady = function () { Test.prototype.onClientsReady = function () {
process.stdout.write(lpad(this.args.descr, 13) + ', ' + (this.args.batch ? lpad('batch ' + this.args.batch, 9) : lpad(this.args.pipeline, 9)) + '/' + this.clientsReady + ' ') process.stdout.write(`${lpad(this.args.descr, 13) }, ${this.args.batch ? lpad(`batch ${this.args.batch}`, 9) : lpad(this.args.pipeline, 9) }/${this.clientsReady} `)
this.testStart = Date.now() this.testStart = Date.now()
this.fillPipeline() this.fillPipeline()
} }
Test.prototype.fillPipeline = function () { Test.prototype.fillPipeline = function () {
var pipeline = this.commandsSent - this.commandsCompleted let pipeline = this.commandsSent - this.commandsCompleted
if (this.testStart < Date.now() - runTime) { if (this.testStart < Date.now() - runTime) {
if (this.ended) { if (this.ended) {
@@ -153,18 +147,18 @@ Test.prototype.fillPipeline = function () {
} }
Test.prototype.batch = function () { Test.prototype.batch = function () {
var self = this const self = this
var curClient = clientNr++ % this.clients.length const curClient = clientNr++ % this.clients.length
var start = process.hrtime() const start = process.hrtime()
var i = 0 let i = 0
var batch = this.clients[curClient].batch() const batch = this.clients[curClient].batch()
while (i++ < this.batchPipeline) { while (i++ < this.batchPipeline) {
this.commandsSent++ this.commandsSent++
batch[this.args.command](this.args.args) batch[this.args.command](this.args.args)
} }
batch.exec(function (err, res) { batch.exec((err, res) => {
if (err) { if (err) {
throw err throw err
} }
@@ -175,11 +169,11 @@ Test.prototype.batch = function () {
} }
Test.prototype.stopClients = function () { Test.prototype.stopClients = function () {
var self = this const self = this
this.clients.forEach(function (client, pos) { this.clients.forEach((client, pos) => {
if (pos === self.clients.length - 1) { if (pos === self.clients.length - 1) {
client.quit(function (err, res) { client.quit((err, res) => {
if (err) throw err if (err) throw err
self.callback() self.callback()
}) })
@@ -190,11 +184,11 @@ Test.prototype.stopClients = function () {
} }
Test.prototype.sendNext = function () { Test.prototype.sendNext = function () {
var self = this const self = this
var curClient = this.commandsSent % this.clients.length const curClient = this.commandsSent % this.clients.length
var start = process.hrtime() const start = process.hrtime()
this.clients[curClient][this.args.command](this.args.args, function (err, res) { this.clients[curClient][this.args.command](this.args.args, (err, res) => {
if (err) { if (err) {
throw err throw err
} }
@@ -205,20 +199,22 @@ Test.prototype.sendNext = function () {
} }
Test.prototype.printStats = function () { Test.prototype.printStats = function () {
var duration = Date.now() - this.testStart const duration = Date.now() - this.testStart
totalTime += duration totalTime += duration
console.log('avg/max: ' + this.commandLatency.printLine() + lpad(duration, 5) + 'ms total, ' + console.log([
lpad(Math.round(this.commandsCompleted / (duration / 1000)), 7) + ' ops/sec') `avg/max: ${this.commandLatency.printLine()}${lpad(duration, 5)}ms total`,
`${lpad(Math.round(this.commandsCompleted / (duration / 1000)), 7)} ops/sec`
].join(','))
} }
smallStr = '1234' const smallStr = '1234'
smallBuf = Buffer.from(smallStr) const smallBuf = Buffer.from(smallStr)
largeStr = (new Array(4096 + 1).join('-')) const largeStr = (new Array(4096 + 1).join('-'))
largeBuf = Buffer.from(largeStr) const largeBuf = Buffer.from(largeStr)
veryLargeStr = (new Array((4 * 1024 * 1024) + 1).join('-')) const veryLargeStr = (new Array((4 * 1024 * 1024) + 1).join('-'))
veryLargeBuf = Buffer.from(veryLargeStr) const veryLargeBuf = Buffer.from(veryLargeStr)
mgetArray = (new Array(1025)).join('fooRand000000000001;').split(';') const mgetArray = (new Array(1025)).join('fooRand000000000001;').split(';')
tests.push(new Test({descr: 'PING', command: 'ping', args: []})) tests.push(new Test({descr: 'PING', command: 'ping', args: []}))
tests.push(new Test({descr: 'PING', command: 'ping', args: [], batch: 50})) tests.push(new Test({descr: 'PING', command: 'ping', args: [], batch: 50}))
@@ -278,14 +274,14 @@ tests.push(new Test({descr: 'MGET 4MiB buf', command: 'mget', args: mgetArray, c
tests.push(new Test({descr: 'MGET 4MiB buf', command: 'mget', args: mgetArray, batch: 20, clientOptions: {returnBuffers: true}})) tests.push(new Test({descr: 'MGET 4MiB buf', command: 'mget', args: mgetArray, batch: 20, clientOptions: {returnBuffers: true}}))
function next () { function next () {
var test = tests.shift() const test = tests.shift()
if (test) { if (test) {
test.run(function () { test.run(() => {
next() next()
}) })
} else if (rp) { } else if (rp) {
// Stop the redis process if started by the benchmark // Stop the redis process if started by the benchmark
rp.stop(function () { rp.stop(() => {
rp = undefined rp = undefined
next() next()
}) })

View File

@@ -14,6 +14,7 @@ Breaking Changes
- Removed `maxAttempts` (max_attempts) option - Removed `maxAttempts` (max_attempts) option
- Removed `socketNoDelay` (socket_no_delay) option - Removed `socketNoDelay` (socket_no_delay) option
- Removed `Redis.print` helper function - Removed `Redis.print` helper function
- Removed backpressure indicator from function return value
- Changed return value of `(p)(un)subscribe` - Changed return value of `(p)(un)subscribe`
- Return an array with the number of current subscribed channels and an array with all affected channels - Return an array with the number of current subscribed channels and an array with all affected channels
- Changed `connectTimeout` (connect_timeout) option - Changed `connectTimeout` (connect_timeout) option

View File

@@ -1,6 +1,6 @@
'use strict' 'use strict'
var redis = require('redis') const redis = require('redis')
// The client stashes the password and will re-authenticate on every connect. // The client stashes the password and will re-authenticate on every connect.
redis.createClient({ redis.createClient({
password: 'some pass' password: 'some pass'

View File

@@ -1,14 +1,14 @@
'use strict' 'use strict'
var redis = require('../index') const redis = require('../index')
var client = redis.createClient() const client = redis.createClient()
client.eval('return 100.5', 0, function (err, res) { client.eval('return 100.5', 0, (err, res) => {
console.dir(err) console.dir(err)
console.dir(res) console.dir(res)
}) })
client.eval([ 'return 100.5', 0 ], function (err, res) { client.eval([ 'return 100.5', 0 ], (err, res) => {
console.dir(err) console.dir(err)
console.dir(res) console.dir(res)
}) })

View File

@@ -1,18 +1,18 @@
'use strict' 'use strict'
var redis = require('redis') const redis = require('redis')
var client = redis.createClient() const client = redis.createClient()
// Extend the RedisClient prototype to add a custom method // Extend the RedisClient prototype to add a custom method
// This one converts the results from 'INFO' into a JavaScript Object // This one converts the results from 'INFO' into a JavaScript Object
redis.RedisClient.prototype.parseInfo = function (callback) { redis.RedisClient.prototype.parseInfo = function (callback) {
this.info(function (err, res) { this.info((err, res) => {
if (err) throw err if (err) throw err
var lines = res.toString().split('\r\n').sort() const lines = res.toString().split('\r\n').sort()
var obj = {} const obj = {}
lines.forEach(function (line) { lines.forEach((line) => {
var parts = line.split(':') const parts = line.split(':')
if (parts[1]) { if (parts[1]) {
obj[parts[0]] = parts[1] obj[parts[0]] = parts[1]
} }
@@ -21,7 +21,7 @@ redis.RedisClient.prototype.parseInfo = function (callback) {
}) })
} }
client.parseInfo(function (info) { client.parseInfo((info) => {
console.dir(info) console.dir(info)
client.quit() client.quit()
}) })

View File

@@ -2,32 +2,32 @@
// Read a file from disk, store it in Redis, then read it back from Redis. // Read a file from disk, store it in Redis, then read it back from Redis.
var redis = require('redis') const redis = require('redis')
var client = redis.createClient({ const client = redis.createClient({
returnBuffers: true returnBuffers: true
}) })
var fs = require('fs') const fs = require('fs')
var assert = require('assert') const assert = require('assert')
var filename = 'grumpyCat.jpg' const filename = 'grumpyCat.jpg'
// Get the file I use for testing like this: // Get the file I use for testing like this:
// curl http://media4.popsugar-assets.com/files/2014/08/08/878/n/1922507/caef16ec354ca23b_thumb_temp_cover_file32304521407524949.xxxlarge/i/Funny-Cat-GIFs.jpg -o grumpyCat.jpg // curl http://media4.popsugar-assets.com/files/2014/08/08/878/n/1922507/caef16ec354ca23b_thumb_temp_cover_file32304521407524949.xxxlarge/i/Funny-Cat-GIFs.jpg -o grumpyCat.jpg
// or just use your own file. // or just use your own file.
// Read a file from fs, store it in Redis, get it back from Redis, write it back to fs. // Read a file from fs, store it in Redis, get it back from Redis, write it back to fs.
fs.readFile(filename, function (err, data) { fs.readFile(filename, (err, data) => {
if (err) throw err if (err) throw err
console.log('Read ' + data.length + ' bytes from filesystem.') console.log(`Read ${data.length} bytes from filesystem.`)
client.set(filename, data, console.log) // set entire file client.set(filename, data, console.log) // set entire file
client.get(filename, function (err, reply) { // get entire file client.get(filename, (err, reply) => { // get entire file
if (err) { if (err) {
console.log('Get error: ' + err) console.log(`Get error: ${err}`)
} else { } else {
assert.strictEqual(data.inspect(), reply.inspect()) assert.strictEqual(data.inspect(), reply.inspect())
fs.writeFile('duplicate_' + filename, reply, function (err) { fs.writeFile(`duplicate_${filename}`, reply, (err) => {
if (err) { if (err) {
console.log('Error on write: ' + err) console.log(`Error on write: ${err}`)
} else { } else {
console.log('File written.') console.log('File written.')
} }

View File

@@ -1,8 +1,8 @@
'use strict' 'use strict'
var client = require('redis').createClient() const client = require('redis').createClient()
client.mget(['sessions started', 'sessions started', 'foo'], function (err, res) { client.mget(['sessions started', 'sessions started', 'foo'], (err, res) => {
if (err) throw err if (err) throw err
console.dir(res) console.dir(res)
}) })

View File

@@ -1,13 +1,13 @@
'use strict' 'use strict'
var client = require('../index').createClient() const client = require('../index').createClient()
var util = require('util') const util = require('util')
client.monitor(function (err, res) { client.monitor((err, res) => {
if (err) throw err if (err) throw err
console.log('Entering monitoring mode.') console.log('Entering monitoring mode.')
}) })
client.on('monitor', function (time, args) { client.on('monitor', (time, args) => {
console.log(time + ': ' + util.inspect(args)) console.log(`${time }: ${util.inspect(args)}`)
}) })

View File

@@ -1,14 +1,14 @@
'use strict' 'use strict'
var redis = require('redis') const redis = require('redis')
var client = redis.createClient() const client = redis.createClient()
var setSize = 20 let setSize = 20
client.sadd('bigset', 'a member') client.sadd('bigset', 'a member')
client.sadd('bigset', 'another member') client.sadd('bigset', 'another member')
while (setSize > 0) { while (setSize > 0) {
client.sadd('bigset', 'member ' + setSize) client.sadd('bigset', `member ${setSize}`)
setSize -= 1 setSize -= 1
} }
@@ -16,23 +16,23 @@ while (setSize > 0) {
client.multi() client.multi()
.scard('bigset') .scard('bigset')
.smembers('bigset') .smembers('bigset')
.keys('*', function (err, replies) { .keys('*', (err, replies) => {
if (err) throw err if (err) throw err
client.mget(replies, console.log) client.mget(replies, console.log)
}) })
.dbsize() .dbsize()
.exec(function (err, replies) { .exec((err, replies) => {
if (err) throw err if (err) throw err
console.log('MULTI got ' + replies.length + ' replies') console.log(`MULTI got ${replies.length} replies`)
replies.forEach(function (reply, index) { replies.forEach((reply, index) => {
console.log('Reply ' + index + ': ' + reply.toString()) console.log(`Reply ${index}: ${reply.toString()}`)
}) })
}) })
client.mset('incr thing', 100, 'incr other thing', 1, console.log) client.mset('incr thing', 100, 'incr other thing', 1, console.log)
// start a separate multi command queue // start a separate multi command queue
var multi = client.multi() const multi = client.multi()
multi.incr('incr thing', console.log) multi.incr('incr thing', console.log)
multi.incr('incr other thing', console.log) multi.incr('incr other thing', console.log)
@@ -40,13 +40,13 @@ multi.incr('incr other thing', console.log)
client.get('incr thing', console.log) // 100 client.get('incr thing', console.log) // 100
// drains multi queue and runs atomically // drains multi queue and runs atomically
multi.exec(function (err, replies) { multi.exec((err, replies) => {
if (err) throw err if (err) throw err
console.log(replies) // 101, 2 console.log(replies) // 101, 2
}) })
// you can re-run the same transaction if you like // you can re-run the same transaction if you like
multi.exec(function (err, replies) { multi.exec((err, replies) => {
if (err) throw err if (err) throw err
console.log(replies) // 102, 3 console.log(replies) // 102, 3
client.quit() client.quit()

View File

@@ -1,10 +1,10 @@
'use strict' 'use strict'
var redis = require('redis') const redis = require('redis')
var client = redis.createClient() const client = redis.createClient()
// start a separate command queue for multi // start a separate command queue for multi
var multi = client.multi() const multi = client.multi()
multi.incr('incr thing', console.log) multi.incr('incr thing', console.log)
multi.incr('incr other thing', console.log) multi.incr('incr other thing', console.log)
@@ -12,13 +12,13 @@ multi.incr('incr other thing', console.log)
client.mset('incr thing', 100, 'incr other thing', 1, console.log) client.mset('incr thing', 100, 'incr other thing', 1, console.log)
// drains multi queue and runs atomically // drains multi queue and runs atomically
multi.exec(function (err, replies) { multi.exec((err, replies) => {
if (err) throw err if (err) throw err
console.log(replies) // 101, 2 console.log(replies) // 101, 2
}) })
// you can re-run the same transaction if you like // you can re-run the same transaction if you like
multi.exec(function (err, replies) { multi.exec((err, replies) => {
if (err) throw err if (err) throw err
console.log(replies) // 102, 3 console.log(replies) // 102, 3
client.quit() client.quit()
@@ -28,7 +28,7 @@ client.multi([
['mget', 'multifoo', 'multibar', console.log], ['mget', 'multifoo', 'multibar', console.log],
['incr', 'multifoo'], ['incr', 'multifoo'],
['incr', 'multibar'] ['incr', 'multibar']
]).exec(function (err, replies) { ]).exec((err, replies) => {
if (err) throw err if (err) throw err
console.log(replies.toString()) console.log(replies.toString())
}) })

View File

@@ -1,29 +1,29 @@
'use strict' 'use strict'
var redis = require('redis') const redis = require('redis')
var client1 = redis.createClient() const client1 = redis.createClient()
var client2 = redis.createClient() const client2 = redis.createClient()
var client3 = redis.createClient() const client3 = redis.createClient()
var client4 = redis.createClient() const client4 = redis.createClient()
var msgCount = 0 let msgCount = 0
client1.on('psubscribe', function (pattern, count) { client1.on('psubscribe', (pattern, count) => {
console.log('client1 psubscribed to ' + pattern + ', ' + count + ' total subscriptions') console.log(`client1 psubscribed to ${pattern}, ${count} total subscriptions`)
client2.publish('channeltwo', 'Me!') client2.publish('channeltwo', 'Me!')
client3.publish('channelthree', 'Me too!') client3.publish('channelthree', 'Me too!')
client4.publish('channelfour', 'And me too!') client4.publish('channelfour', 'And me too!')
}) })
client1.on('punsubscribe', function (pattern, count) { client1.on('punsubscribe', (pattern, count) => {
console.log('client1 punsubscribed from ' + pattern + ', ' + count + ' total subscriptions') console.log(`client1 punsubscribed from ${pattern}, ${count} total subscriptions`)
client4.end() client4.end()
client3.end() client3.end()
client2.end() client2.end()
client1.end() client1.end()
}) })
client1.on('pmessage', function (pattern, channel, message) { client1.on('pmessage', (pattern, channel, message) => {
console.log('(' + pattern + ') client1 received message on ' + channel + ': ' + message) console.log(`(${pattern}) client1 received message on ${channel}: ${message}`)
msgCount += 1 msgCount += 1
if (msgCount === 3) { if (msgCount === 3) {
client1.punsubscribe() client1.punsubscribe()

View File

@@ -1,13 +1,13 @@
'use strict' 'use strict'
var redis = require('redis') const redis = require('redis')
var client1 = redis.createClient() const client1 = redis.createClient()
var msgCount = 0 let msgCount = 0
var client2 = redis.createClient() const client2 = redis.createClient()
// Most clients probably don't do much on 'subscribe'. This example uses it to coordinate things within one program. // Most clients probably don't do much on 'subscribe'. This example uses it to coordinate things within one program.
client1.on('subscribe', function (channel, count) { client1.on('subscribe', (channel, count) => {
console.log('client1 subscribed to ' + channel + ', ' + count + ' total subscriptions') console.log(`client1 subscribed to ${channel}, ${count} total subscriptions`)
if (count === 2) { if (count === 2) {
client2.publish('a nice channel', 'I am sending a message.') client2.publish('a nice channel', 'I am sending a message.')
client2.publish('another one', 'I am sending a second message.') client2.publish('another one', 'I am sending a second message.')
@@ -15,28 +15,28 @@ client1.on('subscribe', function (channel, count) {
} }
}) })
client1.on('unsubscribe', function (channel, count) { client1.on('unsubscribe', (channel, count) => {
console.log('client1 unsubscribed from ' + channel + ', ' + count + ' total subscriptions') console.log(`client1 unsubscribed from ${channel}, ${count} total subscriptions`)
if (count === 0) { if (count === 0) {
client2.end() client2.end()
client1.end() client1.end()
} }
}) })
client1.on('message', function (channel, message) { client1.on('message', (channel, message) => {
console.log('client1 channel ' + channel + ': ' + message) console.log(`client1 channel ${channel}: ${message}`)
msgCount += 1 msgCount += 1
if (msgCount === 3) { if (msgCount === 3) {
client1.unsubscribe() client1.unsubscribe()
} }
}) })
client1.on('ready', function () { client1.on('ready', () => {
// if you need auth, do it here // if you need auth, do it here
client1.incr('did a thing') client1.incr('did a thing')
client1.subscribe('a nice channel', 'another one') client1.subscribe('a nice channel', 'another one')
}) })
client2.on('ready', function () { client2.on('ready', () => {
// if you need auth, do it here // if you need auth, do it here
}) })

View File

@@ -1,22 +1,22 @@
'use strict' 'use strict'
var redis = require('redis') const redis = require('redis')
var client = redis.createClient() const client = redis.createClient()
var cursor = '0' let cursor = '0'
function scan () { function scan () {
client.scan( client.scan(
cursor, cursor,
'MATCH', 'q:job:*', 'MATCH', 'q:job:*',
'COUNT', '10', 'COUNT', '10',
function (err, res) { (err, res) => {
if (err) throw err if (err) throw err
// Update the cursor position for the next scan // Update the cursor position for the next scan
cursor = res[0] cursor = res[0]
// get the SCAN result for this iteration // get the SCAN result for this iteration
var keys = res[1] const keys = res[1]
// Remember: more or less than COUNT or no keys may be returned // Remember: more or less than COUNT or no keys may be returned
// See http://redis.io/commands/scan#the-count-option // See http://redis.io/commands/scan#the-count-option

View File

@@ -1,27 +1,27 @@
'use strict' 'use strict'
var redis = require('redis') const redis = require('redis')
var client = redis.createClient() const client = redis.createClient()
client.on('error', function (err) { client.on('error', (err) => {
console.log('error event - ' + client.host + ':' + client.port + ' - ' + err) console.log(`error event - ${client.host}:${client.port} - ${err}`)
}) })
client.set('string key', 'string val', console.log) client.set('string key', 'string val', console.log)
client.hset('hash key', 'hashtest 1', 'some value', console.log) client.hset('hash key', 'hashtest 1', 'some value', console.log)
client.hset(['hash key', 'hashtest 2', 'some other value'], console.log) client.hset(['hash key', 'hashtest 2', 'some other value'], console.log)
client.hkeys('hash key', function (err, replies) { client.hkeys('hash key', (err, replies) => {
if (err) { if (err) {
return console.error('error response - ' + err) return console.error(`error response - ${err}`)
} }
console.log(replies.length + ' replies:') console.log(`${replies.length } replies:`)
replies.forEach(function (reply, i) { replies.forEach((reply, i) => {
console.log(' ' + i + ': ' + reply) console.log(` ${i}: ${reply}`)
}) })
}) })
client.quit(function (err, res) { client.quit((err, res) => {
if (err) throw err if (err) throw err
console.log('Exiting from quit command.') console.log('Exiting from quit command.')
}) })

View File

@@ -1,7 +1,7 @@
'use strict' 'use strict'
var redis = require('redis') const redis = require('redis')
var client = redis.createClient() const client = redis.createClient()
client.sadd('mylist', 1) client.sadd('mylist', 1)
client.sadd('mylist', 2) client.sadd('mylist', 2)

View File

@@ -3,14 +3,14 @@
// Sending commands in response to other commands. // Sending commands in response to other commands.
// This example runs 'type' against every key in the database // This example runs 'type' against every key in the database
// //
var client = require('redis').createClient() const client = require('redis').createClient()
client.keys('*', function (err, keys) { client.keys('*', (err, keys) => {
if (err) throw err if (err) throw err
keys.forEach(function (key, pos) { keys.forEach((key, pos) => {
client.type(key, function (err, keytype) { client.type(key, (err, keytype) => {
if (err) throw err if (err) throw err
console.log(key + ' is ' + keytype) console.log(`${key } is ${keytype}`)
if (pos === (keys.length - 1)) { if (pos === (keys.length - 1)) {
client.quit() client.quit()
} }

View File

@@ -1,14 +1,14 @@
'use strict' 'use strict'
var client = require('redis').createClient() const client = require('redis').createClient()
// build a map of all keys and their types // build a map of all keys and their types
client.keys('*', function (err, allKeys) { client.keys('*', (err, allKeys) => {
if (err) throw err if (err) throw err
var keyTypes = {} const keyTypes = {}
allKeys.forEach(function (key, pos) { // use second arg of forEach to get pos allKeys.forEach((key, pos) => { // use second arg of forEach to get pos
client.type(key, function (err, type) { client.type(key, (err, type) => {
if (err) throw err if (err) throw err
keyTypes[key] = type keyTypes[key] = type
if (pos === allKeys.length - 1) { // callbacks all run in order if (pos === allKeys.length - 1) { // callbacks all run in order

View File

@@ -1,32 +1,32 @@
'use strict' 'use strict'
var redis = require('redis') const redis = require('redis')
var client = redis.createClient('/tmp/redis.sock') const client = redis.createClient('/tmp/redis.sock')
var profiler = require('v8-profiler') const profiler = require('v8-profiler')
client.on('connect', function () { client.on('connect', () => {
console.log('Got Unix socket connection.') console.log('Got Unix socket connection.')
}) })
client.on('error', function (err) { client.on('error', (err) => {
console.log(err.message) console.log(err.message)
}) })
client.set('space chars', 'space value') client.set('space chars', 'space value')
setInterval(function () { setInterval(() => {
client.get('space chars') client.get('space chars')
}, 100) }, 100)
function done () { function done () {
client.info(function (err, reply) { client.info((err, reply) => {
if (err) throw err if (err) throw err
console.log(reply.toString()) console.log(reply.toString())
client.quit() client.quit()
}) })
} }
setTimeout(function () { setTimeout(() => {
console.log('Taking snapshot.') console.log('Taking snapshot.')
profiler.takeSnapshot() profiler.takeSnapshot()
done() done()

View File

@@ -2,34 +2,34 @@
// A simple web server that generates dyanmic content based on responses from Redis // A simple web server that generates dyanmic content based on responses from Redis
var http = require('http') const http = require('http')
var redisClient = require('redis').createClient() const redisClient = require('redis').createClient()
http.createServer(function (request, response) { // The server http.createServer((request, response) => { // The server
response.writeHead(200, { response.writeHead(200, {
'Content-Type': 'text/plain' 'Content-Type': 'text/plain'
}) })
var redisInfo, totalRequests let redisInfo, totalRequests
redisClient.info(function (err, reply) { redisClient.info((err, reply) => {
if (err) throw err if (err) throw err
redisInfo = reply // stash response in outer scope redisInfo = reply // stash response in outer scope
}) })
redisClient.incr('requests', function (err, reply) { redisClient.incr('requests', (err, reply) => {
if (err) throw err if (err) throw err
totalRequests = reply // stash response in outer scope totalRequests = reply // stash response in outer scope
}) })
redisClient.hincrby('ip', request.connection.remoteAddress, 1) redisClient.hincrby('ip', request.connection.remoteAddress, 1)
redisClient.hgetall('ip', function (err, reply) { redisClient.hgetall('ip', (err, reply) => {
if (err) throw err if (err) throw err
// This is the last reply, so all of the previous replies must have completed already // This is the last reply, so all of the previous replies must have completed already
response.write('This page was generated after talking to redis.\n\n' + response.write(`${'This page was generated after talking to redis.\n\n' +
'Redis info:\n' + redisInfo + '\n' + 'Redis info:\n'}${redisInfo}\n` +
'Total requests: ' + totalRequests + '\n\n' + `Total requests: ${totalRequests}\n\n` +
'IP count: \n') `IP count: \n`)
Object.keys(reply).forEach(function (ip) { Object.keys(reply).forEach((ip) => {
response.write(' ' + ip + ': ' + reply[ip] + '\n') response.write(` ${ip}: ${reply[ip]}\n`)
}) })
response.end() response.end()
}) })

244
index.js
View File

@@ -1,19 +1,19 @@
'use strict' 'use strict'
var Buffer = require('safe-buffer').Buffer const Buffer = require('safe-buffer').Buffer
var net = require('net') const net = require('net')
var tls = require('tls') const tls = require('tls')
var util = require('util') const util = require('util')
var utils = require('./lib/utils') const utils = require('./lib/utils')
var Command = require('./lib/command') const Command = require('./lib/command')
var Queue = require('double-ended-queue') const Queue = require('double-ended-queue')
var errorClasses = require('./lib/customErrors') const errorClasses = require('./lib/customErrors')
var EventEmitter = require('events') const EventEmitter = require('events')
var Parser = require('redis-parser') const Parser = require('redis-parser')
var commands = require('redis-commands') const commands = require('redis-commands')
var debug = require('./lib/debug') const debug = require('./lib/debug')
var unifyOptions = require('./lib/createClient') const unifyOptions = require('./lib/createClient')
var SUBSCRIBE_COMMANDS = { const SUBSCRIBE_COMMANDS = {
subscribe: true, subscribe: true,
unsubscribe: true, unsubscribe: true,
psubscribe: true, psubscribe: true,
@@ -43,10 +43,10 @@ function RedisClient (options, stream) {
// Copy the options so they are not mutated // Copy the options so they are not mutated
options = utils.clone(options) options = utils.clone(options)
EventEmitter.call(this) EventEmitter.call(this)
var cnxOptions = {} const cnxOptions = {}
var self = this const self = this
/* istanbul ignore next: travis does not work with stunnel atm. Therefore the tls tests are skipped on travis */ /* istanbul ignore next: travis does not work with stunnel atm. Therefore the tls tests are skipped on travis */
for (var tlsOption in options.tls) { for (const tlsOption in options.tls) {
cnxOptions[tlsOption] = options.tls[tlsOption] cnxOptions[tlsOption] = options.tls[tlsOption]
// Copy the tls options into the general options to make sure the address is set right // Copy the tls options into the general options to make sure the address is set right
if (tlsOption === 'port' || tlsOption === 'host' || tlsOption === 'path' || tlsOption === 'family') { if (tlsOption === 'port' || tlsOption === 'host' || tlsOption === 'path' || tlsOption === 'family') {
@@ -65,7 +65,7 @@ function RedisClient (options, stream) {
cnxOptions.port = +options.port || 6379 cnxOptions.port = +options.port || 6379
cnxOptions.host = options.host || '127.0.0.1' cnxOptions.host = options.host || '127.0.0.1'
cnxOptions.family = (!options.family && net.isIP(cnxOptions.host)) || (options.family === 'IPv6' ? 6 : 4) cnxOptions.family = (!options.family && net.isIP(cnxOptions.host)) || (options.family === 'IPv6' ? 6 : 4)
this.address = cnxOptions.host + ':' + cnxOptions.port this.address = `${cnxOptions.host}:${cnxOptions.port}`
} }
this.connectionOptions = cnxOptions this.connectionOptions = cnxOptions
@@ -75,7 +75,7 @@ function RedisClient (options, stream) {
if (options.socketKeepalive === undefined) { if (options.socketKeepalive === undefined) {
options.socketKeepalive = true options.socketKeepalive = true
} }
for (var command in options.renameCommands) { for (const command in options.renameCommands) {
options.renameCommands[command.toLowerCase()] = options.renameCommands[command] options.renameCommands[command.toLowerCase()] = options.renameCommands[command]
} }
options.returnBuffers = !!options.returnBuffers options.returnBuffers = !!options.returnBuffers
@@ -131,14 +131,14 @@ RedisClient.connectionId = 0
function createParser (self) { function createParser (self) {
return new Parser({ return new Parser({
returnReply: function (data) { returnReply (data) {
self.returnReply(data) self.returnReply(data)
}, },
returnError: function (err) { returnError (err) {
// Return a ReplyError to indicate Redis returned an error // Return a ReplyError to indicate Redis returned an error
self.returnError(err) self.returnError(err)
}, },
returnFatalError: function (err) { returnFatalError (err) {
// Error out all fired commands. Otherwise they might rely on faulty data. We have to reconnect to get in a working state again // Error out all fired commands. Otherwise they might rely on faulty data. We have to reconnect to get in a working state again
// Note: the execution order is important. First flush and emit, then create the stream // Note: the execution order is important. First flush and emit, then create the stream
err.message += '. Please report this.' err.message += '. Please report this.'
@@ -168,7 +168,7 @@ function createParser (self) {
// Attention: the function name "createStream" should not be changed, as other libraries need this to mock the stream (e.g. fakeredis) // Attention: the function name "createStream" should not be changed, as other libraries need this to mock the stream (e.g. fakeredis)
RedisClient.prototype.createStream = function () { RedisClient.prototype.createStream = function () {
var self = this const self = this
// Init parser // Init parser
this.replyParser = createParser(this) this.replyParser = createParser(this)
@@ -195,7 +195,7 @@ RedisClient.prototype.createStream = function () {
} }
if (this.options.connectTimeout) { if (this.options.connectTimeout) {
this.stream.setTimeout(this.connectTimeout, function () { this.stream.setTimeout(this.connectTimeout, () => {
// Note: This is only tested if a internet connection is established // Note: This is only tested if a internet connection is established
self.retryTotaltime = self.connectTimeout self.retryTotaltime = self.connectTimeout
self.connectionGone('timeout') self.connectionGone('timeout')
@@ -203,34 +203,34 @@ RedisClient.prototype.createStream = function () {
} }
/* istanbul ignore next: travis does not work with stunnel atm. Therefore the tls tests are skipped on travis */ /* istanbul ignore next: travis does not work with stunnel atm. Therefore the tls tests are skipped on travis */
var connectEvent = this.options.tls ? 'secureConnect' : 'connect' const connectEvent = this.options.tls ? 'secureConnect' : 'connect'
this.stream.once(connectEvent, function () { this.stream.once(connectEvent, function () {
this.removeAllListeners('timeout') this.removeAllListeners('timeout')
self.timesConnected++ self.timesConnected++
self.onConnect() self.onConnect()
}) })
this.stream.on('data', function (bufferFromSocket) { this.stream.on('data', (bufferFromSocket) => {
// The bufferFromSocket.toString() has a significant impact on big chunks and therefore this should only be used if necessary // The bufferFromSocket.toString() has a significant impact on big chunks and therefore this should only be used if necessary
debug('Net read ' + self.address + ' id ' + self.connectionId) // + ': ' + bufferFromSocket.toString()); debug(`Net read ${self.address} id ${self.connectionId}`) // + ': ' + bufferFromSocket.toString());
self.replyParser.execute(bufferFromSocket) self.replyParser.execute(bufferFromSocket)
}) })
this.stream.on('error', function (err) { this.stream.on('error', (err) => {
self.onError(err) self.onError(err)
}) })
/* istanbul ignore next: difficult to test and not important as long as we keep this listener */ /* istanbul ignore next: difficult to test and not important as long as we keep this listener */
this.stream.on('clientError', function (err) { this.stream.on('clientError', (err) => {
debug('clientError occurred') debug('clientError occurred')
self.onError(err) self.onError(err)
}) })
this.stream.once('close', function (hadError) { this.stream.once('close', (hadError) => {
self.connectionGone('close') self.connectionGone('close')
}) })
this.stream.once('end', function () { this.stream.once('end', () => {
self.connectionGone('end') self.connectionGone('end')
}) })
@@ -261,10 +261,10 @@ RedisClient.prototype.initializeRetryVars = function () {
} }
RedisClient.prototype.warn = function (msg) { RedisClient.prototype.warn = function (msg) {
var self = this const self = this
// Warn on the next tick. Otherwise no event listener can be added // Warn on the next tick. Otherwise no event listener can be added
// for warnings that are emitted in the redis client constructor // for warnings that are emitted in the redis client constructor
process.nextTick(function () { process.nextTick(() => {
if (self.listeners('warning').length !== 0) { if (self.listeners('warning').length !== 0) {
self.emit('warning', msg) self.emit('warning', msg)
} else { } else {
@@ -276,9 +276,9 @@ RedisClient.prototype.warn = function (msg) {
// Flush provided queues, erroring any items with a callback first // Flush provided queues, erroring any items with a callback first
RedisClient.prototype.flushAndError = function (errorAttributes, options) { RedisClient.prototype.flushAndError = function (errorAttributes, options) {
options = options || {} options = options || {}
var aggregatedErrors = [] const aggregatedErrors = []
var queueNames = options.queues || ['commandQueue', 'offlineQueue'] // Flush the commandQueue first to keep the order intact const queueNames = options.queues || ['commandQueue', 'offlineQueue'] // Flush the commandQueue first to keep the order intact
for (var i = 0; i < queueNames.length; i++) { for (let i = 0; i < queueNames.length; i++) {
// If the command was fired it might have been processed so far // If the command was fired it might have been processed so far
if (queueNames[i] === 'commandQueue') { if (queueNames[i] === 'commandQueue') {
errorAttributes.message += ' It might have been processed.' errorAttributes.message += ' It might have been processed.'
@@ -286,8 +286,8 @@ RedisClient.prototype.flushAndError = function (errorAttributes, options) {
errorAttributes.message = errorAttributes.message.replace(' It might have been processed.', '') errorAttributes.message = errorAttributes.message.replace(' It might have been processed.', '')
} }
// Don't flush everything from the queue // Don't flush everything from the queue
for (var commandObj = this[queueNames[i]].shift(); commandObj; commandObj = this[queueNames[i]].shift()) { for (let commandObj = this[queueNames[i]].shift(); commandObj; commandObj = this[queueNames[i]].shift()) {
var err = new errorClasses.AbortError(errorAttributes) const err = new errorClasses.AbortError(errorAttributes)
if (commandObj.error) { if (commandObj.error) {
err.stack = err.stack + commandObj.error.stack.replace(/^Error.*?\n/, '\n') err.stack = err.stack + commandObj.error.stack.replace(/^Error.*?\n/, '\n')
} }
@@ -307,7 +307,7 @@ RedisClient.prototype.flushAndError = function (errorAttributes, options) {
} }
// Currently this would be a breaking change, therefore it's only emitted in debugMode // Currently this would be a breaking change, therefore it's only emitted in debugMode
if (exports.debugMode && aggregatedErrors.length) { if (exports.debugMode && aggregatedErrors.length) {
var error let error
if (aggregatedErrors.length === 1) { if (aggregatedErrors.length === 1) {
error = aggregatedErrors[0] error = aggregatedErrors[0]
} else { } else {
@@ -324,7 +324,7 @@ RedisClient.prototype.onError = function (err) {
return return
} }
err.message = 'Redis connection to ' + this.address + ' failed - ' + err.message err.message = `Redis connection to ${this.address} failed - ${err.message}`
debug(err.message) debug(err.message)
this.connected = false this.connected = false
this.ready = false this.ready = false
@@ -339,7 +339,7 @@ RedisClient.prototype.onError = function (err) {
} }
RedisClient.prototype.onConnect = function () { RedisClient.prototype.onConnect = function () {
debug('Stream connected ' + this.address + ' id ' + this.connectionId) debug(`Stream connected ${this.address} id ${this.connectionId}`)
this.connected = true this.connected = true
this.ready = false this.ready = false
@@ -358,9 +358,9 @@ RedisClient.prototype.onConnect = function () {
} }
RedisClient.prototype.onReady = function () { RedisClient.prototype.onReady = function () {
var self = this const self = this
debug('onReady called ' + this.address + ' id ' + this.connectionId) debug(`onReady called ${this.address} id ${this.connectionId}`)
this.ready = true this.ready = true
this.cork = function () { this.cork = function () {
@@ -386,12 +386,12 @@ RedisClient.prototype.onReady = function () {
if (this.monitoring) { // Monitor has to be fired before pub sub commands if (this.monitoring) { // Monitor has to be fired before pub sub commands
this.internalSendCommand(new Command('monitor', [])) this.internalSendCommand(new Command('monitor', []))
} }
var callbackCount = Object.keys(this.subscriptionSet).length const callbackCount = Object.keys(this.subscriptionSet).length
if (!this.options.disableResubscribing && callbackCount) { if (!this.options.disableResubscribing && callbackCount) {
debug('Sending pub/sub onReady commands') debug('Sending pub/sub onReady commands')
for (var key in this.subscriptionSet) { for (const key in this.subscriptionSet) {
var command = key.slice(0, key.indexOf('_')) const command = key.slice(0, key.indexOf('_'))
var args = this.subscriptionSet[key] const args = this.subscriptionSet[key]
this[command]([args]) this[command]([args])
} }
} }
@@ -405,7 +405,7 @@ RedisClient.prototype.onInfoCmd = function (err, res) {
this.onReady() this.onReady()
return return
} }
err.message = 'Ready check failed: ' + err.message err.message = `Ready check failed: ${err.message}`
this.emit('error', err) this.emit('error', err)
return return
} }
@@ -429,41 +429,41 @@ RedisClient.prototype.onInfoCmd = function (err, res) {
} }
} }
var retryTime = +this.serverInfo.loading_eta_seconds * 1000 let retryTime = +this.serverInfo.loading_eta_seconds * 1000
if (retryTime > 1000) { if (retryTime > 1000) {
retryTime = 1000 retryTime = 1000
} }
debug('Redis server still loading, trying again in ' + retryTime) debug(`Redis server still loading, trying again in ${retryTime}`)
setTimeout(function (self) { setTimeout((self) => {
self.readyCheck() self.readyCheck()
}, retryTime, this) }, retryTime, this)
} }
RedisClient.prototype.readyCheck = function () { RedisClient.prototype.readyCheck = function () {
var self = this const self = this
debug('Checking server ready state...') debug('Checking server ready state...')
// Always fire this info command as first command even if other commands are already queued up // Always fire this info command as first command even if other commands are already queued up
this.ready = true this.ready = true
this.info(function (err, res) { this.info((err, res) => {
self.onInfoCmd(err, res) self.onInfoCmd(err, res)
}) })
this.ready = false this.ready = false
} }
RedisClient.prototype.sendOfflineQueue = function () { RedisClient.prototype.sendOfflineQueue = function () {
for (var commandObj = this.offlineQueue.shift(); commandObj; commandObj = this.offlineQueue.shift()) { for (let commandObj = this.offlineQueue.shift(); commandObj; commandObj = this.offlineQueue.shift()) {
debug('Sending offline command: ' + commandObj.command) debug(`Sending offline command: ${commandObj.command}`)
this.internalSendCommand(commandObj) this.internalSendCommand(commandObj)
} }
} }
var retryConnection = function (self, error) { const retryConnection = function (self, error) {
debug('Retrying connection...') debug('Retrying connection...')
var reconnectParams = { const reconnectParams = {
delay: self.retryDelay, delay: self.retryDelay,
attempt: self.attempts, attempt: self.attempts,
error: error, error,
totalRetryTime: self.retryTotaltime, totalRetryTime: self.retryTotaltime,
timesConnected: self.timesConnected timesConnected: self.timesConnected
} }
@@ -483,7 +483,7 @@ RedisClient.prototype.connectionGone = function (why, error) {
} }
error = error || null error = error || null
debug('Redis connection is gone from ' + why + ' event.') debug(`Redis connection is gone from ${why} event.`)
this.connected = false this.connected = false
this.ready = false this.ready = false
// Deactivate cork to work with the offline queue // Deactivate cork to work with the offline queue
@@ -505,15 +505,15 @@ RedisClient.prototype.connectionGone = function (why, error) {
message: 'Stream connection ended and command aborted.', message: 'Stream connection ended and command aborted.',
code: 'NR_CLOSED' code: 'NR_CLOSED'
}, { }, {
error: error error
}) })
return return
} }
if (typeof this.options.retryStrategy === 'function') { if (typeof this.options.retryStrategy === 'function') {
var retryParams = { const retryParams = {
attempt: this.attempts, attempt: this.attempts,
error: error, error,
totalRetryTime: this.retryTotaltime, totalRetryTime: this.retryTotaltime,
timesConnected: this.timesConnected timesConnected: this.timesConnected
} }
@@ -527,7 +527,7 @@ RedisClient.prototype.connectionGone = function (why, error) {
message: 'Stream connection ended and command aborted.', message: 'Stream connection ended and command aborted.',
code: 'NR_CLOSED' code: 'NR_CLOSED'
}, { }, {
error: error error
}) })
this.end(false) this.end(false)
return return
@@ -543,20 +543,20 @@ RedisClient.prototype.connectionGone = function (why, error) {
message: 'Redis connection lost and command aborted.', message: 'Redis connection lost and command aborted.',
code: 'UNCERTAIN_STATE' code: 'UNCERTAIN_STATE'
}, { }, {
error: error, error,
queues: ['commandQueue'] queues: ['commandQueue']
}) })
} }
debug('Retry connection in ' + this.retryDelay + ' ms') debug(`Retry connection in ${this.retryDelay} ms`)
this.retryTimer = setTimeout(retryConnection, this.retryDelay, this, error) this.retryTimer = setTimeout(retryConnection, this.retryDelay, this, error)
} }
RedisClient.prototype.returnError = function (err) { RedisClient.prototype.returnError = function (err) {
var commandObj = this.commandQueue.shift() const commandObj = this.commandQueue.shift()
if (commandObj.error) { if (commandObj.error) {
err.stack = commandObj.error.stack.replace(/^Error.*?\n/, 'ReplyError: ' + err.message + '\n') err.stack = commandObj.error.stack.replace(/^Error.*?\n/, `ReplyError: ${err.message}\n`)
} }
err.command = commandObj.command.toUpperCase() err.command = commandObj.command.toUpperCase()
if (commandObj.args && commandObj.args.length) { if (commandObj.args && commandObj.args.length) {
@@ -568,7 +568,7 @@ RedisClient.prototype.returnError = function (err) {
this.pubSubMode-- this.pubSubMode--
} }
var match = err.message.match(utils.errCode) const match = err.message.match(utils.errCode)
// LUA script could return user errors that don't behave like all other errors! // LUA script could return user errors that don't behave like all other errors!
if (match) { if (match) {
err.code = match[1] err.code = match[1]
@@ -578,7 +578,7 @@ RedisClient.prototype.returnError = function (err) {
} }
function normalReply (self, reply) { function normalReply (self, reply) {
var commandObj = self.commandQueue.shift() const commandObj = self.commandQueue.shift()
if (typeof commandObj.callback === 'function') { if (typeof commandObj.callback === 'function') {
if (commandObj.command !== 'exec') { if (commandObj.command !== 'exec') {
reply = self.handleReply(reply, commandObj.command, commandObj.bufferArgs) reply = self.handleReply(reply, commandObj.command, commandObj.bufferArgs)
@@ -592,28 +592,28 @@ function normalReply (self, reply) {
function subscribeUnsubscribe (self, reply, type) { function subscribeUnsubscribe (self, reply, type) {
// Subscribe commands take an optional callback and also emit an event, but only the Last_ response is included in the callback // Subscribe commands take an optional callback and also emit an event, but only the Last_ response is included in the callback
// The pub sub commands return each argument in a separate return value and have to be handled that way // The pub sub commands return each argument in a separate return value and have to be handled that way
var commandObj = self.commandQueue.get(0) const commandObj = self.commandQueue.get(0)
var buffer = self.options.returnBuffers || self.options.detectBuffers && commandObj.bufferArgs const buffer = self.options.returnBuffers || self.options.detectBuffers && commandObj.bufferArgs
var channel = (buffer || reply[1] === null) ? reply[1] : reply[1].toString() const channel = (buffer || reply[1] === null) ? reply[1] : reply[1].toString()
var count = +reply[2] // Return the channel counter as number no matter if `stringNumbers` is activated or not const count = +reply[2] // Return the channel counter as number no matter if `stringNumbers` is activated or not
debug(type, channel) debug(type, channel)
// Emit first, then return the callback // Emit first, then return the callback
if (channel !== null) { // Do not emit or "unsubscribe" something if there was no channel to unsubscribe from if (channel !== null) { // Do not emit or "unsubscribe" something if there was no channel to unsubscribe from
self.emit(type, channel, count) self.emit(type, channel, count)
if (type === 'subscribe' || type === 'psubscribe') { if (type === 'subscribe' || type === 'psubscribe') {
self.subscriptionSet[type + '_' + channel] = channel self.subscriptionSet[`${type}_${channel}`] = channel
} else { } else {
type = type === 'unsubscribe' ? 'subscribe' : 'psubscribe' // Make types consistent type = type === 'unsubscribe' ? 'subscribe' : 'psubscribe' // Make types consistent
delete self.subscriptionSet[type + '_' + channel] delete self.subscriptionSet[`${type}_${channel}`]
} }
self.subscribeChannels.push(channel) self.subscribeChannels.push(channel)
} }
if (commandObj.args.length === 1 || self.subCommandsLeft === 1 || commandObj.args.length === 0 && (count === 0 || channel === null)) { if (commandObj.args.length === 1 || self.subCommandsLeft === 1 || commandObj.args.length === 0 && (count === 0 || channel === null)) {
if (count === 0) { // unsubscribed from all channels if (count === 0) { // unsubscribed from all channels
var runningCommand let runningCommand
var i = 1 let i = 1
self.pubSubMode = 0 // Deactivating pub sub mode self.pubSubMode = 0 // Deactivating pub sub mode
// This should be a rare case and therefore handling it this way should be good performance wise for the general case // This should be a rare case and therefore handling it this way should be good performance wise for the general case
for (runningCommand = self.commandQueue.get(i); runningCommand !== undefined; runningCommand = self.commandQueue.get(i)) { for (runningCommand = self.commandQueue.get(i); runningCommand !== undefined; runningCommand = self.commandQueue.get(i)) {
@@ -640,7 +640,7 @@ function subscribeUnsubscribe (self, reply, type) {
} }
function returnPubSub (self, reply) { function returnPubSub (self, reply) {
var type = reply[0].toString() const type = reply[0].toString()
if (type === 'message') { // channel, message if (type === 'message') { // channel, message
if (!self.options.returnBuffers || self.messageBuffers) { // backwards compatible. Refactor this in v.3 to always return a string on the normal emitter if (!self.options.returnBuffers || self.messageBuffers) { // backwards compatible. Refactor this in v.3 to always return a string on the normal emitter
self.emit('message', reply[1].toString(), reply[2].toString()) self.emit('message', reply[1].toString(), reply[2].toString())
@@ -665,7 +665,7 @@ RedisClient.prototype.returnReply = function (reply) {
// As this is not the average use case and monitor is expensive anyway, let's change the code here, to improve // As this is not the average use case and monitor is expensive anyway, let's change the code here, to improve
// the average performance of all other commands in case of no monitor mode // the average performance of all other commands in case of no monitor mode
if (this.monitoring) { if (this.monitoring) {
var replyStr let replyStr
if (this.buffers && Buffer.isBuffer(reply)) { if (this.buffers && Buffer.isBuffer(reply)) {
replyStr = reply.toString() replyStr = reply.toString()
} else { } else {
@@ -674,8 +674,8 @@ RedisClient.prototype.returnReply = function (reply) {
// While reconnecting the redis server does not recognize the client as in monitor mode anymore // While reconnecting the redis server does not recognize the client as in monitor mode anymore
// Therefore the monitor command has to finish before it catches further commands // Therefore the monitor command has to finish before it catches further commands
if (typeof replyStr === 'string' && utils.monitorRegex.test(replyStr)) { if (typeof replyStr === 'string' && utils.monitorRegex.test(replyStr)) {
var timestamp = replyStr.slice(0, replyStr.indexOf(' ')) const timestamp = replyStr.slice(0, replyStr.indexOf(' '))
var args = replyStr.slice(replyStr.indexOf('"') + 1, -1).split('" "').map(function (elem) { const args = replyStr.slice(replyStr.indexOf('"') + 1, -1).split('" "').map((elem) => {
return elem.replace(/\\"/g, '"') return elem.replace(/\\"/g, '"')
}) })
this.emit('monitor', timestamp, args, replyStr) this.emit('monitor', timestamp, args, replyStr)
@@ -697,8 +697,8 @@ RedisClient.prototype.returnReply = function (reply) {
} }
function handleOfflineCommand (self, commandObj) { function handleOfflineCommand (self, commandObj) {
var command = commandObj.command let command = commandObj.command
var err, msg let err, msg
if (self.closing || !self.enableOfflineQueue) { if (self.closing || !self.enableOfflineQueue) {
command = command.toUpperCase() command = command.toUpperCase()
if (!self.closing) { if (!self.closing) {
@@ -711,16 +711,16 @@ function handleOfflineCommand (self, commandObj) {
msg = 'The connection is already closed.' msg = 'The connection is already closed.'
} }
err = new errorClasses.AbortError({ err = new errorClasses.AbortError({
message: command + " can't be processed. " + msg, message: `${command} can't be processed. ${msg}`,
code: 'NR_CLOSED', code: 'NR_CLOSED',
command: command command
}) })
if (commandObj.args.length) { if (commandObj.args.length) {
err.args = commandObj.args err.args = commandObj.args
} }
utils.replyInOrder(self, commandObj.callback, err) utils.replyInOrder(self, commandObj.callback, err)
} else { } else {
debug('Queueing ' + command + ' for next server connection.') debug(`Queueing ${command} for next server connection.`)
self.offlineQueue.push(commandObj) self.offlineQueue.push(commandObj)
} }
self.shouldBuffer = true self.shouldBuffer = true
@@ -729,14 +729,14 @@ function handleOfflineCommand (self, commandObj) {
// Do not call internalSendCommand directly, if you are not absolutely certain it handles everything properly // Do not call internalSendCommand directly, if you are not absolutely certain it handles everything properly
// e.g. monitor / info does not work with internalSendCommand only // e.g. monitor / info does not work with internalSendCommand only
RedisClient.prototype.internalSendCommand = function (commandObj) { RedisClient.prototype.internalSendCommand = function (commandObj) {
var arg, prefixKeys let arg, prefixKeys
var i = 0 let i = 0
var commandStr = '' let commandStr = ''
var args = commandObj.args const args = commandObj.args
var command = commandObj.command let command = commandObj.command
var len = args.length const len = args.length
var bigData = false let bigData = false
var argsCopy = new Array(len) const argsCopy = new Array(len)
if (process.domain && commandObj.callback) { if (process.domain && commandObj.callback) {
commandObj.callback = process.domain.bind(commandObj.callback) commandObj.callback = process.domain.bind(commandObj.callback)
@@ -745,7 +745,7 @@ RedisClient.prototype.internalSendCommand = function (commandObj) {
if (this.ready === false || this.stream.writable === false) { if (this.ready === false || this.stream.writable === false) {
// Handle offline commands right away // Handle offline commands right away
handleOfflineCommand(this, commandObj) handleOfflineCommand(this, commandObj)
return false // Indicate buffering return
} }
for (i = 0; i < len; i += 1) { for (i = 0; i < len; i += 1) {
@@ -761,34 +761,28 @@ RedisClient.prototype.internalSendCommand = function (commandObj) {
if (args[i] instanceof Date) { // Accept dates as valid input if (args[i] instanceof Date) { // Accept dates as valid input
argsCopy[i] = args[i].toString() argsCopy[i] = args[i].toString()
} else if (args[i] === null) { } else if (args[i] === null) {
this.warn( const err = new TypeError('The command contains a "null" argument but NodeRedis can only handle strings, numbers and buffers.')
'Deprecated: The ' + command.toUpperCase() + ' command contains a "null" argument.\n' + err.command = command.toUpperCase()
'This is converted to a "null" string now and will return an error from v.3.0 on.\n' + err.args = args
'Please handle this in your code to make sure everything works as you intended it to.' return utils.replyInOrder(this, commandObj.callback, err, undefined, this.commandQueue)
)
argsCopy[i] = 'null' // Backwards compatible :/
} else if (Buffer.isBuffer(args[i])) { } else if (Buffer.isBuffer(args[i])) {
argsCopy[i] = args[i] argsCopy[i] = args[i]
commandObj.bufferArgs = true commandObj.bufferArgs = true
bigData = true bigData = true
} else { } else {
this.warn( const err = new TypeError('The command contains a argument of type "' + args[i].constructor.name + '" but NodeRedis can only handle strings, numbers, and buffers.')
'Deprecated: The ' + command.toUpperCase() + ' command contains a argument of type ' + args[i].constructor.name + '.\n' + err.command = command.toUpperCase()
'This is converted to "' + args[i].toString() + '" by using .toString() now and will return an error from v.3.0 on.\n' + err.args = args
'Please handle this in your code to make sure everything works as you intended it to.' return utils.replyInOrder(this, commandObj.callback, err, undefined, this.commandQueue)
)
argsCopy[i] = args[i].toString() // Backwards compatible :/
} }
} else if (typeof args[i] === 'undefined') { } else if (typeof args[i] === 'undefined') {
this.warn( const err = new TypeError('The command contains a "undefined" argument but NodeRedis can only handle strings, numbers and buffers.')
'Deprecated: The ' + command.toUpperCase() + ' command contains a "undefined" argument.\n' + err.command = command.toUpperCase()
'This is converted to a "undefined" string now and will return an error from v.3.0 on.\n' + err.args = args
'Please handle this in your code to make sure everything works as you intended it to.' return utils.replyInOrder(this, commandObj.callback, err, undefined, this.commandQueue)
)
argsCopy[i] = 'undefined' // Backwards compatible :/
} else { } else {
// Seems like numbers are converted fast using string concatenation // Seems like numbers are converted fast using string concatenation
argsCopy[i] = '' + args[i] argsCopy[i] = `${args[i]}`
} }
} }
@@ -803,30 +797,30 @@ RedisClient.prototype.internalSendCommand = function (commandObj) {
} }
// Always use 'Multi bulk commands', but if passed any Buffer args, then do multiple writes, one for each arg. // Always use 'Multi bulk commands', but if passed any Buffer args, then do multiple writes, one for each arg.
// This means that using Buffers in commands is going to be slower, so use Strings if you don't already have a Buffer. // This means that using Buffers in commands is going to be slower, so use Strings if you don't already have a Buffer.
commandStr = '*' + (len + 1) + '\r\n$' + command.length + '\r\n' + command + '\r\n' commandStr = `*${len + 1}\r\n$${command.length}\r\n${command}\r\n`
if (bigData === false) { // Build up a string and send entire command in one write if (bigData === false) { // Build up a string and send entire command in one write
for (i = 0; i < len; i += 1) { for (i = 0; i < len; i += 1) {
arg = argsCopy[i] arg = argsCopy[i]
commandStr += '$' + Buffer.byteLength(arg) + '\r\n' + arg + '\r\n' commandStr += `$${Buffer.byteLength(arg)}\r\n${arg}\r\n`
} }
debug('Send ' + this.address + ' id ' + this.connectionId + ': ' + commandStr) debug(`Send ${this.address} id ${this.connectionId}: ${commandStr}`)
this.write(commandStr) this.write(commandStr)
} else { } else {
debug('Send command (' + commandStr + ') has Buffer arguments') debug(`Send command (${commandStr}) has Buffer arguments`)
this.fireStrings = false this.fireStrings = false
this.write(commandStr) this.write(commandStr)
for (i = 0; i < len; i += 1) { for (i = 0; i < len; i += 1) {
arg = argsCopy[i] arg = argsCopy[i]
if (typeof arg === 'string') { if (typeof arg === 'string') {
this.write('$' + Buffer.byteLength(arg) + '\r\n' + arg + '\r\n') this.write(`$${Buffer.byteLength(arg)}\r\n${arg}\r\n`)
} else { // buffer } else { // buffer
this.write('$' + arg.length + '\r\n') this.write(`$${arg.length}\r\n`)
this.write(arg) this.write(arg)
this.write('\r\n') this.write('\r\n')
} }
debug('sendCommand: buffer send ' + arg.length + ' bytes') debug(`sendCommand: buffer send ${arg.length} bytes`)
} }
} }
if (commandObj.callOnWrite) { if (commandObj.callOnWrite) {
@@ -849,12 +843,12 @@ RedisClient.prototype.internalSendCommand = function (commandObj) {
this.reply = 'ON' this.reply = 'ON'
} }
} }
return !this.shouldBuffer return
} }
RedisClient.prototype.writeStrings = function () { RedisClient.prototype.writeStrings = function () {
var str = '' let str = ''
for (var command = this.pipelineQueue.shift(); command; command = this.pipelineQueue.shift()) { for (let command = this.pipelineQueue.shift(); command; command = this.pipelineQueue.shift()) {
// Write to stream if the string is bigger than 4mb. The biggest string may be Math.pow(2, 28) - 15 chars long // Write to stream if the string is bigger than 4mb. The biggest string may be Math.pow(2, 28) - 15 chars long
if (str.length + command.length > 4 * 1024 * 1024) { if (str.length + command.length > 4 * 1024 * 1024) {
this.shouldBuffer = !this.stream.write(str) this.shouldBuffer = !this.stream.write(str)
@@ -868,7 +862,7 @@ RedisClient.prototype.writeStrings = function () {
} }
RedisClient.prototype.writeBuffers = function () { RedisClient.prototype.writeBuffers = function () {
for (var command = this.pipelineQueue.shift(); command; command = this.pipelineQueue.shift()) { for (let command = this.pipelineQueue.shift(); command; command = this.pipelineQueue.shift()) {
this.shouldBuffer = !this.stream.write(command) this.shouldBuffer = !this.stream.write(command)
} }
} }

View File

@@ -1,6 +1,6 @@
'use strict' 'use strict'
var betterStackTraces = /development/i.test(process.env.NODE_ENV) || /\bredis\b/i.test(process.env.NODE_DEBUG) const betterStackTraces = /development/i.test(process.env.NODE_ENV) || /\bredis\b/i.test(process.env.NODE_DEBUG)
function Command (command, args, callback, callOnWrite) { function Command (command, args, callback, callOnWrite) {
this.command = command this.command = command

View File

@@ -1,24 +1,24 @@
'use strict' 'use strict'
var commands = require('redis-commands') const commands = require('redis-commands')
var Multi = require('./multi') const Multi = require('./multi')
var RedisClient = require('../').RedisClient const RedisClient = require('../').RedisClient
var Command = require('./command') const Command = require('./command')
// TODO: Rewrite this including the individual commands into a Commands class // TODO: Rewrite this including the individual commands into a Commands class
// that provided a functionality to add new commands to the client // that provided a functionality to add new commands to the client
commands.list.forEach(function (command) { commands.list.forEach((command) => {
// Some rare Redis commands use special characters in their command name // Some rare Redis commands use special characters in their command name
// Convert those to a underscore to prevent using invalid function names // Convert those to a underscore to prevent using invalid function names
var commandName = command.replace(/(?:^([0-9])|[^a-zA-Z0-9_$])/g, '_$1') const commandName = command.replace(/(?:^([0-9])|[^a-zA-Z0-9_$])/g, '_$1')
// Do not override existing functions // Do not override existing functions
if (!RedisClient.prototype[command]) { if (!RedisClient.prototype[command]) {
RedisClient.prototype[command] = function () { RedisClient.prototype[command] = function () {
var arr let arr
var len = arguments.length let len = arguments.length
var callback let callback
var i = 0 let i = 0
if (Array.isArray(arguments[0])) { if (Array.isArray(arguments[0])) {
arr = arguments[0] arr = arguments[0]
if (len === 2) { if (len === 2) {
@@ -57,10 +57,10 @@ commands.list.forEach(function (command) {
// Do not override existing functions // Do not override existing functions
if (!Multi.prototype[command]) { if (!Multi.prototype[command]) {
Multi.prototype[command] = function () { Multi.prototype[command] = function () {
var arr let arr
var len = arguments.length let len = arguments.length
var callback let callback
var i = 0 let i = 0
if (Array.isArray(arguments[0])) { if (Array.isArray(arguments[0])) {
arr = arguments[0] arr = arguments[0]
if (len === 2) { if (len === 2) {

View File

@@ -1,11 +1,11 @@
'use strict' 'use strict'
var utils = require('./utils') const utils = require('./utils')
var URL = require('url') const URL = require('url')
module.exports = function createClient (portArg, hostArg, options) { module.exports = function createClient (portArg, hostArg, options) {
if (typeof portArg === 'number' || (typeof portArg === 'string' && /^\d+$/.test(portArg))) { if (typeof portArg === 'number' || (typeof portArg === 'string' && /^\d+$/.test(portArg))) {
var host let host
if (typeof hostArg === 'string') { if (typeof hostArg === 'string') {
host = hostArg host = hostArg
} else { } else {
@@ -20,7 +20,7 @@ module.exports = function createClient (portArg, hostArg, options) {
} else if (typeof portArg === 'string' || (portArg && portArg.url)) { } else if (typeof portArg === 'string' || (portArg && portArg.url)) {
options = utils.clone(portArg.url ? portArg : (hostArg || options)) options = utils.clone(portArg.url ? portArg : (hostArg || options))
var parsed = URL.parse(portArg.url || portArg, true, true) const parsed = URL.parse(portArg.url || portArg, true, true)
// [redis:]//[[user][:password]@][host][:port][/db-number][?db=db-number[&password=bar[&option=value]]] // [redis:]//[[user][:password]@][host][:port][/db-number][?db=db-number[&password=bar[&option=value]]]
if (parsed.slashes) { // We require slashes if (parsed.slashes) { // We require slashes
@@ -28,7 +28,7 @@ module.exports = function createClient (portArg, hostArg, options) {
options.password = parsed.auth.split(':')[1] options.password = parsed.auth.split(':')[1]
} }
if (parsed.protocol && parsed.protocol !== 'redis:') { if (parsed.protocol && parsed.protocol !== 'redis:') {
console.warn('nodeRedis: WARNING: You passed "' + parsed.protocol.substring(0, parsed.protocol.length - 1) + '" as protocol instead of the "redis" protocol!') console.warn(`nodeRedis: WARNING: You passed "${parsed.protocol.substring(0, parsed.protocol.length - 1) }" as protocol instead of the "redis" protocol!`)
} }
if (parsed.pathname && parsed.pathname !== '/') { if (parsed.pathname && parsed.pathname !== '/') {
options.db = parsed.pathname.substr(1) options.db = parsed.pathname.substr(1)
@@ -40,14 +40,14 @@ module.exports = function createClient (portArg, hostArg, options) {
options.port = parsed.port options.port = parsed.port
} }
if (parsed.search !== '') { if (parsed.search !== '') {
var elem let elem
for (elem in parsed.query) { for (elem in parsed.query) {
// If options are passed twice, only the parsed options will be used // If options are passed twice, only the parsed options will be used
if (elem in options) { if (elem in options) {
if (options[elem] === parsed.query[elem]) { if (options[elem] === parsed.query[elem]) {
console.warn('nodeRedis: WARNING: You passed the ' + elem + ' option twice!') console.warn(`nodeRedis: WARNING: You passed the ${elem} option twice!`)
} else { } else {
throw new RangeError('The ' + elem + ' option is added twice and does not match') throw new RangeError(`The ${elem} option is added twice and does not match`)
} }
} }
options[elem] = parsed.query[elem] options[elem] = parsed.query[elem]

View File

@@ -1,9 +1,9 @@
'use strict' 'use strict'
var util = require('util') const util = require('util')
var assert = require('assert') const assert = require('assert')
var RedisError = require('redis-parser').RedisError const RedisError = require('redis-parser').RedisError
var ADD_STACKTRACE = false const ADD_STACKTRACE = false
function AbortError (obj, stack) { function AbortError (obj, stack) {
assert(obj, 'The options argument is required') assert(obj, 'The options argument is required')
@@ -18,7 +18,7 @@ function AbortError (obj, stack) {
if (stack || stack === undefined) { if (stack || stack === undefined) {
Error.captureStackTrace(this, AbortError) Error.captureStackTrace(this, AbortError)
} }
for (var keys = Object.keys(obj), key = keys.pop(); key; key = keys.pop()) { for (let keys = Object.keys(obj), key = keys.pop(); key; key = keys.pop()) {
this[key] = obj[key] this[key] = obj[key]
} }
} }
@@ -34,7 +34,7 @@ function AggregateError (obj) {
writable: true writable: true
}) })
Error.captureStackTrace(this, AggregateError) Error.captureStackTrace(this, AggregateError)
for (var keys = Object.keys(obj), key = keys.pop(); key; key = keys.pop()) { for (let keys = Object.keys(obj), key = keys.pop(); key; key = keys.pop()) {
this[key] = obj[key] this[key] = obj[key]
} }
} }
@@ -54,6 +54,6 @@ Object.defineProperty(AggregateError.prototype, 'name', {
}) })
module.exports = { module.exports = {
AbortError: AbortError, AbortError,
AggregateError: AggregateError AggregateError
} }

View File

@@ -1,6 +1,6 @@
'use strict' 'use strict'
var index = require('../') const index = require('../')
function debug () { function debug () {
if (index.debugMode) { if (index.debugMode) {

View File

@@ -1,10 +1,10 @@
'use strict' 'use strict'
var utils = require('./utils') const utils = require('./utils')
var debug = require('./debug') const debug = require('./debug')
var RedisClient = require('../').RedisClient const RedisClient = require('../').RedisClient
var Command = require('./command') const Command = require('./command')
var noop = function () {} const noop = function () {}
/********************************************** /**********************************************
All documented and exposed API belongs in here All documented and exposed API belongs in here
@@ -14,7 +14,7 @@ All documented and exposed API belongs in here
RedisClient.prototype.sendCommand = function (command, args, callback) { RedisClient.prototype.sendCommand = function (command, args, callback) {
// Throw to fail early instead of relying in order in this case // Throw to fail early instead of relying in order in this case
if (typeof command !== 'string') { if (typeof command !== 'string') {
throw new TypeError('Wrong input type "' + (command !== null && command !== undefined ? command.constructor.name : command) + '" for command name') throw new TypeError(`Wrong input type "${command !== null && command !== undefined ? command.constructor.name : command}" for command name`)
} }
if (!Array.isArray(args)) { if (!Array.isArray(args)) {
if (args === undefined || args === null) { if (args === undefined || args === null) {
@@ -23,11 +23,11 @@ RedisClient.prototype.sendCommand = function (command, args, callback) {
callback = args callback = args
args = [] args = []
} else { } else {
throw new TypeError('Wrong input type "' + args.constructor.name + '" for args') throw new TypeError(`Wrong input type "${args.constructor.name}" for args`)
} }
} }
if (typeof callback !== 'function' && callback !== undefined) { if (typeof callback !== 'function' && callback !== undefined) {
throw new TypeError('Wrong input type "' + (callback !== null ? callback.constructor.name : 'null') + '" for callback function') throw new TypeError(`Wrong input type "${callback !== null ? callback.constructor.name : 'null' }" for callback function`)
} }
// Using the raw multi command is only possible with this function // Using the raw multi command is only possible with this function
@@ -88,22 +88,22 @@ RedisClient.prototype.duplicate = function (options, callback) {
callback = options callback = options
options = null options = null
} }
var existingOptions = utils.clone(this.options) const existingOptions = utils.clone(this.options)
options = utils.clone(options) options = utils.clone(options)
for (var elem in options) { for (const elem in options) {
existingOptions[elem] = options[elem] existingOptions[elem] = options[elem]
} }
var client = new RedisClient(existingOptions) const client = new RedisClient(existingOptions)
client.selectedDb = this.selectedDb client.selectedDb = this.selectedDb
if (typeof callback === 'function') { if (typeof callback === 'function') {
var readyListener = function () { const errorListener = function (err) {
callback(null, client)
client.removeAllListeners(errorListener)
}
var errorListener = function (err) {
callback(err) callback(err)
client.end(true) client.end(true)
} }
const readyListener = function () {
callback(null, client)
client.removeAllListeners(errorListener)
}
client.once('ready', readyListener) client.once('ready', readyListener)
client.once('error', errorListener) client.once('error', errorListener)
return return

View File

@@ -1,12 +1,12 @@
'use strict' 'use strict'
var utils = require('./utils') const utils = require('./utils')
var debug = require('./debug') const debug = require('./debug')
var Multi = require('./multi') const Multi = require('./multi')
var Command = require('./command') const Command = require('./command')
var noPasswordIsSet = /no password is set/ const noPasswordIsSet = /no password is set/
var loading = /LOADING/ const loading = /LOADING/
var RedisClient = require('../').RedisClient const RedisClient = require('../').RedisClient
/******************************************************************************************** /********************************************************************************************
Replace built-in redis functions Replace built-in redis functions
@@ -22,7 +22,7 @@ var RedisClient = require('../').RedisClient
********************************************************************************************/ ********************************************************************************************/
RedisClient.prototype.multi = function multi (args) { RedisClient.prototype.multi = function multi (args) {
var multi = new Multi(this, args) const multi = new Multi(this, args)
multi.exec = multi.EXEC = multi.execTransaction multi.exec = multi.EXEC = multi.execTransaction
return multi return multi
} }
@@ -53,8 +53,8 @@ Multi.prototype.select = function select (db, callback) {
RedisClient.prototype.monitor = RedisClient.prototype.MONITOR = function monitor (callback) { RedisClient.prototype.monitor = RedisClient.prototype.MONITOR = function monitor (callback) {
// Use a individual command, as this is a special case that does not has to be checked for any other command // Use a individual command, as this is a special case that does not has to be checked for any other command
var self = this const self = this
var callOnWrite = function () { const callOnWrite = function () {
// Activating monitor mode has to happen before Redis returned the callback. The monitor result is returned first. // Activating monitor mode has to happen before Redis returned the callback. The monitor result is returned first.
// Therefore we expect the command to be properly processed. If this is not the case, it's not an issue either. // Therefore we expect the command to be properly processed. If this is not the case, it's not an issue either.
self.monitoring = true self.monitoring = true
@@ -66,8 +66,8 @@ RedisClient.prototype.monitor = RedisClient.prototype.MONITOR = function monitor
Multi.prototype.monitor = function monitor (callback) { Multi.prototype.monitor = function monitor (callback) {
// Use a individual command, as this is a special case that does not has to be checked for any other command // Use a individual command, as this is a special case that does not has to be checked for any other command
if (this.exec !== this.execTransaction) { if (this.exec !== this.execTransaction) {
var self = this const self = this
var callOnWrite = function () { const callOnWrite = function () {
self._client.monitoring = true self._client.monitoring = true
} }
this.queue.push(new Command('monitor', [], callback, callOnWrite)) this.queue.push(new Command('monitor', [], callback, callOnWrite))
@@ -102,7 +102,7 @@ RedisClient.prototype.quit = function quit (callback) {
// TODO: Consider this for v.3 // TODO: Consider this for v.3
// Allow the quit command to be fired as soon as possible to prevent it landing in the offline queue. // Allow the quit command to be fired as soon as possible to prevent it landing in the offline queue.
// this.ready = this.offlineQueue.length === 0; // this.ready = this.offlineQueue.length === 0;
var backpressureIndicator = this.internalSendCommand(new Command('quit', [], quitCallback(this, callback))) const backpressureIndicator = this.internalSendCommand(new Command('quit', [], quitCallback(this, callback)))
// Calling quit should always end the connection, no matter if there's a connection or not // Calling quit should always end the connection, no matter if there's a connection or not
this.closing = true this.closing = true
this.ready = false this.ready = false
@@ -111,8 +111,8 @@ RedisClient.prototype.quit = function quit (callback) {
// Only works with batch, not in a transaction // Only works with batch, not in a transaction
Multi.prototype.quit = function quit (callback) { Multi.prototype.quit = function quit (callback) {
var self = this._client const self = this._client
var callOnWrite = function () { const callOnWrite = function () {
// If called in a multi context, we expect redis is available // If called in a multi context, we expect redis is available
self.closing = true self.closing = true
self.ready = false self.ready = false
@@ -124,11 +124,11 @@ Multi.prototype.quit = function quit (callback) {
function infoCallback (self, callback) { function infoCallback (self, callback) {
return function (err, res) { return function (err, res) {
if (res) { if (res) {
var obj = {} const obj = {}
var lines = res.toString().split('\r\n') const lines = res.toString().split('\r\n')
var line, parts, subParts let line, parts, subParts
for (var i = 0; i < lines.length; i++) { for (let i = 0; i < lines.length; i++) {
parts = lines[i].split(':') parts = lines[i].split(':')
if (parts[1]) { if (parts[1]) {
if (parts[0].indexOf('db') === 0) { if (parts[0].indexOf('db') === 0) {
@@ -145,7 +145,7 @@ function infoCallback (self, callback) {
} }
obj.versions = [] obj.versions = []
if (obj.redis_version) { if (obj.redis_version) {
obj.redis_version.split('.').forEach(function (num) { obj.redis_version.split('.').forEach((num) => {
obj.versions.push(+num) obj.versions.push(+num)
}) })
} }
@@ -160,7 +160,7 @@ function infoCallback (self, callback) {
// Store info in this.serverInfo after each call // Store info in this.serverInfo after each call
RedisClient.prototype.info = function info (section, callback) { RedisClient.prototype.info = function info (section, callback) {
var args = [] let args = []
if (typeof section === 'function') { if (typeof section === 'function') {
callback = section callback = section
} else if (section !== undefined) { } else if (section !== undefined) {
@@ -170,7 +170,7 @@ RedisClient.prototype.info = function info (section, callback) {
} }
Multi.prototype.info = function info (section, callback) { Multi.prototype.info = function info (section, callback) {
var args = [] let args = []
if (typeof section === 'function') { if (typeof section === 'function') {
callback = section callback = section
} else if (section !== undefined) { } else if (section !== undefined) {
@@ -190,7 +190,7 @@ function authCallback (self, pass, callback) {
} else if (loading.test(err.message)) { } else if (loading.test(err.message)) {
// If redis is still loading the db, it will not authenticate and everything else will fail // If redis is still loading the db, it will not authenticate and everything else will fail
debug('Redis still loading, trying to authenticate later') debug('Redis still loading, trying to authenticate later')
setTimeout(function () { setTimeout(() => {
self.auth(pass, callback) self.auth(pass, callback)
}, 100) }, 100)
return return
@@ -201,20 +201,20 @@ function authCallback (self, pass, callback) {
} }
RedisClient.prototype.auth = function auth (pass, callback) { RedisClient.prototype.auth = function auth (pass, callback) {
debug('Sending auth to ' + this.address + ' id ' + this.connectionId) debug(`Sending auth to ${this.address} id ${this.connectionId}`)
// Stash auth for connect and reconnect. // Stash auth for connect and reconnect.
this.authPass = pass this.authPass = pass
var ready = this.ready const ready = this.ready
this.ready = ready || this.offlineQueue.length === 0 this.ready = ready || this.offlineQueue.length === 0
var tmp = this.internalSendCommand(new Command('auth', [pass], authCallback(this, pass, callback))) const tmp = this.internalSendCommand(new Command('auth', [pass], authCallback(this, pass, callback)))
this.ready = ready this.ready = ready
return tmp return tmp
} }
// Only works with batch, not in a transaction // Only works with batch, not in a transaction
Multi.prototype.auth = function auth (pass, callback) { Multi.prototype.auth = function auth (pass, callback) {
debug('Sending auth to ' + this.address + ' id ' + this.connectionId) debug(`Sending auth to ${this.address} id ${this.connectionId}`)
// Stash auth for connect and reconnect. // Stash auth for connect and reconnect.
this.authPass = pass this.authPass = pass
@@ -223,10 +223,10 @@ Multi.prototype.auth = function auth (pass, callback) {
} }
RedisClient.prototype.client = function client () { RedisClient.prototype.client = function client () {
var arr let arr
var len = arguments.length let len = arguments.length
var callback let callback
var i = 0 let i = 0
if (Array.isArray(arguments[0])) { if (Array.isArray(arguments[0])) {
arr = arguments[0] arr = arguments[0]
callback = arguments[1] callback = arguments[1]
@@ -252,12 +252,12 @@ RedisClient.prototype.client = function client () {
arr[i] = arguments[i] arr[i] = arguments[i]
} }
} }
var self = this const self = this
var callOnWrite let callOnWrite
// CLIENT REPLY ON|OFF|SKIP // CLIENT REPLY ON|OFF|SKIP
/* istanbul ignore next: TODO: Remove this as soon as Travis runs Redis 3.2 */ /* istanbul ignore next: TODO: Remove this as soon as Travis runs Redis 3.2 */
if (arr.length === 2 && arr[0].toString().toUpperCase() === 'REPLY') { if (arr.length === 2 && arr[0].toString().toUpperCase() === 'REPLY') {
var replyOnOff = arr[1].toString().toUpperCase() const replyOnOff = arr[1].toString().toUpperCase()
if (replyOnOff === 'ON' || replyOnOff === 'OFF' || replyOnOff === 'SKIP') { if (replyOnOff === 'ON' || replyOnOff === 'OFF' || replyOnOff === 'SKIP') {
callOnWrite = function () { callOnWrite = function () {
self.reply = replyOnOff self.reply = replyOnOff
@@ -268,10 +268,10 @@ RedisClient.prototype.client = function client () {
} }
Multi.prototype.client = function client () { Multi.prototype.client = function client () {
var arr let arr
var len = arguments.length let len = arguments.length
var callback let callback
var i = 0 let i = 0
if (Array.isArray(arguments[0])) { if (Array.isArray(arguments[0])) {
arr = arguments[0] arr = arguments[0]
callback = arguments[1] callback = arguments[1]
@@ -297,12 +297,12 @@ Multi.prototype.client = function client () {
arr[i] = arguments[i] arr[i] = arguments[i]
} }
} }
var self = this._client const self = this._client
var callOnWrite let callOnWrite
// CLIENT REPLY ON|OFF|SKIP // CLIENT REPLY ON|OFF|SKIP
/* istanbul ignore next: TODO: Remove this as soon as Travis runs Redis 3.2 */ /* istanbul ignore next: TODO: Remove this as soon as Travis runs Redis 3.2 */
if (arr.length === 2 && arr[0].toString().toUpperCase() === 'REPLY') { if (arr.length === 2 && arr[0].toString().toUpperCase() === 'REPLY') {
var replyOnOff = arr[1].toString().toUpperCase() const replyOnOff = arr[1].toString().toUpperCase()
if (replyOnOff === 'ON' || replyOnOff === 'OFF' || replyOnOff === 'SKIP') { if (replyOnOff === 'ON' || replyOnOff === 'OFF' || replyOnOff === 'SKIP') {
callOnWrite = function () { callOnWrite = function () {
self.reply = replyOnOff self.reply = replyOnOff
@@ -314,10 +314,10 @@ Multi.prototype.client = function client () {
} }
RedisClient.prototype.hmset = function hmset () { RedisClient.prototype.hmset = function hmset () {
var arr let arr
var len = arguments.length let len = arguments.length
var callback let callback
var i = 0 let i = 0
if (Array.isArray(arguments[0])) { if (Array.isArray(arguments[0])) {
arr = arguments[0] arr = arguments[0]
callback = arguments[1] callback = arguments[1]
@@ -333,7 +333,7 @@ RedisClient.prototype.hmset = function hmset () {
} }
} else if (typeof arguments[1] === 'object' && (arguments.length === 2 || (arguments.length === 3 && (typeof arguments[2] === 'function' || typeof arguments[2] === 'undefined')))) { } else if (typeof arguments[1] === 'object' && (arguments.length === 2 || (arguments.length === 3 && (typeof arguments[2] === 'function' || typeof arguments[2] === 'undefined')))) {
arr = [arguments[0]] arr = [arguments[0]]
for (var field in arguments[1]) { for (const field in arguments[1]) {
arr.push(field, arguments[1][field]) arr.push(field, arguments[1][field])
} }
callback = arguments[2] callback = arguments[2]
@@ -353,10 +353,10 @@ RedisClient.prototype.hmset = function hmset () {
} }
Multi.prototype.hmset = function hmset () { Multi.prototype.hmset = function hmset () {
var arr let arr
var len = arguments.length let len = arguments.length
var callback let callback
var i = 0 let i = 0
if (Array.isArray(arguments[0])) { if (Array.isArray(arguments[0])) {
arr = arguments[0] arr = arguments[0]
callback = arguments[1] callback = arguments[1]
@@ -372,7 +372,7 @@ Multi.prototype.hmset = function hmset () {
} }
} else if (typeof arguments[1] === 'object' && (arguments.length === 2 || (arguments.length === 3 && (typeof arguments[2] === 'function' || typeof arguments[2] === 'undefined')))) { } else if (typeof arguments[1] === 'object' && (arguments.length === 2 || (arguments.length === 3 && (typeof arguments[2] === 'function' || typeof arguments[2] === 'undefined')))) {
arr = [arguments[0]] arr = [arguments[0]]
for (var field in arguments[1]) { for (const field in arguments[1]) {
arr.push(field, arguments[1][field]) arr.push(field, arguments[1][field])
} }
callback = arguments[2] callback = arguments[2]
@@ -393,10 +393,10 @@ Multi.prototype.hmset = function hmset () {
} }
RedisClient.prototype.subscribe = function subscribe () { RedisClient.prototype.subscribe = function subscribe () {
var arr let arr
var len = arguments.length let len = arguments.length
var callback let callback
var i = 0 let i = 0
if (Array.isArray(arguments[0])) { if (Array.isArray(arguments[0])) {
arr = arguments[0].slice(0) arr = arguments[0].slice(0)
callback = arguments[1] callback = arguments[1]
@@ -412,18 +412,18 @@ RedisClient.prototype.subscribe = function subscribe () {
arr[i] = arguments[i] arr[i] = arguments[i]
} }
} }
var self = this const self = this
var callOnWrite = function () { const callOnWrite = function () {
self.pubSubMode = self.pubSubMode || self.commandQueue.length + 1 self.pubSubMode = self.pubSubMode || self.commandQueue.length + 1
} }
return this.internalSendCommand(new Command('subscribe', arr, callback, callOnWrite)) return this.internalSendCommand(new Command('subscribe', arr, callback, callOnWrite))
} }
Multi.prototype.subscribe = function subscribe () { Multi.prototype.subscribe = function subscribe () {
var arr let arr
var len = arguments.length let len = arguments.length
var callback let callback
var i = 0 let i = 0
if (Array.isArray(arguments[0])) { if (Array.isArray(arguments[0])) {
arr = arguments[0].slice(0) arr = arguments[0].slice(0)
callback = arguments[1] callback = arguments[1]
@@ -439,8 +439,8 @@ Multi.prototype.subscribe = function subscribe () {
arr[i] = arguments[i] arr[i] = arguments[i]
} }
} }
var self = this._client const self = this._client
var callOnWrite = function () { const callOnWrite = function () {
self.pubSubMode = self.pubSubMode || self.commandQueue.length + 1 self.pubSubMode = self.pubSubMode || self.commandQueue.length + 1
} }
this.queue.push(new Command('subscribe', arr, callback, callOnWrite)) this.queue.push(new Command('subscribe', arr, callback, callOnWrite))
@@ -448,10 +448,10 @@ Multi.prototype.subscribe = function subscribe () {
} }
RedisClient.prototype.unsubscribe = function unsubscribe () { RedisClient.prototype.unsubscribe = function unsubscribe () {
var arr let arr
var len = arguments.length let len = arguments.length
var callback let callback
var i = 0 let i = 0
if (Array.isArray(arguments[0])) { if (Array.isArray(arguments[0])) {
arr = arguments[0].slice(0) arr = arguments[0].slice(0)
callback = arguments[1] callback = arguments[1]
@@ -467,8 +467,8 @@ RedisClient.prototype.unsubscribe = function unsubscribe () {
arr[i] = arguments[i] arr[i] = arguments[i]
} }
} }
var self = this const self = this
var callOnWrite = function () { const callOnWrite = function () {
// Pub sub has to be activated even if not in pub sub mode, as the return value is manipulated in the callback // Pub sub has to be activated even if not in pub sub mode, as the return value is manipulated in the callback
self.pubSubMode = self.pubSubMode || self.commandQueue.length + 1 self.pubSubMode = self.pubSubMode || self.commandQueue.length + 1
} }
@@ -476,10 +476,10 @@ RedisClient.prototype.unsubscribe = function unsubscribe () {
} }
Multi.prototype.unsubscribe = function unsubscribe () { Multi.prototype.unsubscribe = function unsubscribe () {
var arr let arr
var len = arguments.length let len = arguments.length
var callback let callback
var i = 0 let i = 0
if (Array.isArray(arguments[0])) { if (Array.isArray(arguments[0])) {
arr = arguments[0].slice(0) arr = arguments[0].slice(0)
callback = arguments[1] callback = arguments[1]
@@ -495,8 +495,8 @@ Multi.prototype.unsubscribe = function unsubscribe () {
arr[i] = arguments[i] arr[i] = arguments[i]
} }
} }
var self = this._client const self = this._client
var callOnWrite = function () { const callOnWrite = function () {
// Pub sub has to be activated even if not in pub sub mode, as the return value is manipulated in the callback // Pub sub has to be activated even if not in pub sub mode, as the return value is manipulated in the callback
self.pubSubMode = self.pubSubMode || self.commandQueue.length + 1 self.pubSubMode = self.pubSubMode || self.commandQueue.length + 1
} }
@@ -505,10 +505,10 @@ Multi.prototype.unsubscribe = function unsubscribe () {
} }
RedisClient.prototype.psubscribe = function psubscribe () { RedisClient.prototype.psubscribe = function psubscribe () {
var arr let arr
var len = arguments.length let len = arguments.length
var callback let callback
var i = 0 let i = 0
if (Array.isArray(arguments[0])) { if (Array.isArray(arguments[0])) {
arr = arguments[0].slice(0) arr = arguments[0].slice(0)
callback = arguments[1] callback = arguments[1]
@@ -524,18 +524,18 @@ RedisClient.prototype.psubscribe = function psubscribe () {
arr[i] = arguments[i] arr[i] = arguments[i]
} }
} }
var self = this const self = this
var callOnWrite = function () { const callOnWrite = function () {
self.pubSubMode = self.pubSubMode || self.commandQueue.length + 1 self.pubSubMode = self.pubSubMode || self.commandQueue.length + 1
} }
return this.internalSendCommand(new Command('psubscribe', arr, callback, callOnWrite)) return this.internalSendCommand(new Command('psubscribe', arr, callback, callOnWrite))
} }
Multi.prototype.psubscribe = function psubscribe () { Multi.prototype.psubscribe = function psubscribe () {
var arr let arr
var len = arguments.length let len = arguments.length
var callback let callback
var i = 0 let i = 0
if (Array.isArray(arguments[0])) { if (Array.isArray(arguments[0])) {
arr = arguments[0].slice(0) arr = arguments[0].slice(0)
callback = arguments[1] callback = arguments[1]
@@ -551,8 +551,8 @@ Multi.prototype.psubscribe = function psubscribe () {
arr[i] = arguments[i] arr[i] = arguments[i]
} }
} }
var self = this._client const self = this._client
var callOnWrite = function () { const callOnWrite = function () {
self.pubSubMode = self.pubSubMode || self.commandQueue.length + 1 self.pubSubMode = self.pubSubMode || self.commandQueue.length + 1
} }
this.queue.push(new Command('psubscribe', arr, callback, callOnWrite)) this.queue.push(new Command('psubscribe', arr, callback, callOnWrite))
@@ -560,10 +560,10 @@ Multi.prototype.psubscribe = function psubscribe () {
} }
RedisClient.prototype.punsubscribe = function punsubscribe () { RedisClient.prototype.punsubscribe = function punsubscribe () {
var arr let arr
var len = arguments.length let len = arguments.length
var callback let callback
var i = 0 let i = 0
if (Array.isArray(arguments[0])) { if (Array.isArray(arguments[0])) {
arr = arguments[0].slice(0) arr = arguments[0].slice(0)
callback = arguments[1] callback = arguments[1]
@@ -579,8 +579,8 @@ RedisClient.prototype.punsubscribe = function punsubscribe () {
arr[i] = arguments[i] arr[i] = arguments[i]
} }
} }
var self = this const self = this
var callOnWrite = function () { const callOnWrite = function () {
// Pub sub has to be activated even if not in pub sub mode, as the return value is manipulated in the callback // Pub sub has to be activated even if not in pub sub mode, as the return value is manipulated in the callback
self.pubSubMode = self.pubSubMode || self.commandQueue.length + 1 self.pubSubMode = self.pubSubMode || self.commandQueue.length + 1
} }
@@ -588,10 +588,10 @@ RedisClient.prototype.punsubscribe = function punsubscribe () {
} }
Multi.prototype.punsubscribe = function punsubscribe () { Multi.prototype.punsubscribe = function punsubscribe () {
var arr let arr
var len = arguments.length let len = arguments.length
var callback let callback
var i = 0 let i = 0
if (Array.isArray(arguments[0])) { if (Array.isArray(arguments[0])) {
arr = arguments[0].slice(0) arr = arguments[0].slice(0)
callback = arguments[1] callback = arguments[1]
@@ -607,8 +607,8 @@ Multi.prototype.punsubscribe = function punsubscribe () {
arr[i] = arguments[i] arr[i] = arguments[i]
} }
} }
var self = this._client const self = this._client
var callOnWrite = function () { const callOnWrite = function () {
// Pub sub has to be activated even if not in pub sub mode, as the return value is manipulated in the callback // Pub sub has to be activated even if not in pub sub mode, as the return value is manipulated in the callback
self.pubSubMode = self.pubSubMode || self.commandQueue.length + 1 self.pubSubMode = self.pubSubMode || self.commandQueue.length + 1
} }

View File

@@ -1,15 +1,15 @@
'use strict' 'use strict'
var Queue = require('double-ended-queue') const Queue = require('double-ended-queue')
var utils = require('./utils') const utils = require('./utils')
var Command = require('./command') const Command = require('./command')
function Multi (client, args) { function Multi (client, args) {
this._client = client this._client = client
this.queue = new Queue() this.queue = new Queue()
var command, tmpArgs let command, tmpArgs
if (args) { // Either undefined or an array. Fail hard if it's not an array if (args) { // Either undefined or an array. Fail hard if it's not an array
for (var i = 0; i < args.length; i++) { for (let i = 0; i < args.length; i++) {
command = args[i][0] command = args[i][0]
tmpArgs = args[i].slice(1) tmpArgs = args[i].slice(1)
if (Array.isArray(command)) { if (Array.isArray(command)) {
@@ -23,7 +23,7 @@ function Multi (client, args) {
function pipelineTransactionCommand (self, commandObj, index) { function pipelineTransactionCommand (self, commandObj, index) {
// Queueing is done first, then the commands are executed // Queueing is done first, then the commands are executed
var tmp = commandObj.callback const tmp = commandObj.callback
commandObj.callback = function (err, reply) { commandObj.callback = function (err, reply) {
// Ignore the multi command. This is applied by nodeRedis and the user does not benefit by it // Ignore the multi command. This is applied by nodeRedis and the user does not benefit by it
if (err && index !== -1) { if (err && index !== -1) {
@@ -49,7 +49,7 @@ Multi.prototype.execAtomic = function execAtomic (callback) {
} }
function multiCallback (self, err, replies) { function multiCallback (self, err, replies) {
var i = 0 let i = 0
if (err) { if (err) {
err.errors = self.errors err.errors = self.errors
@@ -63,9 +63,9 @@ function multiCallback (self, err, replies) {
} }
if (replies) { if (replies) {
for (var commandObj = self.queue.shift(); commandObj !== undefined; commandObj = self.queue.shift()) { for (let commandObj = self.queue.shift(); commandObj !== undefined; commandObj = self.queue.shift()) {
if (replies[i] instanceof Error) { if (replies[i] instanceof Error) {
var match = replies[i].message.match(utils.errCode) const match = replies[i].message.match(utils.errCode)
// LUA script could return user errors that don't behave like all other errors! // LUA script could return user errors that don't behave like all other errors!
if (match) { if (match) {
replies[i].code = match[1] replies[i].code = match[1]
@@ -92,31 +92,31 @@ function multiCallback (self, err, replies) {
Multi.prototype.execTransaction = function execTransaction (callback) { Multi.prototype.execTransaction = function execTransaction (callback) {
if (this.monitoring || this._client.monitoring) { if (this.monitoring || this._client.monitoring) {
var err = new RangeError( const err = new RangeError(
'Using transaction with a client that is in monitor mode does not work due to faulty return values of Redis.' 'Using transaction with a client that is in monitor mode does not work due to faulty return values of Redis.'
) )
err.command = 'EXEC' err.command = 'EXEC'
err.code = 'EXECABORT' err.code = 'EXECABORT'
return utils.replyInOrder(this._client, callback, err) return utils.replyInOrder(this._client, callback, err)
} }
var self = this const self = this
var len = self.queue.length const len = self.queue.length
self.errors = [] self.errors = []
self.callback = callback self.callback = callback
self._client.cork() self._client.cork()
self.wantsBuffers = new Array(len) self.wantsBuffers = new Array(len)
pipelineTransactionCommand(self, new Command('multi', []), -1) pipelineTransactionCommand(self, new Command('multi', []), -1)
// Drain queue, callback will catch 'QUEUED' or error // Drain queue, callback will catch 'QUEUED' or error
for (var index = 0; index < len; index++) { for (let index = 0; index < len; index++) {
// The commands may not be shifted off, since they are needed in the result handler // The commands may not be shifted off, since they are needed in the result handler
pipelineTransactionCommand(self, self.queue.get(index), index) pipelineTransactionCommand(self, self.queue.get(index), index)
} }
self._client.internalSendCommand(new Command('exec', [], function (err, replies) { self._client.internalSendCommand(new Command('exec', [], (err, replies) => {
multiCallback(self, err, replies) multiCallback(self, err, replies)
})) }))
self._client.uncork() self._client.uncork()
return !self._client.shouldBuffer return
} }
function batchCallback (self, cb, i) { function batchCallback (self, cb, i) {
@@ -133,13 +133,13 @@ function batchCallback (self, cb, i) {
} }
Multi.prototype.exec = Multi.prototype.execBatch = function execBatch (callback) { Multi.prototype.exec = Multi.prototype.execBatch = function execBatch (callback) {
var self = this const self = this
var len = self.queue.length const len = self.queue.length
var index = 0 let index = 0
var commandObj let commandObj
if (len === 0) { if (len === 0) {
utils.replyInOrder(self._client, callback, null, []) utils.replyInOrder(self._client, callback, null, [])
return !self._client.shouldBuffer return
} }
self._client.cork() self._client.cork()
if (!callback) { if (!callback) {
@@ -147,13 +147,13 @@ Multi.prototype.exec = Multi.prototype.execBatch = function execBatch (callback)
self._client.internalSendCommand(commandObj) self._client.internalSendCommand(commandObj)
} }
self._client.uncork() self._client.uncork()
return !self._client.shouldBuffer return
} }
var callbackWithoutOwnCb = function (err, res) { const callbackWithoutOwnCb = function (err, res) {
if (err) { if (err) {
self.results.push(err) self.results.push(err)
// Add the position to the error // Add the position to the error
var i = self.results.length - 1 const i = self.results.length - 1
self.results[i].position = i self.results[i].position = i
} else { } else {
self.results.push(res) self.results.push(res)
@@ -161,7 +161,7 @@ Multi.prototype.exec = Multi.prototype.execBatch = function execBatch (callback)
// Do not emit an error here. Otherwise each error would result in one emit. // Do not emit an error here. Otherwise each error would result in one emit.
// The errors will be returned in the result anyway // The errors will be returned in the result anyway
} }
var lastCallback = function (cb) { const lastCallback = function (cb) {
return function (err, res) { return function (err, res) {
cb(err, res) cb(err, res)
callback(null, self.results) callback(null, self.results)
@@ -181,7 +181,7 @@ Multi.prototype.exec = Multi.prototype.execBatch = function execBatch (callback)
index++ index++
} }
self._client.uncork() self._client.uncork()
return !self._client.shouldBuffer return
} }
module.exports = Multi module.exports = Multi

View File

@@ -7,8 +7,8 @@ function replyToObject (reply) {
if (reply.length === 0 || !(reply instanceof Array)) { if (reply.length === 0 || !(reply instanceof Array)) {
return null return null
} }
var obj = {} const obj = {}
for (var i = 0; i < reply.length; i += 2) { for (let i = 0; i < reply.length; i += 2) {
obj[reply[i].toString('binary')] = reply[i + 1] obj[reply[i].toString('binary')] = reply[i + 1]
} }
return obj return obj
@@ -19,8 +19,8 @@ function replyToStrings (reply) {
return reply.toString() return reply.toString()
} }
if (reply instanceof Array) { if (reply instanceof Array) {
var res = new Array(reply.length) const res = new Array(reply.length)
for (var i = 0; i < reply.length; i++) { for (let i = 0; i < reply.length; i++) {
// Recursively call the function as slowlog returns deep nested replies // Recursively call the function as slowlog returns deep nested replies
res[i] = replyToStrings(reply[i]) res[i] = replyToStrings(reply[i])
} }
@@ -33,18 +33,18 @@ function replyToStrings (reply) {
// Deep clone arbitrary objects with arrays. Can't handle cyclic structures (results in a range error) // Deep clone arbitrary objects with arrays. Can't handle cyclic structures (results in a range error)
// Any attribute with a non primitive value besides object and array will be passed by reference (e.g. Buffers, Maps, Functions) // Any attribute with a non primitive value besides object and array will be passed by reference (e.g. Buffers, Maps, Functions)
function clone (obj) { function clone (obj) {
var copy let copy
if (Array.isArray(obj)) { if (Array.isArray(obj)) {
copy = new Array(obj.length) copy = new Array(obj.length)
for (var i = 0; i < obj.length; i++) { for (let i = 0; i < obj.length; i++) {
copy[i] = clone(obj[i]) copy[i] = clone(obj[i])
} }
return copy return copy
} }
if (Object.prototype.toString.call(obj) === '[object Object]') { if (Object.prototype.toString.call(obj) === '[object Object]') {
copy = {} copy = {}
var elements = Object.keys(obj) const elements = Object.keys(obj)
for (var elem = elements.pop(); elem !== undefined; elem = elements.pop()) { for (let elem = elements.pop(); elem !== undefined; elem = elements.pop()) {
copy[elem] = clone(obj[elem]) copy[elem] = clone(obj[elem])
} }
return copy return copy
@@ -67,18 +67,18 @@ function callbackOrEmit (self, callback, err, res) {
function replyInOrder (self, callback, err, res, queue) { function replyInOrder (self, callback, err, res, queue) {
// If the queue is explicitly passed, use that, otherwise fall back to the offline queue first, // If the queue is explicitly passed, use that, otherwise fall back to the offline queue first,
// as there might be commands in both queues at the same time // as there might be commands in both queues at the same time
var commandObj let commandObj
if (queue) { if (queue) {
commandObj = queue.peekBack() commandObj = queue.peekBack()
} else { } else {
commandObj = self.offlineQueue.peekBack() || self.commandQueue.peekBack() commandObj = self.offlineQueue.peekBack() || self.commandQueue.peekBack()
} }
if (!commandObj) { if (!commandObj) {
process.nextTick(function () { process.nextTick(() => {
callbackOrEmit(self, callback, err, res) callbackOrEmit(self, callback, err, res)
}) })
} else { } else {
var tmp = commandObj.callback const tmp = commandObj.callback
commandObj.callback = tmp commandObj.callback = tmp
? function (e, r) { ? function (e, r) {
tmp(e, r) tmp(e, r)
@@ -94,11 +94,11 @@ function replyInOrder (self, callback, err, res, queue) {
} }
module.exports = { module.exports = {
replyToStrings: replyToStrings, replyToStrings,
replyToObject: replyToObject, replyToObject,
errCode: /^([A-Z]+)\s+(.+)$/, errCode: /^([A-Z]+)\s+(.+)$/,
monitorRegex: /^[0-9]{10,11}\.[0-9]+ \[[0-9]+ .+]( ".+?")+$/, monitorRegex: /^[0-9]{10,11}\.[0-9]+ \[[0-9]+ .+]( ".+?")+$/,
clone: convenienceClone, clone: convenienceClone,
callbackOrEmit: callbackOrEmit, callbackOrEmit,
replyInOrder: replyInOrder replyInOrder
} }

View File

@@ -1,30 +1,30 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('./lib/config') const config = require('./lib/config')
var helper = require('./helper') const helper = require('./helper')
var redis = config.redis const redis = config.redis
// TODO: Fix redis process spawn on windows // TODO: Fix redis process spawn on windows
if (process.platform !== 'win32') { if (process.platform !== 'win32') {
describe('client authentication', function () { describe('client authentication', () => {
before(function (done) { before((done) => {
helper.stopRedis(function () { helper.stopRedis(() => {
helper.startRedis('./conf/password.conf', done) helper.startRedis('./conf/password.conf', done)
}) })
}) })
helper.allTests({ helper.allTests({
allConnections: true allConnections: true
}, function (ip, args) { }, (ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var auth = 'porkchopsandwiches' const auth = 'porkchopsandwiches'
var client = null let client = null
beforeEach(function () { beforeEach(() => {
client = null client = null
}) })
afterEach(function () { afterEach(() => {
// Explicitly ignore still running commands // Explicitly ignore still running commands
// The ready command could still be running // The ready command could still be running
client.end(false) client.end(false)
@@ -34,7 +34,7 @@ if (process.platform !== 'win32') {
if (helper.redisProcess().spawnFailed()) this.skip() if (helper.redisProcess().spawnFailed()) this.skip()
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.auth(auth, function (err, res) { client.auth(auth, (err, res) => {
assert.strictEqual(null, err) assert.strictEqual(null, err)
assert.strictEqual('OK', res.toString()) assert.strictEqual('OK', res.toString())
return done(err) return done(err)
@@ -45,17 +45,17 @@ if (process.platform !== 'win32') {
if (helper.redisProcess().spawnFailed()) this.skip() if (helper.redisProcess().spawnFailed()) this.skip()
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
var time = Date.now() const time = Date.now()
client.auth(auth, function (err, res) { client.auth(auth, (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual('retry worked', res) assert.strictEqual('retry worked', res)
var now = Date.now() const now = Date.now()
// Hint: setTimeout sometimes triggers early and therefore the value can be like one or two ms to early // Hint: setTimeout sometimes triggers early and therefore the value can be like one or two ms to early
assert(now - time >= 98, 'Time should be above 100 ms (the reconnect time) and is ' + (now - time)) assert(now - time >= 98, `Time should be above 100 ms (the reconnect time) and is ${now - time}`)
assert(now - time < 225, 'Time should be below 255 ms (the reconnect should only take a bit above 100 ms) and is ' + (now - time)) assert(now - time < 225, `Time should be below 255 ms (the reconnect should only take a bit above 100 ms) and is ${now - time}`)
done() done()
}) })
var tmp = client.commandQueue.get(0).callback const tmp = client.commandQueue.get(0).callback
client.commandQueue.get(0).callback = function (err) { client.commandQueue.get(0).callback = function (err) {
assert.strictEqual(err, null) assert.strictEqual(err, null)
client.auth = function (pass, callback) { client.auth = function (pass, callback) {
@@ -70,13 +70,13 @@ if (process.platform !== 'win32') {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('error', function (err) { client.once('error', (err) => {
assert.strictEqual(err.command, 'AUTH') assert.strictEqual(err.command, 'AUTH')
assert.ok(/ERR invalid password/.test(err.message)) assert.ok(/ERR invalid password/.test(err.message))
return done() return done()
}) })
client.auth(auth + 'bad') client.auth(`${auth}bad`)
}) })
it('returns an error when auth is bad (empty string) with a callback', function (done) { it('returns an error when auth is bad (empty string) with a callback', function (done) {
@@ -84,7 +84,7 @@ if (process.platform !== 'win32') {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.auth('', function (err) { client.auth('', (err) => {
assert.strictEqual(err.command, 'AUTH') assert.strictEqual(err.command, 'AUTH')
assert.ok(/ERR invalid password/.test(err.message)) assert.ok(/ERR invalid password/.test(err.message))
done() done()
@@ -95,13 +95,13 @@ if (process.platform !== 'win32') {
it('allows auth to be provided as part of redis url and do not fire commands before auth is done', function (done) { it('allows auth to be provided as part of redis url and do not fire commands before auth is done', function (done) {
if (helper.redisProcess().spawnFailed()) this.skip() if (helper.redisProcess().spawnFailed()) this.skip()
var end = helper.callFuncAfter(done, 2) const end = helper.callFuncAfter(done, 2)
client = redis.createClient('redis://:' + auth + '@' + config.HOST[ip] + ':' + config.PORT) client = redis.createClient(`redis://:${auth}@${config.HOST[ip]}:${config.PORT}`)
client.on('ready', function () { client.on('ready', () => {
end() end()
}) })
// The info command may be used while loading but not if not yet authenticated // The info command may be used while loading but not if not yet authenticated
client.info(function (err) { client.info((err) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
end(err) end(err)
}) })
@@ -110,17 +110,17 @@ if (process.platform !== 'win32') {
it('allows auth and database to be provided as part of redis url query parameter', function (done) { it('allows auth and database to be provided as part of redis url query parameter', function (done) {
if (helper.redisProcess().spawnFailed()) this.skip() if (helper.redisProcess().spawnFailed()) this.skip()
client = redis.createClient('redis://' + config.HOST[ip] + ':' + config.PORT + '?db=2&password=' + auth) client = redis.createClient(`redis://${config.HOST[ip]}:${config.PORT}?db=2&password=${auth}`)
assert.strictEqual(client.options.db, '2') assert.strictEqual(client.options.db, '2')
assert.strictEqual(client.options.password, auth) assert.strictEqual(client.options.password, auth)
assert.strictEqual(client.authPass, auth) assert.strictEqual(client.authPass, auth)
client.on('ready', function () { client.on('ready', () => {
// Set a key so the used database is returned in the info command // Set a key so the used database is returned in the info command
client.set('foo', 'bar') client.set('foo', 'bar')
client.get('foo') client.get('foo')
assert.strictEqual(client.serverInfo.db2, undefined) assert.strictEqual(client.serverInfo.db2, undefined)
// Using the info command should update the serverInfo // Using the info command should update the serverInfo
client.info(function (err) { client.info((err) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert(typeof client.serverInfo.db2 === 'object') assert(typeof client.serverInfo.db2 === 'object')
}) })
@@ -132,7 +132,7 @@ if (process.platform !== 'win32') {
it('allows auth to be provided as config option for client', function (done) { it('allows auth to be provided as config option for client', function (done) {
if (helper.redisProcess().spawnFailed()) this.skip() if (helper.redisProcess().spawnFailed()) this.skip()
var args = config.configureClient(ip, { const args = config.configureClient(ip, {
authPass: auth authPass: auth
}) })
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
@@ -142,7 +142,7 @@ if (process.platform !== 'win32') {
it('allows auth and noReadyCheck to be provided as config option for client', function (done) { it('allows auth and noReadyCheck to be provided as config option for client', function (done) {
if (helper.redisProcess().spawnFailed()) this.skip() if (helper.redisProcess().spawnFailed()) this.skip()
var args = config.configureClient(ip, { const args = config.configureClient(ip, {
password: auth, password: auth,
noReadyCheck: true noReadyCheck: true
}) })
@@ -153,7 +153,7 @@ if (process.platform !== 'win32') {
it('allows auth to be provided post-hoc with auth method', function (done) { it('allows auth to be provided post-hoc with auth method', function (done) {
if (helper.redisProcess().spawnFailed()) this.skip() if (helper.redisProcess().spawnFailed()) this.skip()
var args = config.configureClient(ip) const args = config.configureClient(ip)
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.auth(auth) client.auth(auth)
client.on('ready', done) client.on('ready', done)
@@ -166,7 +166,7 @@ if (process.platform !== 'win32') {
client.auth(auth) client.auth(auth)
client.on('ready', function () { client.on('ready', function () {
if (this.timesConnected < 3) { if (this.timesConnected < 3) {
var interval = setInterval(function () { let interval = setInterval(() => {
if (client.commandQueue.length !== 0) { if (client.commandQueue.length !== 0) {
return return
} }
@@ -181,46 +181,19 @@ if (process.platform !== 'win32') {
done() done()
} }
}) })
client.on('reconnecting', function (params) { client.on('reconnecting', (params) => {
assert.strictEqual(params.error, null) assert.strictEqual(params.error, null)
}) })
}) })
it('should return an error if the password is not correct and a callback has been provided', function (done) {
if (helper.redisProcess().spawnFailed()) this.skip()
client = redis.createClient.apply(null, args)
var async = true
client.auth(undefined, function (err, res) {
assert.strictEqual(err.message, 'ERR invalid password')
assert.strictEqual(err.command, 'AUTH')
assert.strictEqual(res, undefined)
async = false
done()
})
assert(async)
})
it('should emit an error if the password is not correct and no callback has been provided', function (done) {
if (helper.redisProcess().spawnFailed()) this.skip()
client = redis.createClient.apply(null, args)
client.on('error', function (err) {
assert.strictEqual(err.message, 'ERR invalid password')
assert.strictEqual(err.command, 'AUTH')
done()
})
client.auth(234567)
})
it('allows auth to be provided post-hoc with auth method again', function (done) { it('allows auth to be provided post-hoc with auth method again', function (done) {
if (helper.redisProcess().spawnFailed()) this.skip() if (helper.redisProcess().spawnFailed()) this.skip()
var args = config.configureClient(ip, { const args = config.configureClient(ip, {
authPass: auth authPass: auth
}) })
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.on('ready', function () { client.on('ready', () => {
client.auth(auth, helper.isString('OK', done)) client.auth(auth, helper.isString('OK', done))
}) })
}) })
@@ -228,12 +201,12 @@ if (process.platform !== 'win32') {
it('does not allow any commands to be processed if not authenticated using noReadyCheck true', function (done) { it('does not allow any commands to be processed if not authenticated using noReadyCheck true', function (done) {
if (helper.redisProcess().spawnFailed()) this.skip() if (helper.redisProcess().spawnFailed()) this.skip()
var args = config.configureClient(ip, { const args = config.configureClient(ip, {
noReadyCheck: true noReadyCheck: true
}) })
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.on('ready', function () { client.on('ready', () => {
client.set('foo', 'bar', function (err) { client.set('foo', 'bar', (err) => {
assert.strictEqual(err.message, 'NOAUTH Authentication required.') assert.strictEqual(err.message, 'NOAUTH Authentication required.')
assert.strictEqual(err.code, 'NOAUTH') assert.strictEqual(err.code, 'NOAUTH')
assert.strictEqual(err.command, 'SET') assert.strictEqual(err.command, 'SET')
@@ -245,7 +218,7 @@ if (process.platform !== 'win32') {
it('does not allow auth to be provided post-hoc with auth method if not authenticated before', function (done) { it('does not allow auth to be provided post-hoc with auth method if not authenticated before', function (done) {
if (helper.redisProcess().spawnFailed()) this.skip() if (helper.redisProcess().spawnFailed()) this.skip()
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.on('error', function (err) { client.on('error', (err) => {
assert.strictEqual(err.code, 'NOAUTH') assert.strictEqual(err.code, 'NOAUTH')
assert.strictEqual(err.message, 'Ready check failed: NOAUTH Authentication required.') assert.strictEqual(err.message, 'Ready check failed: NOAUTH Authentication required.')
assert.strictEqual(err.command, 'INFO') assert.strictEqual(err.command, 'INFO')
@@ -258,7 +231,7 @@ if (process.platform !== 'win32') {
client = redis.createClient({ client = redis.createClient({
password: 'wrongPassword' password: 'wrongPassword'
}) })
client.once('error', function (err) { client.once('error', (err) => {
assert.strictEqual(err.message, 'ERR invalid password') assert.strictEqual(err.message, 'ERR invalid password')
done() done()
}) })
@@ -267,49 +240,49 @@ if (process.platform !== 'win32') {
it('pubsub working with auth', function (done) { it('pubsub working with auth', function (done) {
if (helper.redisProcess().spawnFailed()) this.skip() if (helper.redisProcess().spawnFailed()) this.skip()
var args = config.configureClient(ip, { const args = config.configureClient(ip, {
password: auth password: auth
}) })
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.set('foo', 'bar') client.set('foo', 'bar')
client.subscribe('somechannel', 'another channel', function (err) { client.subscribe('somechannel', 'another channel', (err) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
client.once('ready', function () { client.once('ready', () => {
assert.strictEqual(client.pubSubMode, 1) assert.strictEqual(client.pubSubMode, 1)
client.get('foo', function (err) { client.get('foo', (err) => {
assert(/ERR only \(P\)SUBSCRIBE \/ \(P\)UNSUBSCRIBE/.test(err.message)) assert(/ERR only \(P\)SUBSCRIBE \/ \(P\)UNSUBSCRIBE/.test(err.message))
done() done()
}) })
}) })
}) })
client.once('ready', function () { client.once('ready', () => {
// Coherent behavior with all other offline commands fires commands before emitting but does not wait till they return // Coherent behavior with all other offline commands fires commands before emitting but does not wait till they return
assert.strictEqual(client.pubSubMode, 2) assert.strictEqual(client.pubSubMode, 2)
client.ping(function () { // Make sure all commands were properly processed already client.ping(() => { // Make sure all commands were properly processed already
client.stream.destroy() client.stream.destroy()
}) })
}) })
}) })
it('individual commands work properly with batch', function (done) { it('individual commands work properly with batch', (done) => {
// quit => might return an error instead of "OK" in the exec callback... (if not connected) // quit => might return an error instead of "OK" in the exec callback... (if not connected)
// auth => might return an error instead of "OK" in the exec callback... (if no password is required / still loading on Redis <= 2.4) // auth => might return an error instead of "OK" in the exec callback... (if no password is required / still loading on Redis <= 2.4)
// This could be fixed by checking the return value of the callback in the exec callback and // This could be fixed by checking the return value of the callback in the exec callback and
// returning the manipulated [error, result] from the callback. // returning the manipulated [error, result] from the callback.
// There should be a better solution though // There should be a better solution though
var args = config.configureClient('localhost', { const args = config.configureClient('localhost', {
noReadyCheck: true noReadyCheck: true
}) })
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
assert.strictEqual(client.selectedDb, undefined) assert.strictEqual(client.selectedDb, undefined)
var end = helper.callFuncAfter(done, 8) const end = helper.callFuncAfter(done, 8)
client.on('monitor', function () { client.on('monitor', () => {
end() // Should be called for each command after monitor end() // Should be called for each command after monitor
}) })
client.batch() client.batch()
.auth(auth) .auth(auth)
.select(5, function (err, res) { .select(5, (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(client.selectedDb, 5) assert.strictEqual(client.selectedDb, 5)
assert.strictEqual(res, 'OK') assert.strictEqual(res, 'OK')
@@ -317,7 +290,7 @@ if (process.platform !== 'win32') {
}) })
.monitor() .monitor()
.set('foo', 'bar', helper.isString('OK')) .set('foo', 'bar', helper.isString('OK'))
.info('stats', function (err, res) { .info('stats', (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res.indexOf('# Stats\r\n'), 0) assert.strictEqual(res.indexOf('# Stats\r\n'), 0)
assert.strictEqual(client.serverInfo.sync_full, '0') assert.strictEqual(client.serverInfo.sync_full, '0')
@@ -328,7 +301,7 @@ if (process.platform !== 'win32') {
.subscribe('/foo', helper.isDeepEqual([2, ['/foo']])) .subscribe('/foo', helper.isDeepEqual([2, ['/foo']]))
.psubscribe('*') .psubscribe('*')
.quit(helper.isString('OK')) .quit(helper.isString('OK'))
.exec(function (err, res) { .exec((err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
res[4] = res[4].substr(0, 9) res[4] = res[4].substr(0, 9)
assert.deepStrictEqual( assert.deepStrictEqual(
@@ -341,9 +314,9 @@ if (process.platform !== 'win32') {
}) })
}) })
after(function (done) { after((done) => {
if (helper.redisProcess().spawnFailed()) return done() if (helper.redisProcess().spawnFailed()) return done()
helper.stopRedis(function () { helper.stopRedis(() => {
helper.startRedis('./conf/redis.conf', done) helper.startRedis('./conf/redis.conf', done)
}) })
}) })

View File

@@ -1,73 +1,73 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('./lib/config') const config = require('./lib/config')
var helper = require('./helper') const helper = require('./helper')
var redis = config.redis const redis = config.redis
describe('The \'batch\' method', function () { describe('The \'batch\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
describe('when not connected', function () { describe('when not connected', () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('connect', function () { client.once('connect', () => {
client.quit() client.quit()
}) })
client.on('end', done) client.on('end', done)
}) })
it('returns an empty array for missing commands', function (done) { it('returns an empty array for missing commands', (done) => {
var batch = client.batch() const batch = client.batch()
batch.exec(function (err, res) { batch.exec((err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res.length, 0) assert.strictEqual(res.length, 0)
done() done()
}) })
}) })
it('returns an error for batch with commands', function (done) { it('returns an error for batch with commands', (done) => {
var batch = client.batch() const batch = client.batch()
batch.set('foo', 'bar') batch.set('foo', 'bar')
batch.exec(function (err, res) { batch.exec((err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res[0].code, 'NR_CLOSED') assert.strictEqual(res[0].code, 'NR_CLOSED')
done() done()
}) })
}) })
it('returns an empty array for missing commands if promisified', function () { it('returns an empty array for missing commands if promisified', () => {
return client.batch().execAsync().then(function (res) { return client.batch().execAsync().then((res) => {
assert.strictEqual(res.length, 0) assert.strictEqual(res.length, 0)
}) })
}) })
}) })
describe('when connected', function () { describe('when connected', () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(function (err) { client.flushdb((err) => {
return done(err) return done(err)
}) })
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
it('returns an empty array and keep the execution order in tact', function (done) { it('returns an empty array and keep the execution order in tact', (done) => {
var called = false let called = false
client.set('foo', 'bar', function () { client.set('foo', 'bar', () => {
called = true called = true
}) })
var batch = client.batch() const batch = client.batch()
batch.exec(function (err, res) { batch.exec((err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res.length, 0) assert.strictEqual(res.length, 0)
assert(called) assert(called)
@@ -75,47 +75,45 @@ describe('The \'batch\' method', function () {
}) })
}) })
it('runs normal calls in-between batch', function (done) { it('runs normal calls in-between batch', (done) => {
var batch = client.batch() const batch = client.batch()
batch.set('m1', '123') batch.set('m1', '123')
client.set('m2', '456', done) client.set('m2', '456', done)
}) })
it('returns an empty array if promisified', function () { it('returns an empty array if promisified', () => {
return client.batch().execAsync().then(function (res) { return client.batch().execAsync().then((res) => {
assert.strictEqual(res.length, 0) assert.strictEqual(res.length, 0)
}) })
}) })
it('returns an empty result array', function (done) { it('returns an empty result array', (done) => {
var batch = client.batch() const batch = client.batch()
var async = true let async = true
var notBuffering = batch.exec(function (err, res) { batch.exec((err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res.length, 0) assert.strictEqual(res.length, 0)
async = false async = false
done() done()
}) })
assert(async) assert(async)
assert.strictEqual(notBuffering, true)
}) })
it('fail individually when one command fails using chaining notation', function (done) { it('fail individually when one command fails using chaining notation', (done) => {
var batch1, batch2 const batch1 = client.batch()
batch1 = client.batch()
batch1.mset('batchfoo', '10', 'batchbar', '20', helper.isString('OK')) batch1.mset('batchfoo', '10', 'batchbar', '20', helper.isString('OK'))
// Provoke an error at queue time // Provoke an error at queue time
batch1.set('foo2', helper.isError()) batch1.set('foo2', helper.isError())
batch1.incr('batchfoo') batch1.incr('batchfoo')
batch1.incr('batchbar') batch1.incr('batchbar')
batch1.exec(function () { batch1.exec(() => {
// Confirm that the previous command, while containing an error, still worked. // Confirm that the previous command, while containing an error, still worked.
batch2 = client.batch() const batch2 = client.batch()
batch2.get('foo2', helper.isNull()) batch2.get('foo2', helper.isNull())
batch2.incr('batchbar', helper.isNumber(22)) batch2.incr('batchbar', helper.isNumber(22))
batch2.incr('batchfoo', helper.isNumber(12)) batch2.incr('batchfoo', helper.isNumber(12))
batch2.exec(function (err, replies) { batch2.exec((err, replies) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(null, replies[0]) assert.strictEqual(null, replies[0])
assert.strictEqual(22, replies[1]) assert.strictEqual(22, replies[1])
@@ -125,19 +123,18 @@ describe('The \'batch\' method', function () {
}) })
}) })
it('fail individually when one command fails and emit the error if no callback has been provided', function (done) { it('fail individually when one command fails and emit the error if no callback has been provided', (done) => {
var batch1 client.on('error', (err) => {
client.on('error', function (err) {
done(err) done(err)
}) })
batch1 = client.batch() const batch1 = client.batch()
batch1.mset('batchfoo', '10', 'batchbar', '20', helper.isString('OK')) batch1.mset('batchfoo', '10', 'batchbar', '20', helper.isString('OK'))
// Provoke an error at queue time // Provoke an error at queue time
batch1.set('foo2') batch1.set('foo2')
batch1.incr('batchfoo') batch1.incr('batchfoo')
batch1.incr('batchbar') batch1.incr('batchbar')
batch1.exec(function (err, res) { batch1.exec((err, res) => {
// TODO: This should actually return an error! // TODO: This should actually return an error!
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res[1].command, 'SET') assert.strictEqual(res[1].command, 'SET')
@@ -146,14 +143,14 @@ describe('The \'batch\' method', function () {
}) })
}) })
it('fail individually when one command in an array of commands fails', function (done) { it('fail individually when one command in an array of commands fails', (done) => {
// test nested batch-bulk replies // test nested batch-bulk replies
client.batch([ client.batch([
['mget', 'batchfoo', 'batchbar', helper.isDeepEqual([null, null])], ['mget', 'batchfoo', 'batchbar', helper.isDeepEqual([null, null])],
['set', 'foo2', helper.isError()], ['set', 'foo2', helper.isError()],
['incr', 'batchfoo'], ['incr', 'batchfoo'],
['incr', 'batchbar'] ['incr', 'batchbar']
]).exec(function (err, replies) { ]).exec((err, replies) => {
// TODO: This should actually return an error! // TODO: This should actually return an error!
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(2, replies[0].length) assert.strictEqual(2, replies[0].length)
@@ -166,7 +163,7 @@ describe('The \'batch\' method', function () {
}) })
}) })
it('handles multiple operations being applied to a set', function (done) { it('handles multiple operations being applied to a set', (done) => {
client.sadd('some set', 'mem 1') client.sadd('some set', 'mem 1')
client.sadd(['some set', 'mem 2']) client.sadd(['some set', 'mem 2'])
client.sadd('some set', 'mem 3') client.sadd('some set', 'mem 3')
@@ -174,7 +171,7 @@ describe('The \'batch\' method', function () {
// make sure empty mb reply works // make sure empty mb reply works
client.del('some missing set') client.del('some missing set')
client.smembers('some missing set', function (err, reply) { client.smembers('some missing set', (err, reply) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
// make sure empty mb reply works // make sure empty mb reply works
assert.strictEqual(0, reply.length) assert.strictEqual(0, reply.length)
@@ -187,7 +184,7 @@ describe('The \'batch\' method', function () {
['smembers', 'some set', undefined] // The explicit undefined is handled as a callback that is undefined ['smembers', 'some set', undefined] // The explicit undefined is handled as a callback that is undefined
]) ])
.scard('some set') .scard('some set')
.exec(function (err, replies) { .exec((err, replies) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(4, replies[0].length) assert.strictEqual(4, replies[0].length)
assert.strictEqual(0, replies[2].length) assert.strictEqual(0, replies[2].length)
@@ -195,12 +192,12 @@ describe('The \'batch\' method', function () {
}) })
}) })
it('allows multiple operations to be performed using constructor with all kinds of syntax', function (done) { it('allows multiple operations to be performed using constructor with all kinds of syntax', (done) => {
var now = Date.now() const now = Date.now()
var arr = ['batchhmset', 'batchbar', 'batchbaz'] const arr = ['batchhmset', 'batchbar', 'batchbaz']
var arr2 = ['some manner of key', 'otherTypes'] const arr2 = ['some manner of key', 'otherTypes']
var arr3 = [5768, 'batchbarx', 'batchfoox'] const arr3 = [5768, 'batchbarx', 'batchfoox']
var arr4 = ['mset', [578, 'batchbar'], helper.isString('OK')] const arr4 = ['mset', [578, 'batchbar'], helper.isString('OK')]
client.batch([ client.batch([
arr4, arr4,
[['mset', 'batchfoo2', 'batchbar2', 'batchfoo3', 'batchbar3'], helper.isString('OK')], [['mset', 'batchfoo2', 'batchbar2', 'batchfoo3', 'batchbar3'], helper.isString('OK')],
@@ -214,15 +211,15 @@ describe('The \'batch\' method', function () {
['hmset', 'batchhmset', ['batchbar', 'batchbaz'], helper.isString('OK')] ['hmset', 'batchhmset', ['batchbar', 'batchbaz'], helper.isString('OK')]
]) ])
.hmget(now, 123456789, 'otherTypes') .hmget(now, 123456789, 'otherTypes')
.hmget('key2', arr2, function noop () {}) .hmget('key2', arr2, () => {})
.hmget(['batchhmset2', 'some manner of key', 'batchbar3']) .hmget(['batchhmset2', 'some manner of key', 'batchbar3'])
.mget('batchfoo2', ['batchfoo3', 'batchfoo'], function (err, res) { .mget('batchfoo2', ['batchfoo3', 'batchfoo'], (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res[0], 'batchbar2') assert.strictEqual(res[0], 'batchbar2')
assert.strictEqual(res[1], 'batchbar3') assert.strictEqual(res[1], 'batchbar3')
assert.strictEqual(res[2], null) assert.strictEqual(res[2], null)
}) })
.exec(function (err, replies) { .exec((err, replies) => {
assert.strictEqual(arr.length, 3) assert.strictEqual(arr.length, 3)
assert.strictEqual(arr2.length, 2) assert.strictEqual(arr2.length, 2)
assert.strictEqual(arr3.length, 3) assert.strictEqual(arr3.length, 3)
@@ -239,7 +236,7 @@ describe('The \'batch\' method', function () {
}) })
}) })
it('converts a non string key to a string', function (done) { it('converts a non string key to a string', (done) => {
// TODO: Converting the key might change soon again. // TODO: Converting the key might change soon again.
client.batch().hmset(true, { client.batch().hmset(true, {
test: 123, test: 123,
@@ -247,21 +244,19 @@ describe('The \'batch\' method', function () {
}).exec(done) }).exec(done)
}) })
it('runs a batch without any further commands', function (done) { it('runs a batch without any further commands', (done) => {
var buffering = client.batch().exec(function (err, res) { client.batch().exec((err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res.length, 0) assert.strictEqual(res.length, 0)
done() done()
}) })
assert(typeof buffering === 'boolean')
}) })
it('runs a batch without any further commands and without callback', function () { it('runs a batch without any further commands and without callback', () => {
var buffering = client.batch().exec() client.batch().exec()
assert.strictEqual(buffering, true)
}) })
it('allows multiple operations to be performed using a chaining API', function (done) { it('allows multiple operations to be performed using a chaining API', (done) => {
client.batch() client.batch()
.mset('some', '10', 'keys', '20') .mset('some', '10', 'keys', '20')
.incr('some') .incr('some')
@@ -270,7 +265,7 @@ describe('The \'batch\' method', function () {
.exec(helper.isDeepEqual(['OK', 11, 21, ['11', '21']], done)) .exec(helper.isDeepEqual(['OK', 11, 21, ['11', '21']], done))
}) })
it('allows multiple commands to work the same as normal to be performed using a chaining API', function (done) { it('allows multiple commands to work the same as normal to be performed using a chaining API', (done) => {
client.batch() client.batch()
.mset(['some', '10', 'keys', '20']) .mset(['some', '10', 'keys', '20'])
.incr('some', helper.isNumber(11)) .incr('some', helper.isNumber(11))
@@ -279,25 +274,25 @@ describe('The \'batch\' method', function () {
.exec(helper.isDeepEqual(['OK', 11, 21, ['11', '21']], done)) .exec(helper.isDeepEqual(['OK', 11, 21, ['11', '21']], done))
}) })
it('allows multiple commands to work the same as normal to be performed using a chaining API promisified', function () { it('allows multiple commands to work the same as normal to be performed using a chaining API promisified', () => {
return client.batch() return client.batch()
.mset(['some', '10', 'keys', '20']) .mset(['some', '10', 'keys', '20'])
.incr('some', helper.isNumber(11)) .incr('some', helper.isNumber(11))
.incr(['keys'], helper.isNumber(21)) .incr(['keys'], helper.isNumber(21))
.mget('some', 'keys') .mget('some', 'keys')
.execAsync() .execAsync()
.then(function (res) { .then((res) => {
helper.isDeepEqual(['OK', 11, 21, ['11', '21']])(null, res) helper.isDeepEqual(['OK', 11, 21, ['11', '21']])(null, res)
}) })
}) })
it('allows an array to be provided indicating multiple operations to perform', function (done) { it('allows an array to be provided indicating multiple operations to perform', (done) => {
// test nested batch-bulk replies with nulls. // test nested batch-bulk replies with nulls.
client.batch([ client.batch([
['mget', ['batchfoo', 'some', 'random value', 'keys']], ['mget', ['batchfoo', 'some', 'random value', 'keys']],
['incr', 'batchfoo'] ['incr', 'batchfoo']
]) ])
.exec(function (err, replies) { .exec((err, replies) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(replies.length, 2) assert.strictEqual(replies.length, 2)
assert.strictEqual(replies[0].length, 4) assert.strictEqual(replies[0].length, 4)
@@ -305,7 +300,7 @@ describe('The \'batch\' method', function () {
}) })
}) })
it('allows multiple operations to be performed on a hash', function (done) { it('allows multiple operations to be performed on a hash', (done) => {
client.batch() client.batch()
.hmset('batchhash', 'a', 'foo', 'b', 1) .hmset('batchhash', 'a', 'foo', 'b', 1)
.hmset('batchhash', { .hmset('batchhash', {
@@ -316,8 +311,8 @@ describe('The \'batch\' method', function () {
.exec(done) .exec(done)
}) })
it('should work without any callback or arguments', function (done) { it('should work without any callback or arguments', (done) => {
var batch = client.batch() const batch = client.batch()
batch.set('baz', 'binary') batch.set('baz', 'binary')
batch.set('foo', 'bar') batch.set('foo', 'bar')
batch.ping() batch.ping()

View File

@@ -1,29 +1,29 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
var intercept = require('intercept-stdout') const intercept = require('intercept-stdout')
describe('The \'blpop\' method', function () { describe('The \'blpop\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
var bclient let bclient
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('pops value immediately if list contains values', function (done) { it('pops value immediately if list contains values', (done) => {
bclient = redis.createClient.apply(null, args) bclient = redis.createClient.apply(null, args)
redis.debugMode = true redis.debugMode = true
var text = '' let text = ''
var unhookIntercept = intercept(function (data) { const unhookIntercept = intercept((data) => {
text += data text += data
return '' return ''
}) })
@@ -31,26 +31,26 @@ describe('The \'blpop\' method', function () {
unhookIntercept() unhookIntercept()
assert(/^Send 127\.0\.0\.1:6379 id [0-9]+: \*3\r\n\$5\r\nrpush\r\n\$13\r\nblocking list\r\n\$13\r\ninitial value\r\n\n$/.test(text)) assert(/^Send 127\.0\.0\.1:6379 id [0-9]+: \*3\r\n\$5\r\nrpush\r\n\$13\r\nblocking list\r\n\$13\r\ninitial value\r\n\n$/.test(text))
redis.debugMode = false redis.debugMode = false
bclient.blpop('blocking list', 0, function (err, value) { bclient.blpop('blocking list', 0, (err, value) => {
assert.strictEqual(value[0], 'blocking list') assert.strictEqual(value[0], 'blocking list')
assert.strictEqual(value[1], 'initial value') assert.strictEqual(value[1], 'initial value')
return done(err) return done(err)
}) })
}) })
it('pops value immediately if list contains values using array notation', function (done) { it('pops value immediately if list contains values using array notation', (done) => {
bclient = redis.createClient.apply(null, args) bclient = redis.createClient.apply(null, args)
client.rpush(['blocking list', 'initial value'], helper.isNumber(1)) client.rpush(['blocking list', 'initial value'], helper.isNumber(1))
bclient.blpop(['blocking list', 0], function (err, value) { bclient.blpop(['blocking list', 0], (err, value) => {
assert.strictEqual(value[0], 'blocking list') assert.strictEqual(value[0], 'blocking list')
assert.strictEqual(value[1], 'initial value') assert.strictEqual(value[1], 'initial value')
return done(err) return done(err)
}) })
}) })
it('waits for value if list is not yet populated', function (done) { it('waits for value if list is not yet populated', (done) => {
bclient = redis.createClient.apply(null, args) bclient = redis.createClient.apply(null, args)
bclient.blpop('blocking list 2', 5, function (err, value) { bclient.blpop('blocking list 2', 5, (err, value) => {
assert.strictEqual(value[0], 'blocking list 2') assert.strictEqual(value[0], 'blocking list 2')
assert.strictEqual(value[1], 'initial value') assert.strictEqual(value[1], 'initial value')
return done(err) return done(err)
@@ -58,15 +58,15 @@ describe('The \'blpop\' method', function () {
client.rpush('blocking list 2', 'initial value', helper.isNumber(1)) client.rpush('blocking list 2', 'initial value', helper.isNumber(1))
}) })
it('times out after specified time', function (done) { it('times out after specified time', (done) => {
bclient = redis.createClient.apply(null, args) bclient = redis.createClient.apply(null, args)
bclient.blpop('blocking list', 1, function (err, res) { bclient.blpop('blocking list', 1, (err, res) => {
assert.strictEqual(res, null) assert.strictEqual(res, null)
return done(err) return done(err)
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
bclient.end(true) bclient.end(true)
}) })

View File

@@ -1,51 +1,51 @@
'use strict' 'use strict'
var Buffer = require('safe-buffer').Buffer const Buffer = require('safe-buffer').Buffer
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'client\' method', function () { describe('The \'client\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
var pattern = /addr=/ const pattern = /addr=/
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
describe('list', function () { describe('list', () => {
it('lists connected clients', function (done) { it('lists connected clients', (done) => {
client.client('LIST', helper.match(pattern, done)) client.client('LIST', helper.match(pattern, done))
}) })
it('lists connected clients when invoked with multi\'s chaining syntax', function (done) { it('lists connected clients when invoked with multi\'s chaining syntax', (done) => {
client.multi().client('list', helper.isType.string()).exec(helper.match(pattern, done)) client.multi().client('list', helper.isType.string()).exec(helper.match(pattern, done))
}) })
it('lists connected clients when invoked with array syntax on client', function (done) { it('lists connected clients when invoked with array syntax on client', (done) => {
client.multi().client(['list']).exec(helper.match(pattern, done)) client.multi().client(['list']).exec(helper.match(pattern, done))
}) })
it('lists connected clients when invoked with multi\'s array syntax', function (done) { it('lists connected clients when invoked with multi\'s array syntax', (done) => {
client.multi([ client.multi([
['client', 'list'] ['client', 'list']
]).exec(helper.match(pattern, done)) ]).exec(helper.match(pattern, done))
}) })
}) })
describe('reply', function () { describe('reply', () => {
describe('as normal command', function () { describe('as normal command', () => {
it('on', function (done) { it('on', function (done) {
helper.serverVersionAtLeast.call(this, client, [3, 2, 0]) helper.serverVersionAtLeast.call(this, client, [3, 2, 0])
assert.strictEqual(client.reply, 'ON') assert.strictEqual(client.reply, 'ON')
@@ -72,15 +72,15 @@ describe('The \'client\' method', function () {
}) })
}) })
describe('in a batch context', function () { describe('in a batch context', () => {
it('on', function (done) { it('on', function (done) {
helper.serverVersionAtLeast.call(this, client, [3, 2, 0]) helper.serverVersionAtLeast.call(this, client, [3, 2, 0])
var batch = client.batch() const batch = client.batch()
assert.strictEqual(client.reply, 'ON') assert.strictEqual(client.reply, 'ON')
batch.client('reply', 'on', helper.isString('OK')) batch.client('reply', 'on', helper.isString('OK'))
assert.strictEqual(client.reply, 'ON') assert.strictEqual(client.reply, 'ON')
batch.set('foo', 'bar') batch.set('foo', 'bar')
batch.exec(function (err, res) { batch.exec((err, res) => {
assert.deepEqual(res, ['OK', 'OK']) assert.deepEqual(res, ['OK', 'OK'])
done(err) done(err)
}) })
@@ -88,12 +88,12 @@ describe('The \'client\' method', function () {
it('off', function (done) { it('off', function (done) {
helper.serverVersionAtLeast.call(this, client, [3, 2, 0]) helper.serverVersionAtLeast.call(this, client, [3, 2, 0])
var batch = client.batch() const batch = client.batch()
assert.strictEqual(client.reply, 'ON') assert.strictEqual(client.reply, 'ON')
batch.set('hello', 'world') batch.set('hello', 'world')
batch.client(Buffer.from('REPLY'), Buffer.from('OFF'), helper.isUndefined()) batch.client(Buffer.from('REPLY'), Buffer.from('OFF'), helper.isUndefined())
batch.set('foo', 'bar', helper.isUndefined()) batch.set('foo', 'bar', helper.isUndefined())
batch.exec(function (err, res) { batch.exec((err, res) => {
assert.strictEqual(client.reply, 'OFF') assert.strictEqual(client.reply, 'OFF')
assert.deepEqual(res, ['OK', undefined, undefined]) assert.deepEqual(res, ['OK', undefined, undefined])
done(err) done(err)
@@ -108,7 +108,7 @@ describe('The \'client\' method', function () {
.client('REPLY', 'SKIP', helper.isUndefined()) .client('REPLY', 'SKIP', helper.isUndefined())
.set('foo', 'bar', helper.isUndefined()) .set('foo', 'bar', helper.isUndefined())
.get('foo') .get('foo')
.exec(function (err, res) { .exec((err, res) => {
assert.strictEqual(client.reply, 'ON') assert.strictEqual(client.reply, 'ON')
assert.deepEqual(res, ['OK', undefined, undefined, 'bar']) assert.deepEqual(res, ['OK', undefined, undefined, 'bar'])
done(err) done(err)
@@ -117,24 +117,24 @@ describe('The \'client\' method', function () {
}) })
}) })
describe('setname / getname', function () { describe('setname / getname', () => {
var client2 let client2
beforeEach(function (done) { beforeEach((done) => {
client2 = redis.createClient.apply(null, args) client2 = redis.createClient.apply(null, args)
client2.once('ready', function () { client2.once('ready', () => {
done() done()
}) })
}) })
afterEach(function () { afterEach(() => {
client2.end(true) client2.end(true)
}) })
it('sets the name', function (done) { it('sets the name', (done) => {
// The querys are auto pipelined and the response is a response to all querys of one client // The querys are auto pipelined and the response is a response to all querys of one client
// per chunk. So the execution order is only guaranteed on each client // per chunk. So the execution order is only guaranteed on each client
var end = helper.callFuncAfter(done, 2) const end = helper.callFuncAfter(done, 2)
client.client('setname', 'RUTH') client.client('setname', 'RUTH')
client2.client('setname', ['RENEE'], helper.isString('OK')) client2.client('setname', ['RENEE'], helper.isString('OK'))

View File

@@ -1,59 +1,59 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
var uuid = require('uuid') const uuid = require('uuid')
describe('The \'dbsize\' method', function () { describe('The \'dbsize\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var key, value let key, value
beforeEach(function () { beforeEach(() => {
key = uuid.v4() key = uuid.v4()
value = uuid.v4() value = uuid.v4()
}) })
describe('when not connected', function () { describe('when not connected', () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.quit() client.quit()
}) })
client.on('end', done) client.on('end', done)
}) })
it('reports an error', function (done) { it('reports an error', (done) => {
client.dbsize([], function (err, res) { client.dbsize([], (err, res) => {
assert(err.message.match(/The connection is already closed/)) assert(err.message.match(/The connection is already closed/))
done() done()
}) })
}) })
}) })
describe('when connected', function () { describe('when connected', () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(function (err, res) { client.flushdb((err, res) => {
helper.isString('OK')(err, res) helper.isString('OK')(err, res)
done() done()
}) })
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
it('returns a zero db size', function (done) { it('returns a zero db size', (done) => {
client.dbsize([], function (err, res) { client.dbsize([], (err, res) => {
helper.isNotError()(err, res) helper.isNotError()(err, res)
helper.isType.number()(err, res) helper.isType.number()(err, res)
assert.strictEqual(res, 0, 'Initial db size should be 0') assert.strictEqual(res, 0, 'Initial db size should be 0')
@@ -61,25 +61,25 @@ describe('The \'dbsize\' method', function () {
}) })
}) })
describe('when more data is added to Redis', function () { describe('when more data is added to Redis', () => {
var oldSize let oldSize
beforeEach(function (done) { beforeEach((done) => {
client.dbsize(function (err, res) { client.dbsize((err, res) => {
helper.isType.number()(err, res) helper.isType.number()(err, res)
assert.strictEqual(res, 0, 'Initial db size should be 0') assert.strictEqual(res, 0, 'Initial db size should be 0')
oldSize = res oldSize = res
client.set(key, value, function (err, res) { client.set(key, value, (err, res) => {
helper.isNotError()(err, res) helper.isNotError()(err, res)
done() done()
}) })
}) })
}) })
it('returns a larger db size', function (done) { it('returns a larger db size', (done) => {
client.dbsize([], function (err, res) { client.dbsize([], (err, res) => {
helper.isNotError()(err, res) helper.isNotError()(err, res)
helper.isType.positiveNumber()(err, res) helper.isType.positiveNumber()(err, res)
assert.strictEqual(true, (oldSize < res), 'Adding data should increase db size.') assert.strictEqual(true, (oldSize < res), 'Adding data should increase db size.')

View File

@@ -1,53 +1,53 @@
'use strict' 'use strict'
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'del\' method', function () { describe('The \'del\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('allows a single key to be deleted', function (done) { it('allows a single key to be deleted', (done) => {
client.set('foo', 'bar') client.set('foo', 'bar')
client.del('foo', helper.isNumber(1)) client.del('foo', helper.isNumber(1))
client.get('foo', helper.isNull(done)) client.get('foo', helper.isNull(done))
}) })
it('allows del to be called on a key that does not exist', function (done) { it('allows del to be called on a key that does not exist', (done) => {
client.del('foo', helper.isNumber(0, done)) client.del('foo', helper.isNumber(0, done))
}) })
it('allows multiple keys to be deleted', function (done) { it('allows multiple keys to be deleted', (done) => {
client.mset('foo', 'bar', 'apple', 'banana') client.mset('foo', 'bar', 'apple', 'banana')
client.del('foo', 'apple', helper.isNumber(2)) client.del('foo', 'apple', helper.isNumber(2))
client.get('foo', helper.isNull()) client.get('foo', helper.isNull())
client.get('apple', helper.isNull(done)) client.get('apple', helper.isNull(done))
}) })
it('allows multiple keys to be deleted with the array syntax', function (done) { it('allows multiple keys to be deleted with the array syntax', (done) => {
client.mset('foo', 'bar', 'apple', 'banana') client.mset('foo', 'bar', 'apple', 'banana')
client.del(['foo', 'apple'], helper.isNumber(2)) client.del(['foo', 'apple'], helper.isNumber(2))
client.get('foo', helper.isNull()) client.get('foo', helper.isNull())
client.get('apple', helper.isNull(done)) client.get('apple', helper.isNull(done))
}) })
it('allows multiple keys to be deleted with the array syntax and no callback', function (done) { it('allows multiple keys to be deleted with the array syntax and no callback', (done) => {
client.mset('foo', 'bar', 'apple', 'banana') client.mset('foo', 'bar', 'apple', 'banana')
client.del(['foo', 'apple']) client.del(['foo', 'apple'])
client.get('foo', helper.isNull()) client.get('foo', helper.isNull())
client.get('apple', helper.isNull(done)) client.get('apple', helper.isNull(done))
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,58 +1,58 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var crypto = require('crypto') const crypto = require('crypto')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'eval\' method', function () { describe('The \'eval\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
var source = 'return redis.call(\'set\', \'sha\', \'test\')' const source = 'return redis.call(\'set\', \'sha\', \'test\')'
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
it('converts a float to an integer when evaluated', function (done) { it('converts a float to an integer when evaluated', (done) => {
client.eval('return 100.5', 0, helper.isNumber(100, done)) client.eval('return 100.5', 0, helper.isNumber(100, done))
}) })
it('returns a string', function (done) { it('returns a string', (done) => {
client.eval('return \'hello world\'', 0, helper.isString('hello world', done)) client.eval('return \'hello world\'', 0, helper.isString('hello world', done))
}) })
it('converts boolean true to integer 1', function (done) { it('converts boolean true to integer 1', (done) => {
client.eval('return true', 0, helper.isNumber(1, done)) client.eval('return true', 0, helper.isNumber(1, done))
}) })
it('converts boolean false to null', function (done) { it('converts boolean false to null', (done) => {
client.eval('return false', 0, helper.isNull(done)) client.eval('return false', 0, helper.isNull(done))
}) })
it('converts lua status code to string representation', function (done) { it('converts lua status code to string representation', (done) => {
client.eval('return {ok=\'fine\'}', 0, helper.isString('fine', done)) client.eval('return {ok=\'fine\'}', 0, helper.isString('fine', done))
}) })
it('converts lua error to an error response', function (done) { it('converts lua error to an error response', (done) => {
client.eval('return {err=\'this is an error\'}', 0, function (err) { client.eval('return {err=\'this is an error\'}', 0, (err) => {
assert(err.code === undefined) assert(err.code === undefined)
helper.isError()(err) helper.isError()(err)
done() done()
}) })
}) })
it('represents a lua table appropritely', function (done) { it('represents a lua table appropritely', (done) => {
client.eval('return {1,2,3,\'ciao\',{1,2}}', 0, function (err, res) { client.eval('return {1,2,3,\'ciao\',{1,2}}', 0, (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(5, res.length) assert.strictEqual(5, res.length)
assert.strictEqual(1, res[0]) assert.strictEqual(1, res[0])
@@ -66,47 +66,47 @@ describe('The \'eval\' method', function () {
}) })
}) })
it('populates keys and argv correctly', function (done) { it('populates keys and argv correctly', (done) => {
client.eval('return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}', 2, 'a', 'b', 'c', 'd', helper.isDeepEqual(['a', 'b', 'c', 'd'], done)) client.eval('return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}', 2, 'a', 'b', 'c', 'd', helper.isDeepEqual(['a', 'b', 'c', 'd'], done))
}) })
it('allows arguments to be provided in array rather than as multiple parameters', function (done) { it('allows arguments to be provided in array rather than as multiple parameters', (done) => {
client.eval(['return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}', 2, 'a', 'b', 'c', 'd'], helper.isDeepEqual(['a', 'b', 'c', 'd'], done)) client.eval(['return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}', 2, 'a', 'b', 'c', 'd'], helper.isDeepEqual(['a', 'b', 'c', 'd'], done))
}) })
it('allows a script to be executed that accesses the redis API without callback', function (done) { it('allows a script to be executed that accesses the redis API without callback', (done) => {
client.eval(source, 0) client.eval(source, 0)
client.get('sha', helper.isString('test', done)) client.get('sha', helper.isString('test', done))
}) })
describe('evalsha', function () { describe('evalsha', () => {
var sha = crypto.createHash('sha1').update(source).digest('hex') const sha = crypto.createHash('sha1').update(source).digest('hex')
it('allows a script to be executed that accesses the redis API', function (done) { it('allows a script to be executed that accesses the redis API', (done) => {
client.eval(source, 0, helper.isString('OK')) client.eval(source, 0, helper.isString('OK'))
client.get('sha', helper.isString('test', done)) client.get('sha', helper.isString('test', done))
}) })
it('can execute a script if the SHA exists', function (done) { it('can execute a script if the SHA exists', (done) => {
client.evalsha(sha, 0, helper.isString('OK')) client.evalsha(sha, 0, helper.isString('OK'))
client.get('sha', helper.isString('test', done)) client.get('sha', helper.isString('test', done))
}) })
it('returns an error if SHA does not exist', function (done) { it('returns an error if SHA does not exist', (done) => {
client.evalsha('ffffffffffffffffffffffffffffffffffffffff', 0, helper.isError(done)) client.evalsha('ffffffffffffffffffffffffffffffffffffffff', 0, helper.isError(done))
}) })
it('emit an error if SHA does not exist without any callback', function (done) { it('emit an error if SHA does not exist without any callback', (done) => {
client.evalsha('ffffffffffffffffffffffffffffffffffffffff', 0) client.evalsha('ffffffffffffffffffffffffffffffffffffffff', 0)
client.on('error', function (err) { client.on('error', (err) => {
assert.strictEqual(err.code, 'NOSCRIPT') assert.strictEqual(err.code, 'NOSCRIPT')
assert(/NOSCRIPT No matching script. Please use EVAL./.test(err.message)) assert(/NOSCRIPT No matching script. Please use EVAL./.test(err.message))
done() done()
}) })
}) })
it('emits an error if SHA does not exist and no callback has been provided', function (done) { it('emits an error if SHA does not exist and no callback has been provided', (done) => {
client.on('error', function (err) { client.on('error', (err) => {
assert.strictEqual(err.message, 'NOSCRIPT No matching script. Please use EVAL.') assert.strictEqual(err.message, 'NOSCRIPT No matching script. Please use EVAL.')
done() done()
}) })
@@ -114,10 +114,10 @@ describe('The \'eval\' method', function () {
}) })
}) })
it('allows a key to be incremented, and performs appropriate conversion from LUA type', function (done) { it('allows a key to be incremented, and performs appropriate conversion from LUA type', (done) => {
client.set('incr key', 0, function (err, reply) { client.set('incr key', 0, (err, reply) => {
if (err) return done(err) if (err) return done(err)
client.eval('local foo = redis.call(\'incr\',\'incr key\')\nreturn {type(foo),foo}', 0, function (err, res) { client.eval('local foo = redis.call(\'incr\',\'incr key\')\nreturn {type(foo),foo}', 0, (err, res) => {
assert.strictEqual(2, res.length) assert.strictEqual(2, res.length)
assert.strictEqual('number', res[0]) assert.strictEqual('number', res[0])
assert.strictEqual(1, res[1]) assert.strictEqual(1, res[1])
@@ -126,10 +126,10 @@ describe('The \'eval\' method', function () {
}) })
}) })
it('allows a bulk operation to be performed, and performs appropriate conversion from LUA type', function (done) { it('allows a bulk operation to be performed, and performs appropriate conversion from LUA type', (done) => {
client.set('bulk reply key', 'bulk reply value', function (err, res) { client.set('bulk reply key', 'bulk reply value', (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
client.eval('local foo = redis.call(\'get\',\'bulk reply key\'); return {type(foo),foo}', 0, function (err, res) { client.eval('local foo = redis.call(\'get\',\'bulk reply key\'); return {type(foo),foo}', 0, (err, res) => {
assert.strictEqual(2, res.length) assert.strictEqual(2, res.length)
assert.strictEqual('string', res[0]) assert.strictEqual('string', res[0])
assert.strictEqual('bulk reply value', res[1]) assert.strictEqual('bulk reply value', res[1])
@@ -138,15 +138,15 @@ describe('The \'eval\' method', function () {
}) })
}) })
it('allows a multi mulk operation to be performed, with the appropriate type conversion', function (done) { it('allows a multi mulk operation to be performed, with the appropriate type conversion', (done) => {
client.multi() client.multi()
.del('mylist') .del('mylist')
.rpush('mylist', 'a') .rpush('mylist', 'a')
.rpush('mylist', 'b') .rpush('mylist', 'b')
.rpush('mylist', 'c') .rpush('mylist', 'c')
.exec(function (err, replies) { .exec((err, replies) => {
if (err) return done(err) if (err) return done(err)
client.eval('local foo = redis.call(\'lrange\',\'mylist\',0,-1); return {type(foo),foo[1],foo[2],foo[3],# foo}', 0, function (err, res) { client.eval('local foo = redis.call(\'lrange\',\'mylist\',0,-1); return {type(foo),foo[1],foo[2],foo[3],# foo}', 0, (err, res) => {
assert.strictEqual(5, res.length) assert.strictEqual(5, res.length)
assert.strictEqual('table', res[0]) assert.strictEqual('table', res[0])
assert.strictEqual('a', res[1]) assert.strictEqual('a', res[1])
@@ -158,8 +158,8 @@ describe('The \'eval\' method', function () {
}) })
}) })
it('returns an appropriate representation of Lua status reply', function (done) { it('returns an appropriate representation of Lua status reply', (done) => {
client.eval('local foo = redis.call(\'set\',\'mykey\',\'myval\'); return {type(foo),foo[\'ok\']}', 0, function (err, res) { client.eval('local foo = redis.call(\'set\',\'mykey\',\'myval\'); return {type(foo),foo[\'ok\']}', 0, (err, res) => {
assert.strictEqual(2, res.length) assert.strictEqual(2, res.length)
assert.strictEqual('table', res[0]) assert.strictEqual('table', res[0])
assert.strictEqual('OK', res[1]) assert.strictEqual('OK', res[1])
@@ -167,10 +167,10 @@ describe('The \'eval\' method', function () {
}) })
}) })
it('returns an appropriate representation of a Lua error reply', function (done) { it('returns an appropriate representation of a Lua error reply', (done) => {
client.set('error reply key', 'error reply value', function (err, res) { client.set('error reply key', 'error reply value', (err, res) => {
if (err) return done(err) if (err) return done(err)
client.eval('local foo = redis.pcall(\'incr\',\'error reply key\'); return {type(foo),foo[\'err\']}', 0, function (err, res) { client.eval('local foo = redis.pcall(\'incr\',\'error reply key\'); return {type(foo),foo[\'err\']}', 0, (err, res) => {
assert.strictEqual(2, res.length) assert.strictEqual(2, res.length)
assert.strictEqual('table', res[0]) assert.strictEqual('table', res[0])
assert.strictEqual('ERR value is not an integer or out of range', res[1]) assert.strictEqual('ERR value is not an integer or out of range', res[1])
@@ -179,10 +179,10 @@ describe('The \'eval\' method', function () {
}) })
}) })
it('returns an appropriate representation of a Lua nil reply', function (done) { it('returns an appropriate representation of a Lua nil reply', (done) => {
client.del('nil reply key', function (err, res) { client.del('nil reply key', (err, res) => {
if (err) return done(err) if (err) return done(err)
client.eval('local foo = redis.call(\'get\',\'nil reply key\'); return {type(foo),foo == false}', 0, function (err, res) { client.eval('local foo = redis.call(\'get\',\'nil reply key\'); return {type(foo),foo == false}', 0, (err, res) => {
if (err) throw err if (err) throw err
assert.strictEqual(2, res.length) assert.strictEqual(2, res.length)
assert.strictEqual('boolean', res[0]) assert.strictEqual('boolean', res[0])

View File

@@ -1,36 +1,36 @@
'use strict' 'use strict'
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'exists\' method', function () { describe('The \'exists\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('returns 1 if the key exists', function (done) { it('returns 1 if the key exists', (done) => {
client.set('foo', 'bar') client.set('foo', 'bar')
client.exists('foo', helper.isNumber(1, done)) client.exists('foo', helper.isNumber(1, done))
}) })
it('returns 1 if the key exists with array syntax', function (done) { it('returns 1 if the key exists with array syntax', (done) => {
client.set('foo', 'bar') client.set('foo', 'bar')
client.exists(['foo'], helper.isNumber(1, done)) client.exists(['foo'], helper.isNumber(1, done))
}) })
it('returns 0 if the key does not exist', function (done) { it('returns 0 if the key does not exist', (done) => {
client.exists('bar', helper.isNumber(0, done)) client.exists('bar', helper.isNumber(0, done))
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,38 +1,38 @@
'use strict' 'use strict'
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'expire\' method', function () { describe('The \'expire\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('expires key after timeout', function (done) { it('expires key after timeout', (done) => {
client.set(['expiry key', 'bar'], helper.isString('OK')) client.set(['expiry key', 'bar'], helper.isString('OK'))
client.expire('expiry key', '1', helper.isNumber(1)) client.expire('expiry key', '1', helper.isNumber(1))
setTimeout(function () { setTimeout(() => {
client.exists(['expiry key'], helper.isNumber(0, done)) client.exists(['expiry key'], helper.isNumber(0, done))
}, 1050) }, 1050)
}) })
it('expires key after timeout with array syntax', function (done) { it('expires key after timeout with array syntax', (done) => {
client.set(['expiry key', 'bar'], helper.isString('OK')) client.set(['expiry key', 'bar'], helper.isString('OK'))
client.expire(['expiry key', '1'], helper.isNumber(1)) client.expire(['expiry key', '1'], helper.isNumber(1))
setTimeout(function () { setTimeout(() => {
client.exists(['expiry key'], helper.isNumber(0, done)) client.exists(['expiry key'], helper.isNumber(0, done))
}, 1050) }, 1050)
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,69 +1,69 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
var uuid = require('uuid') const uuid = require('uuid')
describe('The \'flushdb\' method', function () { describe('The \'flushdb\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var key, key2 let key, key2
beforeEach(function () { beforeEach(() => {
key = uuid.v4() key = uuid.v4()
key2 = uuid.v4() key2 = uuid.v4()
}) })
describe('when not connected', function () { describe('when not connected', () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.quit() client.quit()
}) })
client.on('end', done) client.on('end', done)
}) })
it('reports an error', function (done) { it('reports an error', (done) => {
client.flushdb(function (err, res) { client.flushdb((err, res) => {
assert(err.message.match(/The connection is already closed/)) assert(err.message.match(/The connection is already closed/))
done() done()
}) })
}) })
}) })
describe('when connected', function () { describe('when connected', () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
done() done()
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
describe('when there is data in Redis', function () { describe('when there is data in Redis', () => {
beforeEach(function (done) { beforeEach((done) => {
client.mset(key, uuid.v4(), key2, uuid.v4(), helper.isNotError()) client.mset(key, uuid.v4(), key2, uuid.v4(), helper.isNotError())
client.dbsize([], function (err, res) { client.dbsize([], (err, res) => {
helper.isType.positiveNumber()(err, res) helper.isType.positiveNumber()(err, res)
assert.strictEqual(res, 2, 'Two keys should have been inserted') assert.strictEqual(res, 2, 'Two keys should have been inserted')
done() done()
}) })
}) })
it('deletes all the keys', function (done) { it('deletes all the keys', (done) => {
client.flushdb(function (err, res) { client.flushdb((err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res, 'OK') assert.strictEqual(res, 'OK')
client.mget(key, key2, function (err, res) { client.mget(key, key2, (err, res) => {
assert.strictEqual(null, err, 'Unexpected error returned') assert.strictEqual(null, err, 'Unexpected error returned')
assert.strictEqual(true, Array.isArray(res), 'Results object should be an array.') assert.strictEqual(true, Array.isArray(res), 'Results object should be an array.')
assert.strictEqual(2, res.length, 'Results array should have length 2.') assert.strictEqual(2, res.length, 'Results array should have length 2.')
@@ -74,16 +74,16 @@ describe('The \'flushdb\' method', function () {
}) })
}) })
it('results in a db size of zero', function (done) { it('results in a db size of zero', (done) => {
client.flushdb(function (err, res) { client.flushdb((err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
client.dbsize([], helper.isNumber(0, done)) client.dbsize([], helper.isNumber(0, done))
}) })
}) })
it('results in a db size of zero without a callback', function (done) { it('results in a db size of zero without a callback', (done) => {
client.flushdb() client.flushdb()
setTimeout(function () { setTimeout(() => {
client.dbsize(helper.isNumber(0, done)) client.dbsize(helper.isNumber(0, done))
}, 25) }, 25)
}) })

View File

@@ -1,31 +1,31 @@
'use strict' 'use strict'
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'geoadd\' method', function () { describe('The \'geoadd\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('returns 1 if the key exists', function (done) { it('returns 1 if the key exists', function (done) {
helper.serverVersionAtLeast.call(this, client, [3, 2, 0]) helper.serverVersionAtLeast.call(this, client, [3, 2, 0])
client.geoadd('mycity:21:0:location', '13.361389', '38.115556', 'COR', function (err, res) { client.geoadd('mycity:21:0:location', '13.361389', '38.115556', 'COR', (err, res) => {
console.log(err, res) console.log(err, res)
// geoadd is still in the unstable branch. As soon as it reaches the stable one, activate this test // geoadd is still in the unstable branch. As soon as it reaches the stable one, activate this test
done() done()
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,87 +1,87 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
var uuid = require('uuid') const uuid = require('uuid')
describe('The \'get\' method', function () { describe('The \'get\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var key, value let key, value
beforeEach(function () { beforeEach(() => {
key = uuid.v4() key = uuid.v4()
value = uuid.v4() value = uuid.v4()
}) })
describe('when not connected', function () { describe('when not connected', () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.quit() client.quit()
}) })
client.on('end', done) client.on('end', done)
}) })
it('reports an error', function (done) { it('reports an error', (done) => {
client.get(key, function (err, res) { client.get(key, (err, res) => {
assert(err.message.match(/The connection is already closed/)) assert(err.message.match(/The connection is already closed/))
done() done()
}) })
}) })
it('reports an error promisified', function () { it('reports an error promisified', () => {
return client.getAsync(key).then(assert, function (err) { return client.getAsync(key).then(assert, (err) => {
assert(err.message.match(/The connection is already closed/)) assert(err.message.match(/The connection is already closed/))
}) })
}) })
}) })
describe('when connected', function () { describe('when connected', () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
done() done()
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
describe('when the key exists in Redis', function () { describe('when the key exists in Redis', () => {
beforeEach(function (done) { beforeEach((done) => {
client.set(key, value, function (err, res) { client.set(key, value, (err, res) => {
helper.isNotError()(err, res) helper.isNotError()(err, res)
done() done()
}) })
}) })
it('gets the value correctly', function (done) { it('gets the value correctly', (done) => {
client.get(key, function (err, res) { client.get(key, (err, res) => {
helper.isString(value)(err, res) helper.isString(value)(err, res)
done(err) done(err)
}) })
}) })
it('should not throw on a get without callback (even if it\'s not useful)', function (done) { it('should not throw on a get without callback (even if it\'s not useful)', (done) => {
client.get(key) client.get(key)
client.on('error', function (err) { client.on('error', (err) => {
throw err throw err
}) })
setTimeout(done, 25) setTimeout(done, 25)
}) })
}) })
describe('when the key does not exist in Redis', function () { describe('when the key does not exist in Redis', () => {
it('gets a null value', function (done) { it('gets a null value', (done) => {
client.get(key, function (err, res) { client.get(key, (err, res) => {
helper.isNull()(err, res) helper.isNull()(err, res)
done(err) done(err)
}) })

View File

@@ -1,87 +1,87 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
var uuid = require('uuid') const uuid = require('uuid')
describe('The \'getset\' method', function () { describe('The \'getset\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var key, value, value2 let key, value, value2
beforeEach(function () { beforeEach(() => {
key = uuid.v4() key = uuid.v4()
value = uuid.v4() value = uuid.v4()
value2 = uuid.v4() value2 = uuid.v4()
}) })
describe('when not connected', function () { describe('when not connected', () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.quit() client.quit()
}) })
client.on('end', done) client.on('end', done)
}) })
it('reports an error', function (done) { it('reports an error', (done) => {
client.get(key, function (err, res) { client.get(key, (err, res) => {
assert(err.message.match(/The connection is already closed/)) assert(err.message.match(/The connection is already closed/))
done() done()
}) })
}) })
}) })
describe('when connected', function () { describe('when connected', () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
done() done()
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
describe('when the key exists in Redis', function () { describe('when the key exists in Redis', () => {
beforeEach(function (done) { beforeEach((done) => {
client.set(key, value, function (err, res) { client.set(key, value, (err, res) => {
helper.isNotError()(err, res) helper.isNotError()(err, res)
done() done()
}) })
}) })
it('gets the value correctly', function (done) { it('gets the value correctly', (done) => {
client.getset(key, value2, function (err, res) { client.getset(key, value2, (err, res) => {
helper.isString(value)(err, res) helper.isString(value)(err, res)
client.get(key, function (err, res) { client.get(key, (err, res) => {
helper.isString(value2)(err, res) helper.isString(value2)(err, res)
done(err) done(err)
}) })
}) })
}) })
it('gets the value correctly with array syntax', function (done) { it('gets the value correctly with array syntax', (done) => {
client.getset([key, value2], function (err, res) { client.getset([key, value2], (err, res) => {
helper.isString(value)(err, res) helper.isString(value)(err, res)
client.get(key, function (err, res) { client.get(key, (err, res) => {
helper.isString(value2)(err, res) helper.isString(value2)(err, res)
done(err) done(err)
}) })
}) })
}) })
it('gets the value correctly with array syntax style 2', function (done) { it('gets the value correctly with array syntax style 2', (done) => {
client.getset(key, [value2], function (err, res) { client.getset(key, [value2], (err, res) => {
helper.isString(value)(err, res) helper.isString(value)(err, res)
client.get(key, function (err, res) { client.get(key, (err, res) => {
helper.isString(value2)(err, res) helper.isString(value2)(err, res)
done(err) done(err)
}) })
@@ -89,9 +89,9 @@ describe('The \'getset\' method', function () {
}) })
}) })
describe('when the key does not exist in Redis', function () { describe('when the key does not exist in Redis', () => {
it('gets a null value', function (done) { it('gets a null value', (done) => {
client.getset(key, value, function (err, res) { client.getset(key, value, (err, res) => {
helper.isNull()(err, res) helper.isNull()(err, res)
done(err) done(err)
}) })

View File

@@ -1,27 +1,27 @@
'use strict' 'use strict'
var Buffer = require('safe-buffer').Buffer const Buffer = require('safe-buffer').Buffer
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'hgetall\' method', function () { describe('The \'hgetall\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
describe('regular client', function () { describe('regular client', () => {
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('handles simple keys and values', function (done) { it('handles simple keys and values', (done) => {
client.hmset(['hosts', 'hasOwnProperty', '1', 'another', '23', 'home', '1234'], helper.isString('OK')) client.hmset(['hosts', 'hasOwnProperty', '1', 'another', '23', 'home', '1234'], helper.isString('OK'))
client.hgetall(['hosts'], function (err, obj) { client.hgetall(['hosts'], (err, obj) => {
assert.strictEqual(3, Object.keys(obj).length) assert.strictEqual(3, Object.keys(obj).length)
assert.strictEqual('1', obj.hasOwnProperty.toString()) assert.strictEqual('1', obj.hasOwnProperty.toString())
assert.strictEqual('23', obj.another.toString()) assert.strictEqual('23', obj.another.toString())
@@ -30,39 +30,39 @@ describe('The \'hgetall\' method', function () {
}) })
}) })
it('handles fetching keys set using an object', function (done) { it('handles fetching keys set using an object', (done) => {
client.batch().hmset('msgTest', { message: 'hello' }, undefined).exec() client.batch().hmset('msgTest', { message: 'hello' }, undefined).exec()
client.hgetall('msgTest', function (err, obj) { client.hgetall('msgTest', (err, obj) => {
assert.strictEqual(1, Object.keys(obj).length) assert.strictEqual(1, Object.keys(obj).length)
assert.strictEqual(obj.message, 'hello') assert.strictEqual(obj.message, 'hello')
done(err) done(err)
}) })
}) })
it('handles fetching a messing key', function (done) { it('handles fetching a messing key', (done) => {
client.hgetall('missing', function (err, obj) { client.hgetall('missing', (err, obj) => {
assert.strictEqual(null, obj) assert.strictEqual(null, obj)
done(err) done(err)
}) })
}) })
}) })
describe('binary client', function () { describe('binary client', () => {
var client let client
var args = config.configureClient(ip, { const args = config.configureClient(ip, {
returnBuffers: true returnBuffers: true
}) })
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('returns binary results', function (done) { it('returns binary results', (done) => {
client.hmset(['bhosts', 'mjr', '1', 'another', '23', 'home', '1234', Buffer.from([0xAA, 0xBB, 0x00, 0xF0]), Buffer.from([0xCC, 0xDD, 0x00, 0xF0])], helper.isString('OK')) client.hmset(['bhosts', 'mjr', '1', 'another', '23', 'home', '1234', Buffer.from([0xAA, 0xBB, 0x00, 0xF0]), Buffer.from([0xCC, 0xDD, 0x00, 0xF0])], helper.isString('OK'))
client.hgetall('bhosts', function (err, obj) { client.hgetall('bhosts', (err, obj) => {
assert.strictEqual(4, Object.keys(obj).length) assert.strictEqual(4, Object.keys(obj).length)
assert.strictEqual('1', obj.mjr.toString()) assert.strictEqual('1', obj.mjr.toString())
assert.strictEqual('23', obj.another.toString()) assert.strictEqual('23', obj.another.toString())
@@ -74,7 +74,7 @@ describe('The \'hgetall\' method', function () {
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,36 +1,36 @@
'use strict' 'use strict'
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'hincrby\' method', function () { describe('The \'hincrby\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
var hash = 'test hash' const hash = 'test hash'
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('increments a key that has already been set', function (done) { it('increments a key that has already been set', (done) => {
var field = 'field 1' const field = 'field 1'
client.hset(hash, field, 33) client.hset(hash, field, 33)
client.hincrby(hash, field, 10, helper.isNumber(43, done)) client.hincrby(hash, field, 10, helper.isNumber(43, done))
}) })
it('increments a key that has not been set', function (done) { it('increments a key that has not been set', (done) => {
var field = 'field 2' const field = 'field 2'
client.hincrby(hash, field, 10, helper.isNumber(10, done)) client.hincrby(hash, field, 10, helper.isNumber(10, done))
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,35 +1,35 @@
'use strict' 'use strict'
var Buffer = require('safe-buffer').Buffer const Buffer = require('safe-buffer').Buffer
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'hlen\' method', function () { describe('The \'hlen\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('reports the count of keys', function (done) { it('reports the count of keys', (done) => {
var hash = 'test hash' const hash = 'test hash'
var field1 = Buffer.from('0123456789') const field1 = Buffer.from('0123456789')
var value1 = Buffer.from('abcdefghij') const value1 = Buffer.from('abcdefghij')
var field2 = Buffer.from('') const field2 = Buffer.from('')
var value2 = Buffer.from('') const value2 = Buffer.from('')
client.hset(hash, field1, value1, helper.isNumber(1)) client.hset(hash, field1, value1, helper.isNumber(1))
client.hset(hash, field2, value2, helper.isNumber(1)) client.hset(hash, field2, value2, helper.isNumber(1))
client.hlen(hash, helper.isNumber(2, done)) client.hlen(hash, helper.isNumber(2, done))
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,36 +1,36 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'hmget\' method', function () { describe('The \'hmget\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
var hash = 'test hash' const hash = 'test hash'
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('error', done) client.once('error', done)
client.once('ready', function () { client.once('ready', () => {
client.flushdb() client.flushdb()
client.hmset(hash, {'0123456789': 'abcdefghij', 'some manner of key': 'a type of value'}, helper.isString('OK', done)) client.hmset(hash, {'0123456789': 'abcdefghij', 'some manner of key': 'a type of value'}, helper.isString('OK', done))
}) })
}) })
it('allows keys to be specified using multiple arguments', function (done) { it('allows keys to be specified using multiple arguments', (done) => {
client.hmget(hash, '0123456789', 'some manner of key', function (err, reply) { client.hmget(hash, '0123456789', 'some manner of key', (err, reply) => {
assert.strictEqual('abcdefghij', reply[0].toString()) assert.strictEqual('abcdefghij', reply[0].toString())
assert.strictEqual('a type of value', reply[1].toString()) assert.strictEqual('a type of value', reply[1].toString())
return done(err) return done(err)
}) })
}) })
it('allows keys to be specified by passing an array without manipulating the array', function (done) { it('allows keys to be specified by passing an array without manipulating the array', (done) => {
var data = ['0123456789', 'some manner of key'] const data = ['0123456789', 'some manner of key']
client.hmget(hash, data, function (err, reply) { client.hmget(hash, data, (err, reply) => {
assert.strictEqual(data.length, 2) assert.strictEqual(data.length, 2)
assert.strictEqual('abcdefghij', reply[0].toString()) assert.strictEqual('abcdefghij', reply[0].toString())
assert.strictEqual('a type of value', reply[1].toString()) assert.strictEqual('a type of value', reply[1].toString())
@@ -38,30 +38,30 @@ describe('The \'hmget\' method', function () {
}) })
}) })
it('allows keys to be specified by passing an array as first argument', function (done) { it('allows keys to be specified by passing an array as first argument', (done) => {
client.hmget([hash, '0123456789', 'some manner of key'], function (err, reply) { client.hmget([hash, '0123456789', 'some manner of key'], (err, reply) => {
assert.strictEqual('abcdefghij', reply[0].toString()) assert.strictEqual('abcdefghij', reply[0].toString())
assert.strictEqual('a type of value', reply[1].toString()) assert.strictEqual('a type of value', reply[1].toString())
return done(err) return done(err)
}) })
}) })
it('allows a single key to be specified in an array', function (done) { it('allows a single key to be specified in an array', (done) => {
client.hmget(hash, ['0123456789'], function (err, reply) { client.hmget(hash, ['0123456789'], (err, reply) => {
assert.strictEqual('abcdefghij', reply[0].toString()) assert.strictEqual('abcdefghij', reply[0].toString())
return done(err) return done(err)
}) })
}) })
it('allows keys to be specified that have not yet been set', function (done) { it('allows keys to be specified that have not yet been set', (done) => {
client.hmget(hash, 'missing thing', 'another missing thing', function (err, reply) { client.hmget(hash, 'missing thing', 'another missing thing', (err, reply) => {
assert.strictEqual(null, reply[0]) assert.strictEqual(null, reply[0])
assert.strictEqual(null, reply[1]) assert.strictEqual(null, reply[1])
return done(err) return done(err)
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,113 +1,113 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'hmset\' method', function () { describe('The \'hmset\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
var hash = 'test hash' const hash = 'test hash'
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('handles redis-style syntax', function (done) { it('handles redis-style syntax', (done) => {
client.hmset(hash, '0123456789', 'abcdefghij', 'some manner of key', 'a type of value', 'otherTypes', 555, helper.isString('OK')) client.hmset(hash, '0123456789', 'abcdefghij', 'some manner of key', 'a type of value', 'otherTypes', 555, helper.isString('OK'))
client.hgetall(hash, function (err, obj) { client.hgetall(hash, (err, obj) => {
assert.strictEqual(obj['0123456789'], 'abcdefghij') assert.strictEqual(obj['0123456789'], 'abcdefghij')
assert.strictEqual(obj['some manner of key'], 'a type of value') assert.strictEqual(obj['some manner of key'], 'a type of value')
return done(err) return done(err)
}) })
}) })
it('handles object-style syntax', function (done) { it('handles object-style syntax', (done) => {
client.hmset(hash, {'0123456789': 'abcdefghij', 'some manner of key': 'a type of value', 'otherTypes': 555}, helper.isString('OK')) client.hmset(hash, {'0123456789': 'abcdefghij', 'some manner of key': 'a type of value', 'otherTypes': 555}, helper.isString('OK'))
client.hgetall(hash, function (err, obj) { client.hgetall(hash, (err, obj) => {
assert.strictEqual(obj['0123456789'], 'abcdefghij') assert.strictEqual(obj['0123456789'], 'abcdefghij')
assert.strictEqual(obj['some manner of key'], 'a type of value') assert.strictEqual(obj['some manner of key'], 'a type of value')
return done(err) return done(err)
}) })
}) })
it('handles object-style syntax and the key being a number', function (done) { it('handles object-style syntax and the key being a number', (done) => {
client.hmset(231232, {'0123456789': 'abcdefghij', 'some manner of key': 'a type of value', 'otherTypes': 555}, undefined) client.hmset(231232, {'0123456789': 'abcdefghij', 'some manner of key': 'a type of value', 'otherTypes': 555}, undefined)
client.hgetall(231232, function (err, obj) { client.hgetall(231232, (err, obj) => {
assert.strictEqual(obj['0123456789'], 'abcdefghij') assert.strictEqual(obj['0123456789'], 'abcdefghij')
assert.strictEqual(obj['some manner of key'], 'a type of value') assert.strictEqual(obj['some manner of key'], 'a type of value')
return done(err) return done(err)
}) })
}) })
it('allows a numeric key', function (done) { it('allows a numeric key', (done) => {
client.hmset(hash, 99, 'banana', helper.isString('OK')) client.hmset(hash, 99, 'banana', helper.isString('OK'))
client.hgetall(hash, function (err, obj) { client.hgetall(hash, (err, obj) => {
assert.strictEqual(obj['99'], 'banana') assert.strictEqual(obj['99'], 'banana')
return done(err) return done(err)
}) })
}) })
it('allows a numeric key without callback', function (done) { it('allows a numeric key without callback', (done) => {
client.hmset(hash, 99, 'banana', 'test', 25) client.hmset(hash, 99, 'banana', 'test', 25)
client.hgetall(hash, function (err, obj) { client.hgetall(hash, (err, obj) => {
assert.strictEqual(obj['99'], 'banana') assert.strictEqual(obj['99'], 'banana')
assert.strictEqual(obj.test, '25') assert.strictEqual(obj.test, '25')
return done(err) return done(err)
}) })
}) })
it('allows an array without callback', function (done) { it('allows an array without callback', (done) => {
client.hmset([hash, 99, 'banana', 'test', 25]) client.hmset([hash, 99, 'banana', 'test', 25])
client.hgetall(hash, function (err, obj) { client.hgetall(hash, (err, obj) => {
assert.strictEqual(obj['99'], 'banana') assert.strictEqual(obj['99'], 'banana')
assert.strictEqual(obj.test, '25') assert.strictEqual(obj.test, '25')
return done(err) return done(err)
}) })
}) })
it('allows an array and a callback', function (done) { it('allows an array and a callback', (done) => {
client.hmset([hash, 99, 'banana', 'test', 25], helper.isString('OK')) client.hmset([hash, 99, 'banana', 'test', 25], helper.isString('OK'))
client.hgetall(hash, function (err, obj) { client.hgetall(hash, (err, obj) => {
assert.strictEqual(obj['99'], 'banana') assert.strictEqual(obj['99'], 'banana')
assert.strictEqual(obj.test, '25') assert.strictEqual(obj.test, '25')
return done(err) return done(err)
}) })
}) })
it('allows a key plus array without callback', function (done) { it('allows a key plus array without callback', (done) => {
client.hmset(hash, [99, 'banana', 'test', 25]) client.hmset(hash, [99, 'banana', 'test', 25])
client.hgetall(hash, function (err, obj) { client.hgetall(hash, (err, obj) => {
assert.strictEqual(obj['99'], 'banana') assert.strictEqual(obj['99'], 'banana')
assert.strictEqual(obj.test, '25') assert.strictEqual(obj.test, '25')
return done(err) return done(err)
}) })
}) })
it('allows a key plus array and a callback', function (done) { it('allows a key plus array and a callback', (done) => {
client.hmset(hash, [99, 'banana', 'test', 25], helper.isString('OK')) client.hmset(hash, [99, 'banana', 'test', 25], helper.isString('OK'))
client.hgetall(hash, function (err, obj) { client.hgetall(hash, (err, obj) => {
assert.strictEqual(obj['99'], 'banana') assert.strictEqual(obj['99'], 'banana')
assert.strictEqual(obj.test, '25') assert.strictEqual(obj.test, '25')
return done(err) return done(err)
}) })
}) })
it('handles object-style syntax without callback', function (done) { it('handles object-style syntax without callback', (done) => {
client.hmset(hash, {'0123456789': 'abcdefghij', 'some manner of key': 'a type of value'}) client.hmset(hash, {'0123456789': 'abcdefghij', 'some manner of key': 'a type of value'})
client.hgetall(hash, function (err, obj) { client.hgetall(hash, (err, obj) => {
assert.strictEqual(obj['0123456789'], 'abcdefghij') assert.strictEqual(obj['0123456789'], 'abcdefghij')
assert.strictEqual(obj['some manner of key'], 'a type of value') assert.strictEqual(obj['some manner of key'], 'a type of value')
return done(err) return done(err)
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,89 +1,80 @@
'use strict' 'use strict'
var Buffer = require('safe-buffer').Buffer const Buffer = require('safe-buffer').Buffer
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'hset\' method', function () { describe('The \'hset\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
var hash = 'test hash' const hash = 'test hash'
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('allows a value to be set in a hash', function (done) { it('allows a value to be set in a hash', (done) => {
var field = Buffer.from('0123456789') const field = Buffer.from('0123456789')
var value = Buffer.from('abcdefghij') const value = Buffer.from('abcdefghij')
client.hset(hash, field, value, helper.isNumber(1)) client.hset(hash, field, value, helper.isNumber(1))
client.hget(hash, field, helper.isString(value.toString(), done)) client.hget(hash, field, helper.isString(value.toString(), done))
}) })
it('handles an empty value', function (done) { it('handles an empty value', (done) => {
var field = Buffer.from('0123456789') const field = Buffer.from('0123456789')
var value = Buffer.from('') const value = Buffer.from('')
client.hset(hash, field, value, helper.isNumber(1)) client.hset(hash, field, value, helper.isNumber(1))
client.hget([hash, field], helper.isString('', done)) client.hget([hash, field], helper.isString('', done))
}) })
it('handles empty key and value', function (done) { it('handles empty key and value', (done) => {
var field = Buffer.from('') const field = Buffer.from('')
var value = Buffer.from('') const value = Buffer.from('')
client.hset([hash, field, value], function (err, res) { client.hset([hash, field, value], (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res, 1) assert.strictEqual(res, 1)
client.hset(hash, field, value, helper.isNumber(0, done)) client.hset(hash, field, value, helper.isNumber(0, done))
}) })
}) })
it('warns if someone passed a array either as field or as value', function (done) { it('warns if someone passed a array either as field or as value', (done) => {
var hash = 'test hash' const hash = 'test hash'
var field = 'array' const field = 'array'
// This would be converted to "array contents" but if you use more than one entry, // This would be converted to "array contents" but if you use more than one entry,
// it'll result in e.g. "array contents,second content" and this is not supported and considered harmful // it'll result in e.g. "array contents,second content" and this is not supported and considered harmful
var value = ['array contents'] const value = ['array contents']
client.on('warning', function (msg) { client.hmset(hash, field, value, helper.isError(done))
assert.strictEqual(
msg,
'Deprecated: The HMSET command contains a argument of type Array.\n' +
'This is converted to "array contents" by using .toString() now and will return an error from v.3.0 on.\n' +
'Please handle this in your code to make sure everything works as you intended it to.'
)
done()
})
client.hmset(hash, field, value)
}) })
it('does not error when a buffer and date are set as values on the same hash', function (done) { it('does not error when a buffer and date are set as values on the same hash', (done) => {
var hash = 'test hash' const hash = 'test hash'
var field1 = 'buffer' const field1 = 'buffer'
var value1 = Buffer.from('abcdefghij') const value1 = Buffer.from('abcdefghij')
var field2 = 'date' const field2 = 'date'
var value2 = new Date() const value2 = new Date()
client.hmset(hash, field1, value1, field2, value2, helper.isString('OK', done)) client.hmset(hash, field1, value1, field2, value2, helper.isString('OK', done))
}) })
it('does not error when a buffer and date are set as fields on the same hash', function (done) { it('does not error when a buffer and date are set as fields on the same hash', (done) => {
var hash = 'test hash' const hash = 'test hash'
var value1 = 'buffer' const value1 = 'buffer'
var field1 = Buffer.from('abcdefghij') const field1 = Buffer.from('abcdefghij')
var value2 = 'date' const value2 = 'date'
var field2 = new Date() const field2 = new Date()
client.hmset(hash, field1, value1, field2, value2, helper.isString('OK', done)) client.hmset(hash, field1, value1, field2, value2, helper.isString('OK', done))
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,18 +1,18 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'incr\' method', function () { describe('The \'incr\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
describe('when connected and a value in Redis', function () { describe('when connected and a value in Redis', () => {
var client let client
var key = 'ABOVE_SAFE_JAVASCRIPT_INTEGER' const key = 'ABOVE_SAFE_JAVASCRIPT_INTEGER'
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
@@ -27,7 +27,7 @@ describe('The \'incr\' method', function () {
9007199254740997 -> 9007199254740996 9007199254740997 -> 9007199254740996
... ...
*/ */
it('count above the safe integers as numbers', function (done) { it('count above the safe integers as numbers', (done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
// Set a value to the maximum safe allowed javascript number (2^53) - 1 // Set a value to the maximum safe allowed javascript number (2^53) - 1
client.set(key, Number.MAX_SAFE_INTEGER, helper.isNotError()) client.set(key, Number.MAX_SAFE_INTEGER, helper.isNotError())
@@ -36,7 +36,7 @@ describe('The \'incr\' method', function () {
client.incr(key, helper.isNumber(Number.MAX_SAFE_INTEGER + 3)) client.incr(key, helper.isNumber(Number.MAX_SAFE_INTEGER + 3))
client.incr(key, helper.isNumber(Number.MAX_SAFE_INTEGER + 4)) client.incr(key, helper.isNumber(Number.MAX_SAFE_INTEGER + 4))
client.incr(key, helper.isNumber(Number.MAX_SAFE_INTEGER + 5)) client.incr(key, helper.isNumber(Number.MAX_SAFE_INTEGER + 5))
client.incr(key, function (err, res) { client.incr(key, (err, res) => {
helper.isNumber(Number.MAX_SAFE_INTEGER + 6)(err, res) helper.isNumber(Number.MAX_SAFE_INTEGER + 6)(err, res)
assert.strictEqual(typeof res, 'number') assert.strictEqual(typeof res, 'number')
}) })
@@ -46,7 +46,7 @@ describe('The \'incr\' method', function () {
client.incr(key, helper.isNumber(Number.MAX_SAFE_INTEGER + 10, done)) client.incr(key, helper.isNumber(Number.MAX_SAFE_INTEGER + 10, done))
}) })
it('count above the safe integers as strings', function (done) { it('count above the safe integers as strings', (done) => {
args[2].stringNumbers = true args[2].stringNumbers = true
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
// Set a value to the maximum safe allowed javascript number (2^53) // Set a value to the maximum safe allowed javascript number (2^53)
@@ -56,7 +56,7 @@ describe('The \'incr\' method', function () {
client.incr(key, helper.isString('9007199254740994')) client.incr(key, helper.isString('9007199254740994'))
client.incr(key, helper.isString('9007199254740995')) client.incr(key, helper.isString('9007199254740995'))
client.incr(key, helper.isString('9007199254740996')) client.incr(key, helper.isString('9007199254740996'))
client.incr(key, function (err, res) { client.incr(key, (err, res) => {
helper.isString('9007199254740997')(err, res) helper.isString('9007199254740997')(err, res)
assert.strictEqual(typeof res, 'string') assert.strictEqual(typeof res, 'string')
}) })

View File

@@ -1,50 +1,50 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'info\' method', function () { describe('The \'info\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushall(done) client.flushall(done)
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
it('update serverInfo after a info command', function (done) { it('update serverInfo after a info command', (done) => {
client.set('foo', 'bar') client.set('foo', 'bar')
client.info() client.info()
client.select(2, function () { client.select(2, () => {
assert.strictEqual(client.serverInfo.db2, undefined) assert.strictEqual(client.serverInfo.db2, undefined)
}) })
client.set('foo', 'bar') client.set('foo', 'bar')
client.info() client.info()
setTimeout(function () { setTimeout(() => {
assert.strictEqual(typeof client.serverInfo.db2, 'object') assert.strictEqual(typeof client.serverInfo.db2, 'object')
done() done()
}, 30) }, 30)
}) })
it('works with optional section provided with and without callback', function (done) { it('works with optional section provided with and without callback', (done) => {
client.set('foo', 'bar') client.set('foo', 'bar')
client.info('keyspace') client.info('keyspace')
client.select(2, function () { client.select(2, () => {
assert.strictEqual(Object.keys(client.serverInfo).length, 2, 'Key length should be three') assert.strictEqual(Object.keys(client.serverInfo).length, 2, 'Key length should be three')
assert.strictEqual(typeof client.serverInfo.db0, 'object', 'db0 keyspace should be an object') assert.strictEqual(typeof client.serverInfo.db0, 'object', 'db0 keyspace should be an object')
}) })
client.info(['keyspace']) client.info(['keyspace'])
client.set('foo', 'bar') client.set('foo', 'bar')
client.info('all', function (err, res) { client.info('all', (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert(Object.keys(client.serverInfo).length > 3, 'Key length should be way above three') assert(Object.keys(client.serverInfo).length > 3, 'Key length should be way above three')
assert.strictEqual(typeof client.serverInfo.redis_version, 'string') assert.strictEqual(typeof client.serverInfo.redis_version, 'string')
@@ -53,20 +53,20 @@ describe('The \'info\' method', function () {
}) })
}) })
it('check redis v.2.4 support', function (done) { it('check redis v.2.4 support', (done) => {
var end = helper.callFuncAfter(done, 2) const end = helper.callFuncAfter(done, 2)
client.internalSendCommand = function (commandObj) { client.internalSendCommand = function (commandObj) {
assert.strictEqual(commandObj.args.length, 0) assert.strictEqual(commandObj.args.length, 0)
assert.strictEqual(commandObj.command, 'info') assert.strictEqual(commandObj.command, 'info')
end() end()
} }
client.info() client.info()
client.info(function () {}) client.info(() => {})
}) })
it('emit error after a failure', function (done) { it('emit error after a failure', (done) => {
client.info() client.info()
client.once('error', function (err) { client.once('error', (err) => {
assert.strictEqual(err.code, 'UNCERTAIN_STATE') assert.strictEqual(err.code, 'UNCERTAIN_STATE')
assert.strictEqual(err.command, 'INFO') assert.strictEqual(err.command, 'INFO')
done() done()

View File

@@ -1,26 +1,26 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var crypto = require('crypto') const crypto = require('crypto')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'keys\' method', function () { describe('The \'keys\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushall(done) client.flushall(done)
}) })
}) })
it('returns matching keys', function (done) { it('returns matching keys', (done) => {
client.mset(['test keys 1', 'test val 1', 'test keys 2', 'test val 2'], helper.isString('OK')) client.mset(['test keys 1', 'test val 1', 'test keys 2', 'test val 2'], helper.isString('OK'))
client.keys('test keys*', function (err, results) { client.keys('test keys*', (err, results) => {
assert.strictEqual(2, results.length) assert.strictEqual(2, results.length)
assert.ok(~results.indexOf('test keys 1')) assert.ok(~results.indexOf('test keys 1'))
assert.ok(~results.indexOf('test keys 2')) assert.ok(~results.indexOf('test keys 2'))
@@ -28,38 +28,38 @@ describe('The \'keys\' method', function () {
}) })
}) })
it('handles a large packet size', function (done) { it('handles a large packet size', (done) => {
var keysValues = [] const keysValues = []
for (var i = 0; i < 200; i++) { for (let i = 0; i < 200; i++) {
var keyValue = [ const keyValue = [
'multibulk:' + crypto.randomBytes(256).toString('hex'), // use long strings as keys to ensure generation of large packet `multibulk:${crypto.randomBytes(256).toString('hex')}`, // use long strings as keys to ensure generation of large packet
'test val ' + i `test val ${i}`
] ]
keysValues.push(keyValue) keysValues.push(keyValue)
} }
client.mset(keysValues.reduce(function (a, b) { client.mset(keysValues.reduce((a, b) => {
return a.concat(b) return a.concat(b)
}), helper.isString('OK')) }), helper.isString('OK'))
client.keys('multibulk:*', function (err, results) { client.keys('multibulk:*', (err, results) => {
assert.deepEqual(keysValues.map(function (val) { assert.deepEqual(keysValues.map((val) => {
return val[0] return val[0]
}).sort(), results.sort()) }).sort(), results.sort())
return done(err) return done(err)
}) })
}) })
it('handles an empty response', function (done) { it('handles an empty response', (done) => {
client.keys(['users:*'], function (err, results) { client.keys(['users:*'], (err, results) => {
assert.strictEqual(results.length, 0) assert.strictEqual(results.length, 0)
assert.ok(Array.isArray(results)) assert.ok(Array.isArray(results))
return done(err) return done(err)
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,27 +1,27 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'mget\' method', function () { describe('The \'mget\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('error', done) client.once('error', done)
client.once('ready', function () { client.once('ready', () => {
client.flushdb() client.flushdb()
client.mset(['mget keys 1', 'mget val 1', 'mget keys 2', 'mget val 2', 'mget keys 3', 'mget val 3'], done) client.mset(['mget keys 1', 'mget val 1', 'mget keys 2', 'mget val 2', 'mget keys 3', 'mget val 3'], done)
}) })
}) })
it('handles fetching multiple keys in argument form', function (done) { it('handles fetching multiple keys in argument form', (done) => {
client.mset(['mget keys 1', 'mget val 1', 'mget keys 2', 'mget val 2', 'mget keys 3', 'mget val 3'], helper.isString('OK')) client.mset(['mget keys 1', 'mget val 1', 'mget keys 2', 'mget val 2', 'mget keys 3', 'mget val 3'], helper.isString('OK'))
client.mget('mget keys 1', 'mget keys 2', 'mget keys 3', function (err, results) { client.mget('mget keys 1', 'mget keys 2', 'mget keys 3', (err, results) => {
assert.strictEqual(3, results.length) assert.strictEqual(3, results.length)
assert.strictEqual('mget val 1', results[0].toString()) assert.strictEqual('mget val 1', results[0].toString())
assert.strictEqual('mget val 2', results[1].toString()) assert.strictEqual('mget val 2', results[1].toString())
@@ -30,8 +30,8 @@ describe('The \'mget\' method', function () {
}) })
}) })
it('handles fetching multiple keys via an array', function (done) { it('handles fetching multiple keys via an array', (done) => {
client.mget(['mget keys 1', 'mget keys 2', 'mget keys 3'], function (err, results) { client.mget(['mget keys 1', 'mget keys 2', 'mget keys 3'], (err, results) => {
assert.strictEqual('mget val 1', results[0].toString()) assert.strictEqual('mget val 1', results[0].toString())
assert.strictEqual('mget val 2', results[1].toString()) assert.strictEqual('mget val 2', results[1].toString())
assert.strictEqual('mget val 3', results[2].toString()) assert.strictEqual('mget val 3', results[2].toString())
@@ -39,8 +39,8 @@ describe('The \'mget\' method', function () {
}) })
}) })
it('handles fetching multiple keys, when some keys do not exist', function (done) { it('handles fetching multiple keys, when some keys do not exist', (done) => {
client.mget('mget keys 1', ['some random shit', 'mget keys 2', 'mget keys 3'], function (err, results) { client.mget('mget keys 1', ['some random shit', 'mget keys 2', 'mget keys 3'], (err, results) => {
assert.strictEqual(4, results.length) assert.strictEqual(4, results.length)
assert.strictEqual('mget val 1', results[0].toString()) assert.strictEqual('mget val 1', results[0].toString())
assert.strictEqual(null, results[1]) assert.strictEqual(null, results[1])
@@ -50,8 +50,8 @@ describe('The \'mget\' method', function () {
}) })
}) })
it('handles fetching multiple keys, when some keys do not exist promisified', function () { it('handles fetching multiple keys, when some keys do not exist promisified', () => {
return client.mgetAsync('mget keys 1', ['some random shit', 'mget keys 2', 'mget keys 3']).then(function (results) { return client.mgetAsync('mget keys 1', ['some random shit', 'mget keys 2', 'mget keys 3']).then((results) => {
assert.strictEqual(4, results.length) assert.strictEqual(4, results.length)
assert.strictEqual('mget val 1', results[0].toString()) assert.strictEqual('mget val 1', results[0].toString())
assert.strictEqual(null, results[1]) assert.strictEqual(null, results[1])
@@ -60,7 +60,7 @@ describe('The \'mget\' method', function () {
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,30 +1,30 @@
'use strict' 'use strict'
var Buffer = require('safe-buffer').Buffer const Buffer = require('safe-buffer').Buffer
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var utils = require('../../lib/utils') const utils = require('../../lib/utils')
var redis = config.redis const redis = config.redis
describe('The \'monitor\' method', function () { describe('The \'monitor\' method', () => {
helper.allTests(function (parser, ip, args) { helper.allTests((parser, ip, args) => {
var client let client
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('connect', function () { client.once('connect', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('monitors commands on all redis clients and works in the correct order', function (done) { it('monitors commands on all redis clients and works in the correct order', (done) => {
var monitorClient = redis.createClient.apply(null, args) const monitorClient = redis.createClient.apply(null, args)
var responses = [ const responses = [
['mget', 'some', 'keys', 'foo', 'bar'], ['mget', 'some', 'keys', 'foo', 'bar'],
['set', 'json', '{"foo":"123","bar":"sdflkdfsjk","another":false}'], ['set', 'json', '{"foo":"123","bar":"sdflkdfsjk","another":false}'],
['eval', 'return redis.call(\'set\', \'sha\', \'test\')', '0'], ['eval', 'return redis.call(\'set\', \'sha\', \'test\')', '0'],
@@ -34,11 +34,11 @@ describe('The \'monitor\' method', function () {
['mget', 'foo', 'baz'], ['mget', 'foo', 'baz'],
['subscribe', 'foo', 'baz'] ['subscribe', 'foo', 'baz']
] ]
var end = helper.callFuncAfter(done, 5) const end = helper.callFuncAfter(done, 5)
monitorClient.set('foo', 'bar') monitorClient.set('foo', 'bar')
monitorClient.flushdb() monitorClient.flushdb()
monitorClient.monitor(function (err, res) { monitorClient.monitor((err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res, 'OK') assert.strictEqual(res, 'OK')
client.mget('some', 'keys', 'foo', 'bar') client.mget('some', 'keys', 'foo', 'bar')
@@ -48,20 +48,20 @@ describe('The \'monitor\' method', function () {
another: false another: false
})) }))
client.eval('return redis.call(\'set\', \'sha\', \'test\')', 0) client.eval('return redis.call(\'set\', \'sha\', \'test\')', 0)
monitorClient.get('baz', function (err, res) { monitorClient.get('baz', (err, res) => {
assert.strictEqual(res, null) assert.strictEqual(res, null)
end(err) end(err)
}) })
monitorClient.set('foo', 'bar" "s are " " good!"', function (err, res) { monitorClient.set('foo', 'bar" "s are " " good!"', (err, res) => {
assert.strictEqual(res, 'OK') assert.strictEqual(res, 'OK')
end(err) end(err)
}) })
monitorClient.mget('foo', 'baz', function (err, res) { monitorClient.mget('foo', 'baz', (err, res) => {
assert.strictEqual(res[0], 'bar" "s are " " good!"') assert.strictEqual(res[0], 'bar" "s are " " good!"')
assert.strictEqual(res[1], null) assert.strictEqual(res[1], null)
end(err) end(err)
}) })
monitorClient.subscribe('foo', 'baz', function (err, res) { monitorClient.subscribe('foo', 'baz', (err, res) => {
// The return value might change in v.3 // The return value might change in v.3
// assert.strictEqual(res, 'baz'); // assert.strictEqual(res, 'baz');
// TODO: Fix the return value of subscribe calls // TODO: Fix the return value of subscribe calls
@@ -69,7 +69,7 @@ describe('The \'monitor\' method', function () {
}) })
}) })
monitorClient.on('monitor', function (time, args, rawOutput) { monitorClient.on('monitor', (time, args, rawOutput) => {
assert.strictEqual(monitorClient.monitoring, true) assert.strictEqual(monitorClient.monitoring, true)
assert.deepEqual(args, responses.shift()) assert.deepEqual(args, responses.shift())
assert(utils.monitorRegex.test(rawOutput), rawOutput) assert(utils.monitorRegex.test(rawOutput), rawOutput)
@@ -83,19 +83,19 @@ describe('The \'monitor\' method', function () {
if (process.platform === 'win32') { if (process.platform === 'win32') {
this.skip() this.skip()
} }
var monitorClient = redis.createClient({ const monitorClient = redis.createClient({
returnBuffers: true, returnBuffers: true,
path: '/tmp/redis.sock' path: '/tmp/redis.sock'
}) })
monitorClient.monitor(function (err, res) { monitorClient.monitor((err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(monitorClient.monitoring, true) assert.strictEqual(monitorClient.monitoring, true)
assert.strictEqual(res.inspect(), Buffer.from('OK').inspect()) assert.strictEqual(res.inspect(), Buffer.from('OK').inspect())
monitorClient.mget('hello', Buffer.from('world')) monitorClient.mget('hello', Buffer.from('world'))
}) })
monitorClient.on('monitor', function (time, args, rawOutput) { monitorClient.on('monitor', (time, args, rawOutput) => {
assert.strictEqual(typeof rawOutput, 'string') assert.strictEqual(typeof rawOutput, 'string')
assert(utils.monitorRegex.test(rawOutput), rawOutput) assert(utils.monitorRegex.test(rawOutput), rawOutput)
assert.deepEqual(args, ['mget', 'hello', 'world']) assert.deepEqual(args, ['mget', 'hello', 'world'])
@@ -104,11 +104,11 @@ describe('The \'monitor\' method', function () {
}) })
}) })
it('monitors reconnects properly and works with the offline queue', function (done) { it('monitors reconnects properly and works with the offline queue', (done) => {
var called = false let called = false
client.monitor(helper.isString('OK')) client.monitor(helper.isString('OK'))
client.mget('hello', 'world') client.mget('hello', 'world')
client.on('monitor', function (time, args, rawOutput) { client.on('monitor', (time, args, rawOutput) => {
assert.strictEqual(client.monitoring, true) assert.strictEqual(client.monitoring, true)
assert(utils.monitorRegex.test(rawOutput), rawOutput) assert(utils.monitorRegex.test(rawOutput), rawOutput)
assert.deepEqual(args, ['mget', 'hello', 'world']) assert.deepEqual(args, ['mget', 'hello', 'world'])
@@ -122,13 +122,13 @@ describe('The \'monitor\' method', function () {
}) })
}) })
it('monitors reconnects properly and works with the offline queue in a batch statement', function (done) { it('monitors reconnects properly and works with the offline queue in a batch statement', (done) => {
var called = false let called = false
var multi = client.batch() const multi = client.batch()
multi.monitor(helper.isString('OK')) multi.monitor(helper.isString('OK'))
multi.mget('hello', 'world') multi.mget('hello', 'world')
multi.exec(helper.isDeepEqual(['OK', [null, null]])) multi.exec(helper.isDeepEqual(['OK', [null, null]]))
client.on('monitor', function (time, args, rawOutput) { client.on('monitor', (time, args, rawOutput) => {
assert.strictEqual(client.monitoring, true) assert.strictEqual(client.monitoring, true)
assert(utils.monitorRegex.test(rawOutput), rawOutput) assert(utils.monitorRegex.test(rawOutput), rawOutput)
assert.deepEqual(args, ['mget', 'hello', 'world']) assert.deepEqual(args, ['mget', 'hello', 'world'])
@@ -142,19 +142,19 @@ describe('The \'monitor\' method', function () {
}) })
}) })
it('monitor activates even if the command could not be processed properly after a reconnect', function (done) { it('monitor activates even if the command could not be processed properly after a reconnect', (done) => {
client.monitor(function (err, res) { client.monitor((err, res) => {
assert.strictEqual(err.code, 'UNCERTAIN_STATE') assert.strictEqual(err.code, 'UNCERTAIN_STATE')
}) })
client.on('error', function () {}) // Ignore error here client.on('error', () => {}) // Ignore error here
client.stream.destroy() client.stream.destroy()
var end = helper.callFuncAfter(done, 2) const end = helper.callFuncAfter(done, 2)
client.on('monitor', function (time, args, rawOutput) { client.on('monitor', (time, args, rawOutput) => {
assert.strictEqual(client.monitoring, true) assert.strictEqual(client.monitoring, true)
end() end()
}) })
client.on('reconnecting', function () { client.on('reconnecting', () => {
client.get('foo', function (err, res) { client.get('foo', (err, res) => {
assert(!err) assert(!err)
assert.strictEqual(client.monitoring, true) assert.strictEqual(client.monitoring, true)
end() end()
@@ -162,8 +162,8 @@ describe('The \'monitor\' method', function () {
}) })
}) })
it('monitors works in combination with the pub sub mode and the offline queue', function (done) { it('monitors works in combination with the pub sub mode and the offline queue', (done) => {
var responses = [ const responses = [
['subscribe', '/foo', '/bar'], ['subscribe', '/foo', '/bar'],
['unsubscribe', '/bar'], ['unsubscribe', '/bar'],
['get', 'foo'], ['get', 'foo'],
@@ -172,39 +172,39 @@ describe('The \'monitor\' method', function () {
['unsubscribe', 'baz'], ['unsubscribe', 'baz'],
['publish', '/foo', 'hello world'] ['publish', '/foo', 'hello world']
] ]
var pub = redis.createClient() const pub = redis.createClient()
pub.on('ready', function () { pub.on('ready', () => {
client.monitor(function (err, res) { client.monitor((err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res, 'OK') assert.strictEqual(res, 'OK')
pub.get('foo', helper.isNull()) pub.get('foo', helper.isNull())
}) })
client.subscribe('/foo', '/bar') client.subscribe('/foo', '/bar')
client.unsubscribe('/bar') client.unsubscribe('/bar')
setTimeout(function () { setTimeout(() => {
client.stream.destroy() client.stream.destroy()
client.once('ready', function () { client.once('ready', () => {
pub.publish('/foo', 'hello world') pub.publish('/foo', 'hello world')
}) })
client.set('foo', 'bar', helper.isError()) client.set('foo', 'bar', helper.isError())
client.subscribe('baz') client.subscribe('baz')
client.unsubscribe('baz') client.unsubscribe('baz')
}, 150) }, 150)
var called = false let called = false
client.on('monitor', function (time, args, rawOutput) { client.on('monitor', (time, args, rawOutput) => {
assert.deepEqual(args, responses.shift()) assert.deepEqual(args, responses.shift())
assert(utils.monitorRegex.test(rawOutput), rawOutput) assert(utils.monitorRegex.test(rawOutput), rawOutput)
if (responses.length === 0) { if (responses.length === 0) {
// The publish is called right after the reconnect and the monitor is called before the message is emitted. // The publish is called right after the reconnect and the monitor is called before the message is emitted.
// Therefore we have to wait till the next tick // Therefore we have to wait till the next tick
process.nextTick(function () { process.nextTick(() => {
assert(called) assert(called)
client.quit(done) client.quit(done)
pub.end(false) pub.end(false)
}) })
} }
}) })
client.on('message', function (channel, msg) { client.on('message', (channel, msg) => {
assert.strictEqual(channel, '/foo') assert.strictEqual(channel, '/foo')
assert.strictEqual(msg, 'hello world') assert.strictEqual(msg, 'hello world')
called = true called = true

View File

@@ -1,60 +1,60 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
var uuid = require('uuid') const uuid = require('uuid')
describe('The \'mset\' method', function () { describe('The \'mset\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var key, value, key2, value2 let key, value, key2, value2
beforeEach(function () { beforeEach(() => {
key = uuid.v4() key = uuid.v4()
value = uuid.v4() value = uuid.v4()
key2 = uuid.v4() key2 = uuid.v4()
value2 = uuid.v4() value2 = uuid.v4()
}) })
describe('when not connected', function () { describe('when not connected', () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.quit() client.quit()
}) })
client.on('end', done) client.on('end', done)
}) })
it('reports an error', function (done) { it('reports an error', (done) => {
client.mset(key, value, key2, value2, function (err, res) { client.mset(key, value, key2, value2, (err, res) => {
assert(err.message.match(/The connection is already closed/)) assert(err.message.match(/The connection is already closed/))
done() done()
}) })
}) })
}) })
describe('when connected', function () { describe('when connected', () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
done() done()
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
describe('and a callback is specified', function () { describe('and a callback is specified', () => {
describe('with valid parameters', function () { describe('with valid parameters', () => {
it('sets the value correctly', function (done) { it('sets the value correctly', (done) => {
client.mset(key, value, key2, value2, function (err) { client.mset(key, value, key2, value2, (err) => {
if (err) { if (err) {
return done(err) return done(err)
} }
@@ -64,9 +64,9 @@ describe('The \'mset\' method', function () {
}) })
}) })
describe('with undefined \'key\' parameter and missing \'value\' parameter', function () { describe('with undefined \'key\' parameter and missing \'value\' parameter', () => {
it('reports an error', function (done) { it('reports an error', (done) => {
client.mset(undefined, function (err, res) { client.mset(undefined, (err, res) => {
helper.isError()(err, null) helper.isError()(err, null)
done() done()
}) })
@@ -74,25 +74,25 @@ describe('The \'mset\' method', function () {
}) })
}) })
describe('and no callback is specified', function () { describe('and no callback is specified', () => {
describe('with valid parameters', function () { describe('with valid parameters', () => {
it('sets the value correctly', function (done) { it('sets the value correctly', (done) => {
client.mset(key, value2, key2, value) client.mset(key, value2, key2, value)
client.get(key, helper.isString(value2)) client.get(key, helper.isString(value2))
client.get(key2, helper.isString(value, done)) client.get(key2, helper.isString(value, done))
}) })
it('sets the value correctly with array syntax', function (done) { it('sets the value correctly with array syntax', (done) => {
client.mset([key, value2, key2, value]) client.mset([key, value2, key2, value])
client.get(key, helper.isString(value2)) client.get(key, helper.isString(value2))
client.get(key2, helper.isString(value, done)) client.get(key2, helper.isString(value, done))
}) })
}) })
describe('with undefined \'key\' and missing \'value\' parameter', function () { describe('with undefined \'key\' and missing \'value\' parameter', () => {
// this behavior is different from the 'set' behavior. // this behavior is different from the 'set' behavior.
it('emits an error', function (done) { it('emits an error', (done) => {
client.on('error', function (err) { client.on('error', (err) => {
assert.strictEqual(err.message, 'ERR wrong number of arguments for \'mset\' command') assert.strictEqual(err.message, 'ERR wrong number of arguments for \'mset\' command')
assert.strictEqual(err.name, 'ReplyError') assert.strictEqual(err.name, 'ReplyError')
done() done()

View File

@@ -1,34 +1,34 @@
'use strict' 'use strict'
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'msetnx\' method', function () { describe('The \'msetnx\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('if any keys exist entire operation fails', function (done) { it('if any keys exist entire operation fails', (done) => {
client.mset(['mset1', 'val1', 'mset2', 'val2', 'mset3', 'val3'], helper.isString('OK')) client.mset(['mset1', 'val1', 'mset2', 'val2', 'mset3', 'val3'], helper.isString('OK'))
client.msetnx(['mset3', 'val3', 'mset4', 'val4'], helper.isNumber(0)) client.msetnx(['mset3', 'val3', 'mset4', 'val4'], helper.isNumber(0))
client.exists(['mset4'], helper.isNumber(0, done)) client.exists(['mset4'], helper.isNumber(0, done))
}) })
it('sets multiple keys if all keys are not set', function (done) { it('sets multiple keys if all keys are not set', (done) => {
client.msetnx(['mset3', 'val3', 'mset4', 'val4'], helper.isNumber(1)) client.msetnx(['mset3', 'val3', 'mset4', 'val4'], helper.isNumber(1))
client.exists(['mset3'], helper.isNumber(1)) client.exists(['mset3'], helper.isNumber(1))
client.exists(['mset3'], helper.isNumber(1, done)) client.exists(['mset3'], helper.isNumber(1, done))
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,31 +1,31 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'randomkey\' method', function () { describe('The \'randomkey\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('returns a random key', function (done) { it('returns a random key', (done) => {
client.mset(['test keys 1', 'test val 1', 'test keys 2', 'test val 2'], helper.isString('OK')) client.mset(['test keys 1', 'test val 1', 'test keys 2', 'test val 2'], helper.isString('OK'))
client.randomkey([], function (err, results) { client.randomkey([], (err, results) => {
assert.strictEqual(true, /test keys.+/.test(results)) assert.strictEqual(true, /test keys.+/.test(results))
return done(err) return done(err)
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,34 +1,34 @@
'use strict' 'use strict'
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'rename\' method', function () { describe('The \'rename\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('populates the new key', function (done) { it('populates the new key', (done) => {
client.set(['foo', 'bar'], helper.isString('OK')) client.set(['foo', 'bar'], helper.isString('OK'))
client.rename(['foo', 'new foo'], helper.isString('OK')) client.rename(['foo', 'new foo'], helper.isString('OK'))
client.exists(['new foo'], helper.isNumber(1, done)) client.exists(['new foo'], helper.isNumber(1, done))
}) })
it('removes the old key', function (done) { it('removes the old key', (done) => {
client.set(['foo', 'bar'], helper.isString('OK')) client.set(['foo', 'bar'], helper.isString('OK'))
client.rename(['foo', 'new foo'], helper.isString('OK')) client.rename(['foo', 'new foo'], helper.isString('OK'))
client.exists(['foo'], helper.isNumber(0, done)) client.exists(['foo'], helper.isNumber(0, done))
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,29 +1,29 @@
'use strict' 'use strict'
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'renamenx\' method', function () { describe('The \'renamenx\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('renames the key if target does not yet exist', function (done) { it('renames the key if target does not yet exist', (done) => {
client.set('foo', 'bar', helper.isString('OK')) client.set('foo', 'bar', helper.isString('OK'))
client.renamenx('foo', 'foo2', helper.isNumber(1)) client.renamenx('foo', 'foo2', helper.isNumber(1))
client.exists('foo', helper.isNumber(0)) client.exists('foo', helper.isNumber(0))
client.exists(['foo2'], helper.isNumber(1, done)) client.exists(['foo2'], helper.isNumber(1, done))
}) })
it('does not rename the key if the target exists', function (done) { it('does not rename the key if the target exists', (done) => {
client.set('foo', 'bar', helper.isString('OK')) client.set('foo', 'bar', helper.isString('OK'))
client.set('foo2', 'apple', helper.isString('OK')) client.set('foo2', 'apple', helper.isString('OK'))
client.renamenx('foo', 'foo2', helper.isNumber(0)) client.renamenx('foo', 'foo2', helper.isNumber(0))
@@ -31,7 +31,7 @@ describe('The \'renamenx\' method', function () {
client.exists(['foo2'], helper.isNumber(1, done)) client.exists(['foo2'], helper.isNumber(1, done))
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,32 +1,32 @@
'use strict' 'use strict'
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
var assert = require('assert') const assert = require('assert')
describe('The \'rpush\' command', function () { describe('The \'rpush\' command', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('inserts multiple values at a time into a list', function (done) { it('inserts multiple values at a time into a list', (done) => {
client.rpush('test', ['list key', 'should be a list']) client.rpush('test', ['list key', 'should be a list'])
client.lrange('test', 0, -1, function (err, res) { client.lrange('test', 0, -1, (err, res) => {
assert.strictEqual(res[0], 'list key') assert.strictEqual(res[0], 'list key')
assert.strictEqual(res[1], 'should be a list') assert.strictEqual(res[1], 'should be a list')
done(err) done(err)
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,38 +1,38 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'sadd\' method', function () { describe('The \'sadd\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('allows a single value to be added to the set', function (done) { it('allows a single value to be added to the set', (done) => {
client.sadd('set0', 'member0', helper.isNumber(1)) client.sadd('set0', 'member0', helper.isNumber(1))
client.smembers('set0', function (err, res) { client.smembers('set0', (err, res) => {
assert.ok(~res.indexOf('member0')) assert.ok(~res.indexOf('member0'))
return done(err) return done(err)
}) })
}) })
it('does not add the same value to the set twice', function (done) { it('does not add the same value to the set twice', (done) => {
client.sadd('set0', 'member0', helper.isNumber(1)) client.sadd('set0', 'member0', helper.isNumber(1))
client.sadd('set0', 'member0', helper.isNumber(0, done)) client.sadd('set0', 'member0', helper.isNumber(0, done))
}) })
it('allows multiple values to be added to the set', function (done) { it('allows multiple values to be added to the set', (done) => {
client.sadd('set0', ['member0', 'member1', 'member2'], helper.isNumber(3)) client.sadd('set0', ['member0', 'member1', 'member2'], helper.isNumber(3))
client.smembers('set0', function (err, res) { client.smembers('set0', (err, res) => {
assert.strictEqual(res.length, 3) assert.strictEqual(res.length, 3)
assert.ok(~res.indexOf('member0')) assert.ok(~res.indexOf('member0'))
assert.ok(~res.indexOf('member1')) assert.ok(~res.indexOf('member1'))
@@ -41,9 +41,9 @@ describe('The \'sadd\' method', function () {
}) })
}) })
it('allows multiple values to be added to the set with a different syntax', function (done) { it('allows multiple values to be added to the set with a different syntax', (done) => {
client.sadd(['set0', 'member0', 'member1', 'member2'], helper.isNumber(3)) client.sadd(['set0', 'member0', 'member1', 'member2'], helper.isNumber(3))
client.smembers('set0', function (err, res) { client.smembers('set0', (err, res) => {
assert.strictEqual(res.length, 3) assert.strictEqual(res.length, 3)
assert.ok(~res.indexOf('member0')) assert.ok(~res.indexOf('member0'))
assert.ok(~res.indexOf('member1')) assert.ok(~res.indexOf('member1'))
@@ -52,7 +52,7 @@ describe('The \'sadd\' method', function () {
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,27 +1,27 @@
'use strict' 'use strict'
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'scard\' method', function () { describe('The \'scard\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('returns the number of values in a set', function (done) { it('returns the number of values in a set', (done) => {
client.sadd('foo', [1, 2, 3], helper.isNumber(3)) client.sadd('foo', [1, 2, 3], helper.isNumber(3))
client.scard('foo', helper.isNumber(3, done)) client.scard('foo', helper.isNumber(3, done))
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,42 +1,42 @@
'use strict' 'use strict'
var config = require('../lib/config') const config = require('../lib/config')
var crypto = require('crypto') const crypto = require('crypto')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'script\' method', function () { describe('The \'script\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
var command = 'return 99' const command = 'return 99'
var commandSha = crypto.createHash('sha1').update(command).digest('hex') const commandSha = crypto.createHash('sha1').update(command).digest('hex')
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
it('loads script with client.script(\'load\')', function (done) { it('loads script with client.script(\'load\')', (done) => {
client.script('load', command, helper.isString(commandSha, done)) client.script('load', command, helper.isString(commandSha, done))
}) })
it('allows a loaded script to be evaluated', function (done) { it('allows a loaded script to be evaluated', (done) => {
client.evalsha(commandSha, 0, helper.isNumber(99, done)) client.evalsha(commandSha, 0, helper.isNumber(99, done))
}) })
it('allows a script to be loaded as part of a chained transaction', function (done) { it('allows a script to be loaded as part of a chained transaction', (done) => {
client.multi().script('load', command).exec(helper.isDeepEqual([commandSha], done)) client.multi().script('load', command).exec(helper.isDeepEqual([commandSha], done))
}) })
it('allows a script to be loaded using a transaction\'s array syntax', function (done) { it('allows a script to be loaded using a transaction\'s array syntax', (done) => {
client.multi([['script', 'load', command]]).exec(helper.isDeepEqual([commandSha], done)) client.multi([['script', 'load', command]]).exec(helper.isDeepEqual([commandSha], done))
}) })
}) })

View File

@@ -1,23 +1,23 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'sdiff\' method', function () { describe('The \'sdiff\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('returns set difference', function (done) { it('returns set difference', (done) => {
client.sadd('foo', 'x', helper.isNumber(1)) client.sadd('foo', 'x', helper.isNumber(1))
client.sadd('foo', ['a'], helper.isNumber(1)) client.sadd('foo', ['a'], helper.isNumber(1))
client.sadd('foo', 'b', helper.isNumber(1)) client.sadd('foo', 'b', helper.isNumber(1))
@@ -28,7 +28,7 @@ describe('The \'sdiff\' method', function () {
client.sadd('baz', 'a', helper.isNumber(1)) client.sadd('baz', 'a', helper.isNumber(1))
client.sadd('baz', 'd', helper.isNumber(1)) client.sadd('baz', 'd', helper.isNumber(1))
client.sdiff('foo', 'bar', 'baz', function (err, values) { client.sdiff('foo', 'bar', 'baz', (err, values) => {
values.sort() values.sort()
assert.strictEqual(values.length, 2) assert.strictEqual(values.length, 2)
assert.strictEqual(values[0], 'b') assert.strictEqual(values[0], 'b')
@@ -37,7 +37,7 @@ describe('The \'sdiff\' method', function () {
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,23 +1,23 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'sdiffstore\' method', function () { describe('The \'sdiffstore\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('calculates set difference ands stores it in a key', function (done) { it('calculates set difference ands stores it in a key', (done) => {
client.sadd('foo', 'x', helper.isNumber(1)) client.sadd('foo', 'x', helper.isNumber(1))
client.sadd('foo', 'a', helper.isNumber(1)) client.sadd('foo', 'a', helper.isNumber(1))
client.sadd('foo', 'b', helper.isNumber(1)) client.sadd('foo', 'b', helper.isNumber(1))
@@ -30,14 +30,14 @@ describe('The \'sdiffstore\' method', function () {
client.sdiffstore('quux', 'foo', 'bar', 'baz', helper.isNumber(2)) client.sdiffstore('quux', 'foo', 'bar', 'baz', helper.isNumber(2))
client.smembers('quux', function (err, values) { client.smembers('quux', (err, values) => {
var members = values.sort() const members = values.sort()
assert.deepEqual(members, [ 'b', 'x' ]) assert.deepEqual(members, [ 'b', 'x' ])
return done(err) return done(err)
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,63 +1,61 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'select\' method', function () { describe('The \'select\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
describe('when not connected', function () { describe('when not connected', () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.quit() client.quit()
}) })
client.on('end', done) client.on('end', done)
}) })
it('returns an error if redis is not connected', function (done) { it('returns an error if redis is not connected', (done) => {
var buffering = client.select(1, function (err, res) { client.select(1, (err, res) => {
assert(err.message.match(/The connection is already closed/)) assert(err.message.match(/The connection is already closed/))
done() done()
}) })
assert(typeof buffering === 'boolean')
}) })
}) })
describe('when connected', function () { describe('when connected', () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
it('changes the database and calls the callback', function (done) { it('changes the database and calls the callback', (done) => {
// default value of null means database 0 will be used. // default value of null means database 0 will be used.
assert.strictEqual(client.selectedDb, undefined, 'default db should be undefined') assert.strictEqual(client.selectedDb, undefined, 'default db should be undefined')
var buffering = client.select(1, function (err, res) { client.select(1, (err, res) => {
helper.isNotError()(err, res) helper.isNotError()(err, res)
assert.strictEqual(client.selectedDb, 1, 'db should be 1 after select') assert.strictEqual(client.selectedDb, 1, 'db should be 1 after select')
done() done()
}) })
assert(typeof buffering === 'boolean')
}) })
describe('and a callback is specified', function () { describe('and a callback is specified', () => {
describe('with a valid db index', function () { describe('with a valid db index', () => {
it('selects the appropriate database', function (done) { it('selects the appropriate database', (done) => {
assert.strictEqual(client.selectedDb, undefined, 'default db should be undefined') assert.strictEqual(client.selectedDb, undefined, 'default db should be undefined')
client.select(1, function (err) { client.select(1, (err) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(client.selectedDb, 1, 'we should have selected the new valid DB') assert.strictEqual(client.selectedDb, 1, 'we should have selected the new valid DB')
done() done()
@@ -65,10 +63,10 @@ describe('The \'select\' method', function () {
}) })
}) })
describe('with an invalid db index', function () { describe('with an invalid db index', () => {
it('returns an error', function (done) { it('returns an error', (done) => {
assert.strictEqual(client.selectedDb, undefined, 'default db should be undefined') assert.strictEqual(client.selectedDb, undefined, 'default db should be undefined')
client.select(9999, function (err) { client.select(9999, (err) => {
assert.strictEqual(err.code, 'ERR') assert.strictEqual(err.code, 'ERR')
assert.strictEqual(err.message, 'ERR invalid DB index') assert.strictEqual(err.message, 'ERR invalid DB index')
done() done()
@@ -77,23 +75,23 @@ describe('The \'select\' method', function () {
}) })
}) })
describe('and no callback is specified', function () { describe('and no callback is specified', () => {
describe('with a valid db index', function () { describe('with a valid db index', () => {
it('selects the appropriate database', function (done) { it('selects the appropriate database', (done) => {
assert.strictEqual(client.selectedDb, undefined, 'default db should be undefined') assert.strictEqual(client.selectedDb, undefined, 'default db should be undefined')
client.select(1) client.select(1)
setTimeout(function () { setTimeout(() => {
assert.strictEqual(client.selectedDb, 1, 'we should have selected the new valid DB') assert.strictEqual(client.selectedDb, 1, 'we should have selected the new valid DB')
done() done()
}, 25) }, 25)
}) })
}) })
describe('with an invalid db index', function () { describe('with an invalid db index', () => {
it('emits an error when callback not provided', function (done) { it('emits an error when callback not provided', (done) => {
assert.strictEqual(client.selectedDb, undefined, 'default db should be undefined') assert.strictEqual(client.selectedDb, undefined, 'default db should be undefined')
client.on('error', function (err) { client.on('error', (err) => {
assert.strictEqual(err.command, 'SELECT') assert.strictEqual(err.command, 'SELECT')
assert.strictEqual(err.message, 'ERR invalid DB index') assert.strictEqual(err.message, 'ERR invalid DB index')
done() done()
@@ -104,14 +102,14 @@ describe('The \'select\' method', function () {
}) })
}) })
describe('reconnection occurs', function () { describe('reconnection occurs', () => {
it('selects the appropriate database after a reconnect', function (done) { it('selects the appropriate database after a reconnect', (done) => {
assert.strictEqual(client.selectedDb, undefined, 'default db should be undefined') assert.strictEqual(client.selectedDb, undefined, 'default db should be undefined')
client.select(3) client.select(3)
client.set('foo', 'bar', function () { client.set('foo', 'bar', () => {
client.stream.destroy() client.stream.destroy()
}) })
client.once('ready', function () { client.once('ready', () => {
assert.strictEqual(client.selectedDb, 3) assert.strictEqual(client.selectedDb, 3)
assert(typeof client.serverInfo.db3 === 'object') assert(typeof client.serverInfo.db3 === 'object')
done() done()

View File

@@ -1,89 +1,89 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
var uuid = require('uuid') const uuid = require('uuid')
describe('The \'set\' method', function () { describe('The \'set\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var key, value let key, value
beforeEach(function () { beforeEach(() => {
key = uuid.v4() key = uuid.v4()
value = uuid.v4() value = uuid.v4()
}) })
describe('when not connected', function () { describe('when not connected', () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.quit() client.quit()
}) })
client.on('end', done) client.on('end', done)
}) })
it('reports an error', function (done) { it('reports an error', (done) => {
client.set(key, value, function (err, res) { client.set(key, value, (err, res) => {
assert(err.message.match(/The connection is already closed/)) assert(err.message.match(/The connection is already closed/))
done() done()
}) })
}) })
}) })
describe('when connected', function () { describe('when connected', () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
describe('and a callback is specified', function () { describe('and a callback is specified', () => {
describe('with valid parameters', function () { describe('with valid parameters', () => {
it('sets the value correctly', function (done) { it('sets the value correctly', (done) => {
client.set(key, value, function (err, res) { client.set(key, value, (err, res) => {
helper.isNotError()(err, res) helper.isNotError()(err, res)
client.get(key, function (err, res) { client.get(key, (err, res) => {
helper.isString(value)(err, res) helper.isString(value)(err, res)
done() done()
}) })
}) })
}) })
it('set expire date in seconds', function (done) { it('set expire date in seconds', (done) => {
client.set('foo', 'bar', 'ex', 10, helper.isString('OK')) client.set('foo', 'bar', 'ex', 10, helper.isString('OK'))
client.pttl('foo', function (err, res) { client.pttl('foo', (err, res) => {
assert(res >= 10000 - 50) // Max 50 ms should have passed assert(res >= 10000 - 50) // Max 50 ms should have passed
assert(res <= 10000) // Max possible should be 10.000 assert(res <= 10000) // Max possible should be 10.000
done(err) done(err)
}) })
}) })
it('set expire date in milliseconds', function (done) { it('set expire date in milliseconds', (done) => {
client.set('foo', 'bar', 'px', 100, helper.isString('OK')) client.set('foo', 'bar', 'px', 100, helper.isString('OK'))
client.pttl('foo', function (err, res) { client.pttl('foo', (err, res) => {
assert(res >= 50) // Max 50 ms should have passed assert(res >= 50) // Max 50 ms should have passed
assert(res <= 100) // Max possible should be 100 assert(res <= 100) // Max possible should be 100
done(err) done(err)
}) })
}) })
it('only set the key if (not) already set', function (done) { it('only set the key if (not) already set', (done) => {
client.set('foo', 'bar', 'NX', helper.isString('OK')) client.set('foo', 'bar', 'NX', helper.isString('OK'))
client.set('foo', 'bar', 'nx', helper.isNull()) client.set('foo', 'bar', 'nx', helper.isNull())
client.set('foo', 'bar', 'EX', '10', 'XX', helper.isString('OK')) client.set('foo', 'bar', 'EX', '10', 'XX', helper.isString('OK'))
client.ttl('foo', function (err, res) { client.ttl('foo', (err, res) => {
assert(res >= 9) // Min 9s should be left assert(res >= 9) // Min 9s should be left
assert(res <= 10) // Max 10s should be left assert(res <= 10) // Max 10s should be left
done(err) done(err)
@@ -91,17 +91,17 @@ describe('The \'set\' method', function () {
}) })
}) })
describe('reports an error with invalid parameters', function () { describe('reports an error with invalid parameters', () => {
it('undefined \'key\' and missing \'value\' parameter', function (done) { it('undefined \'key\' and missing \'value\' parameter', (done) => {
client.set(undefined, function (err, res) { client.set(undefined, (err, res) => {
helper.isError()(err, null) helper.isError()(err, null)
assert.strictEqual(err.command, 'SET') assert.strictEqual(err.command, 'SET')
done() done()
}) })
}) })
it('empty array as second parameter', function (done) { it('empty array as second parameter', (done) => {
client.set('foo', [], function (err, res) { client.set('foo', [], (err, res) => {
assert.strictEqual(err.message, 'ERR wrong number of arguments for \'set\' command') assert.strictEqual(err.message, 'ERR wrong number of arguments for \'set\' command')
done() done()
}) })
@@ -109,27 +109,27 @@ describe('The \'set\' method', function () {
}) })
}) })
describe('and no callback is specified', function () { describe('and no callback is specified', () => {
describe('with valid parameters', function () { describe('with valid parameters', () => {
it('sets the value correctly', function (done) { it('sets the value correctly', (done) => {
client.set(key, value) client.set(key, value)
client.get(key, helper.isString(value, done)) client.get(key, helper.isString(value, done))
}) })
it('sets the value correctly even if the callback is explicitly set to undefined', function (done) { it('sets the value correctly even if the callback is explicitly set to undefined', (done) => {
client.set(key, value, undefined) client.set(key, value, undefined)
client.get(key, helper.isString(value, done)) client.get(key, helper.isString(value, done))
}) })
it('sets the value correctly with the array syntax', function (done) { it('sets the value correctly with the array syntax', (done) => {
client.set([key, value]) client.set([key, value])
client.get(key, helper.isString(value, done)) client.get(key, helper.isString(value, done))
}) })
}) })
describe('with undefined \'key\' and missing \'value\' parameter', function () { describe('with undefined \'key\' and missing \'value\' parameter', () => {
it('emits an error without callback', function (done) { it('emits an error without callback', (done) => {
client.on('error', function (err) { client.on('error', (err) => {
assert.strictEqual(err.message, 'ERR wrong number of arguments for \'set\' command') assert.strictEqual(err.message, 'ERR wrong number of arguments for \'set\' command')
assert.strictEqual(err.command, 'SET') assert.strictEqual(err.command, 'SET')
done() done()
@@ -138,14 +138,12 @@ describe('The \'set\' method', function () {
}) })
}) })
// TODO: This test has to be refactored from v.3.0 on to expect an error instead it('returns an error on \'null\'', (done) => {
it('converts null to \'null\'', function (done) { client.set('foo', null, helper.isError(done))
client.set('foo', null)
client.get('foo', helper.isString('null', done))
}) })
it('emit an error with only the key set', function (done) { it('emit an error with only the key set', (done) => {
client.on('error', function (err) { client.on('error', (err) => {
assert.strictEqual(err.message, 'ERR wrong number of arguments for \'set\' command') assert.strictEqual(err.message, 'ERR wrong number of arguments for \'set\' command')
done() done()
}) })
@@ -153,8 +151,8 @@ describe('The \'set\' method', function () {
client.set('foo') client.set('foo')
}) })
it('emit an error without any parameters', function (done) { it('emit an error without any parameters', (done) => {
client.once('error', function (err) { client.once('error', (err) => {
assert.strictEqual(err.message, 'ERR wrong number of arguments for \'set\' command') assert.strictEqual(err.message, 'ERR wrong number of arguments for \'set\' command')
assert.strictEqual(err.command, 'SET') assert.strictEqual(err.command, 'SET')
done() done()

View File

@@ -1,34 +1,33 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'setex\' method', function () { describe('The \'setex\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('sets a key with an expiry', function (done) { it('sets a key with an expiry', (done) => {
client.setex(['setex key', '100', 'setex val'], helper.isString('OK')) client.setex(['setex key', '100', 'setex val'], helper.isString('OK'))
var buffering = client.exists(['setex key'], helper.isNumber(1)) client.exists(['setex key'], helper.isNumber(1))
assert(typeof buffering === 'boolean') client.ttl(['setex key'], (err, ttl) => {
client.ttl(['setex key'], function (err, ttl) {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert(ttl > 0) assert(ttl > 0)
return done() return done()
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,33 +1,33 @@
'use strict' 'use strict'
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'setnx\' method', function () { describe('The \'setnx\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('sets key if it does not have a value', function (done) { it('sets key if it does not have a value', (done) => {
client.setnx('foo', 'banana', helper.isNumber(1)) client.setnx('foo', 'banana', helper.isNumber(1))
client.get('foo', helper.isString('banana', done)) client.get('foo', helper.isString('banana', done))
}) })
it('does not set key if it already has a value', function (done) { it('does not set key if it already has a value', (done) => {
client.set('foo', 'bar', helper.isString('OK')) client.set('foo', 'bar', helper.isString('OK'))
client.setnx('foo', 'banana', helper.isNumber(0)) client.setnx('foo', 'banana', helper.isNumber(0))
client.get('foo', helper.isString('bar', done)) client.get('foo', helper.isString('bar', done))
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,23 +1,23 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'sinter\' method', function () { describe('The \'sinter\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('handles two sets being intersected', function (done) { it('handles two sets being intersected', (done) => {
client.sadd('sa', 'a', helper.isNumber(1)) client.sadd('sa', 'a', helper.isNumber(1))
client.sadd('sa', 'b', helper.isNumber(1)) client.sadd('sa', 'b', helper.isNumber(1))
client.sadd('sa', 'c', helper.isNumber(1)) client.sadd('sa', 'c', helper.isNumber(1))
@@ -26,14 +26,14 @@ describe('The \'sinter\' method', function () {
client.sadd('sb', 'c', helper.isNumber(1)) client.sadd('sb', 'c', helper.isNumber(1))
client.sadd('sb', 'd', helper.isNumber(1)) client.sadd('sb', 'd', helper.isNumber(1))
client.sinter('sa', 'sb', function (err, intersection) { client.sinter('sa', 'sb', (err, intersection) => {
assert.strictEqual(intersection.length, 2) assert.strictEqual(intersection.length, 2)
assert.deepEqual(intersection.sort(), [ 'b', 'c' ]) assert.deepEqual(intersection.sort(), [ 'b', 'c' ])
return done(err) return done(err)
}) })
}) })
it('handles three sets being intersected', function (done) { it('handles three sets being intersected', (done) => {
client.sadd('sa', 'a', helper.isNumber(1)) client.sadd('sa', 'a', helper.isNumber(1))
client.sadd('sa', 'b', helper.isNumber(1)) client.sadd('sa', 'b', helper.isNumber(1))
client.sadd('sa', 'c', helper.isNumber(1)) client.sadd('sa', 'c', helper.isNumber(1))
@@ -46,14 +46,14 @@ describe('The \'sinter\' method', function () {
client.sadd('sc', 'd', helper.isNumber(1)) client.sadd('sc', 'd', helper.isNumber(1))
client.sadd('sc', 'e', helper.isNumber(1)) client.sadd('sc', 'e', helper.isNumber(1))
client.sinter('sa', 'sb', 'sc', function (err, intersection) { client.sinter('sa', 'sb', 'sc', (err, intersection) => {
assert.strictEqual(intersection.length, 1) assert.strictEqual(intersection.length, 1)
assert.strictEqual(intersection[0], 'c') assert.strictEqual(intersection[0], 'c')
return done(err) return done(err)
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,23 +1,23 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'sinterstore\' method', function () { describe('The \'sinterstore\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('calculates set intersection and stores it in a key', function (done) { it('calculates set intersection and stores it in a key', (done) => {
client.sadd('sa', 'a', helper.isNumber(1)) client.sadd('sa', 'a', helper.isNumber(1))
client.sadd('sa', 'b', helper.isNumber(1)) client.sadd('sa', 'b', helper.isNumber(1))
client.sadd('sa', 'c', helper.isNumber(1)) client.sadd('sa', 'c', helper.isNumber(1))
@@ -32,13 +32,13 @@ describe('The \'sinterstore\' method', function () {
client.sinterstore('foo', 'sa', 'sb', 'sc', helper.isNumber(1)) client.sinterstore('foo', 'sa', 'sb', 'sc', helper.isNumber(1))
client.smembers('foo', function (err, members) { client.smembers('foo', (err, members) => {
assert.deepEqual(members, [ 'c' ]) assert.deepEqual(members, [ 'c' ])
return done(err) return done(err)
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,31 +1,31 @@
'use strict' 'use strict'
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'sismember\' method', function () { describe('The \'sismember\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('returns 0 if the value is not in the set', function (done) { it('returns 0 if the value is not in the set', (done) => {
client.sismember('foo', 'banana', helper.isNumber(0, done)) client.sismember('foo', 'banana', helper.isNumber(0, done))
}) })
it('returns 1 if the value is in the set', function (done) { it('returns 1 if the value is in the set', (done) => {
client.sadd('foo', 'banana', helper.isNumber(1)) client.sadd('foo', 'banana', helper.isNumber(1))
client.sismember('foo', 'banana', helper.isNumber(1, done)) client.sismember('foo', 'banana', helper.isNumber(1, done))
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,28 +1,28 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'slowlog\' method', function () { describe('The \'slowlog\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('logs operations in slowlog', function (done) { it('logs operations in slowlog', (done) => {
client.config('set', 'slowlog-log-slower-than', 0, helper.isString('OK')) client.config('set', 'slowlog-log-slower-than', 0, helper.isString('OK'))
client.slowlog('reset', helper.isString('OK')) client.slowlog('reset', helper.isString('OK'))
client.set('foo', 'bar', helper.isString('OK')) client.set('foo', 'bar', helper.isString('OK'))
client.get('foo', helper.isString('bar')) client.get('foo', helper.isString('bar'))
client.slowlog('get', function (err, res) { client.slowlog('get', (err, res) => {
assert.strictEqual(res.length, 3) assert.strictEqual(res.length, 3)
assert.strictEqual(res[0][3].length, 2) assert.strictEqual(res[0][3].length, 2)
assert.deepEqual(res[1][3], ['set', 'foo', 'bar']) assert.deepEqual(res[1][3], ['set', 'foo', 'bar'])
@@ -31,7 +31,7 @@ describe('The \'slowlog\' method', function () {
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,34 +1,34 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'smembers\' method', function () { describe('The \'smembers\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('returns all values in a set', function (done) { it('returns all values in a set', (done) => {
client.sadd('foo', 'x', helper.isNumber(1)) client.sadd('foo', 'x', helper.isNumber(1))
client.sadd('foo', 'y', helper.isNumber(1)) client.sadd('foo', 'y', helper.isNumber(1))
client.smembers('foo', function (err, values) { client.smembers('foo', (err, values) => {
assert.strictEqual(values.length, 2) assert.strictEqual(values.length, 2)
var members = values.sort() const members = values.sort()
assert.deepEqual(members, [ 'x', 'y' ]) assert.deepEqual(members, [ 'x', 'y' ])
return done(err) return done(err)
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,36 +1,36 @@
'use strict' 'use strict'
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'smove\' method', function () { describe('The \'smove\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('moves a value to a set that does not yet exist', function (done) { it('moves a value to a set that does not yet exist', (done) => {
client.sadd('foo', 'x', helper.isNumber(1)) client.sadd('foo', 'x', helper.isNumber(1))
client.smove('foo', 'bar', 'x', helper.isNumber(1)) client.smove('foo', 'bar', 'x', helper.isNumber(1))
client.sismember('foo', 'x', helper.isNumber(0)) client.sismember('foo', 'x', helper.isNumber(0))
client.sismember('bar', 'x', helper.isNumber(1, done)) client.sismember('bar', 'x', helper.isNumber(1, done))
}) })
it('does not move a value if it does not exist in the first set', function (done) { it('does not move a value if it does not exist in the first set', (done) => {
client.sadd('foo', 'x', helper.isNumber(1)) client.sadd('foo', 'x', helper.isNumber(1))
client.smove('foo', 'bar', 'y', helper.isNumber(0)) client.smove('foo', 'bar', 'y', helper.isNumber(0))
client.sismember('foo', 'y', helper.isNumber(0)) client.sismember('foo', 'y', helper.isNumber(0))
client.sismember('bar', 'y', helper.isNumber(0, done)) client.sismember('bar', 'y', helper.isNumber(0, done))
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,9 +1,9 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
function setupData (client, done) { function setupData (client, done) {
client.rpush('y', 'd') client.rpush('y', 'd')
@@ -32,94 +32,94 @@ function setupData (client, done) {
client.set('p9', 'tux', done) client.set('p9', 'tux', done)
} }
describe('The \'sort\' method', function () { describe('The \'sort\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('error', done) client.once('error', done)
client.once('connect', function () { client.once('connect', () => {
client.flushdb() client.flushdb()
setupData(client, done) setupData(client, done)
}) })
}) })
describe('alphabetical', function () { describe('alphabetical', () => {
it('sorts in ascending alphabetical order', function (done) { it('sorts in ascending alphabetical order', (done) => {
client.sort('y', 'asc', 'alpha', function (err, sorted) { client.sort('y', 'asc', 'alpha', (err, sorted) => {
assert.deepEqual(sorted, ['a', 'b', 'c', 'd']) assert.deepEqual(sorted, ['a', 'b', 'c', 'd'])
return done(err) return done(err)
}) })
}) })
it('sorts in descending alphabetical order', function (done) { it('sorts in descending alphabetical order', (done) => {
client.sort('y', 'desc', 'alpha', function (err, sorted) { client.sort('y', 'desc', 'alpha', (err, sorted) => {
assert.deepEqual(sorted, ['d', 'c', 'b', 'a']) assert.deepEqual(sorted, ['d', 'c', 'b', 'a'])
return done(err) return done(err)
}) })
}) })
}) })
describe('numeric', function () { describe('numeric', () => {
it('sorts in ascending numeric order', function (done) { it('sorts in ascending numeric order', (done) => {
client.sort('x', 'asc', function (err, sorted) { client.sort('x', 'asc', (err, sorted) => {
assert.deepEqual(sorted, [2, 3, 4, 9]) assert.deepEqual(sorted, [2, 3, 4, 9])
return done(err) return done(err)
}) })
}) })
it('sorts in descending numeric order', function (done) { it('sorts in descending numeric order', (done) => {
client.sort('x', 'desc', function (err, sorted) { client.sort('x', 'desc', (err, sorted) => {
assert.deepEqual(sorted, [9, 4, 3, 2]) assert.deepEqual(sorted, [9, 4, 3, 2])
return done(err) return done(err)
}) })
}) })
}) })
describe('pattern', function () { describe('pattern', () => {
it('handles sorting with a pattern', function (done) { it('handles sorting with a pattern', (done) => {
client.sort('x', 'by', 'w*', 'asc', function (err, sorted) { client.sort('x', 'by', 'w*', 'asc', (err, sorted) => {
assert.deepEqual(sorted, [3, 9, 4, 2]) assert.deepEqual(sorted, [3, 9, 4, 2])
return done(err) return done(err)
}) })
}) })
it('handles sorting with a \'by\' pattern and 1 \'get\' pattern', function (done) { it('handles sorting with a \'by\' pattern and 1 \'get\' pattern', (done) => {
client.sort('x', 'by', 'w*', 'asc', 'get', 'o*', function (err, sorted) { client.sort('x', 'by', 'w*', 'asc', 'get', 'o*', (err, sorted) => {
assert.deepEqual(sorted, ['foo', 'bar', 'baz', 'buz']) assert.deepEqual(sorted, ['foo', 'bar', 'baz', 'buz'])
return done(err) return done(err)
}) })
}) })
it('handles sorting with a \'by\' pattern and 2 \'get\' patterns', function (done) { it('handles sorting with a \'by\' pattern and 2 \'get\' patterns', (done) => {
client.sort('x', 'by', 'w*', 'asc', 'get', 'o*', 'get', 'p*', function (err, sorted) { client.sort('x', 'by', 'w*', 'asc', 'get', 'o*', 'get', 'p*', (err, sorted) => {
assert.deepEqual(sorted, ['foo', 'bux', 'bar', 'tux', 'baz', 'lux', 'buz', 'qux']) assert.deepEqual(sorted, ['foo', 'bux', 'bar', 'tux', 'baz', 'lux', 'buz', 'qux'])
return done(err) return done(err)
}) })
}) })
it('handles sorting with a \'by\' pattern and 2 \'get\' patterns with the array syntax', function (done) { it('handles sorting with a \'by\' pattern and 2 \'get\' patterns with the array syntax', (done) => {
client.sort(['x', 'by', 'w*', 'asc', 'get', 'o*', 'get', 'p*'], function (err, sorted) { client.sort(['x', 'by', 'w*', 'asc', 'get', 'o*', 'get', 'p*'], (err, sorted) => {
assert.deepEqual(sorted, ['foo', 'bux', 'bar', 'tux', 'baz', 'lux', 'buz', 'qux']) assert.deepEqual(sorted, ['foo', 'bux', 'bar', 'tux', 'baz', 'lux', 'buz', 'qux'])
return done(err) return done(err)
}) })
}) })
it('sorting with a \'by\' pattern and 2 \'get\' patterns and stores results', function (done) { it('sorting with a \'by\' pattern and 2 \'get\' patterns and stores results', (done) => {
client.sort('x', 'by', 'w*', 'asc', 'get', 'o*', 'get', 'p*', 'store', 'bacon', function (err) { client.sort('x', 'by', 'w*', 'asc', 'get', 'o*', 'get', 'p*', 'store', 'bacon', (err) => {
if (err) return done(err) if (err) return done(err)
}) })
client.lrange('bacon', 0, -1, function (err, values) { client.lrange('bacon', 0, -1, (err, values) => {
assert.deepEqual(values, ['foo', 'bux', 'bar', 'tux', 'baz', 'lux', 'buz', 'qux']) assert.deepEqual(values, ['foo', 'bux', 'bar', 'tux', 'baz', 'lux', 'buz', 'qux'])
return done(err) return done(err)
}) })
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,34 +1,34 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'spop\' method', function () { describe('The \'spop\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('returns a random element from the set', function (done) { it('returns a random element from the set', (done) => {
client.sadd('zzz', 'member0', helper.isNumber(1)) client.sadd('zzz', 'member0', helper.isNumber(1))
client.scard('zzz', helper.isNumber(1)) client.scard('zzz', helper.isNumber(1))
client.spop('zzz', function (err, value) { client.spop('zzz', (err, value) => {
if (err) return done(err) if (err) return done(err)
assert.strictEqual(value, 'member0') assert.strictEqual(value, 'member0')
client.scard('zzz', helper.isNumber(0, done)) client.scard('zzz', helper.isNumber(0, done))
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,56 +1,56 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'srem\' method', function () { describe('The \'srem\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('removes a value', function (done) { it('removes a value', (done) => {
client.sadd('set0', 'member0', helper.isNumber(1)) client.sadd('set0', 'member0', helper.isNumber(1))
client.srem('set0', 'member0', helper.isNumber(1)) client.srem('set0', 'member0', helper.isNumber(1))
client.scard('set0', helper.isNumber(0, done)) client.scard('set0', helper.isNumber(0, done))
}) })
it('handles attempting to remove a missing value', function (done) { it('handles attempting to remove a missing value', (done) => {
client.srem('set0', 'member0', helper.isNumber(0, done)) client.srem('set0', 'member0', helper.isNumber(0, done))
}) })
it('allows multiple values to be removed', function (done) { it('allows multiple values to be removed', (done) => {
client.sadd('set0', ['member0', 'member1', 'member2'], helper.isNumber(3)) client.sadd('set0', ['member0', 'member1', 'member2'], helper.isNumber(3))
client.srem('set0', ['member1', 'member2'], helper.isNumber(2)) client.srem('set0', ['member1', 'member2'], helper.isNumber(2))
client.smembers('set0', function (err, res) { client.smembers('set0', (err, res) => {
assert.strictEqual(res.length, 1) assert.strictEqual(res.length, 1)
assert.ok(~res.indexOf('member0')) assert.ok(~res.indexOf('member0'))
return done(err) return done(err)
}) })
}) })
it('allows multiple values to be removed with sendCommand', function (done) { it('allows multiple values to be removed with sendCommand', (done) => {
client.sendCommand('sadd', ['set0', 'member0', 'member1', 'member2'], helper.isNumber(3)) client.sendCommand('sadd', ['set0', 'member0', 'member1', 'member2'], helper.isNumber(3))
client.sendCommand('srem', ['set0', 'member1', 'member2'], helper.isNumber(2)) client.sendCommand('srem', ['set0', 'member1', 'member2'], helper.isNumber(2))
client.smembers('set0', function (err, res) { client.smembers('set0', (err, res) => {
assert.strictEqual(res.length, 1) assert.strictEqual(res.length, 1)
assert.ok(~res.indexOf('member0')) assert.ok(~res.indexOf('member0'))
return done(err) return done(err)
}) })
}) })
it('handles a value missing from the set of values being removed', function (done) { it('handles a value missing from the set of values being removed', (done) => {
client.sadd(['set0', 'member0', 'member1', 'member2'], helper.isNumber(3)) client.sadd(['set0', 'member0', 'member1', 'member2'], helper.isNumber(3))
client.srem(['set0', 'member3', 'member4'], helper.isNumber(0)) client.srem(['set0', 'member3', 'member4'], helper.isNumber(0))
client.smembers('set0', function (err, res) { client.smembers('set0', (err, res) => {
assert.strictEqual(res.length, 3) assert.strictEqual(res.length, 3)
assert.ok(~res.indexOf('member0')) assert.ok(~res.indexOf('member0'))
assert.ok(~res.indexOf('member1')) assert.ok(~res.indexOf('member1'))
@@ -59,7 +59,7 @@ describe('The \'srem\' method', function () {
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,23 +1,23 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'sunion\' method', function () { describe('The \'sunion\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('returns the union of a group of sets', function (done) { it('returns the union of a group of sets', (done) => {
client.sadd('sa', 'a', helper.isNumber(1)) client.sadd('sa', 'a', helper.isNumber(1))
client.sadd('sa', 'b', helper.isNumber(1)) client.sadd('sa', 'b', helper.isNumber(1))
client.sadd('sa', 'c', helper.isNumber(1)) client.sadd('sa', 'c', helper.isNumber(1))
@@ -30,13 +30,13 @@ describe('The \'sunion\' method', function () {
client.sadd('sc', 'd', helper.isNumber(1)) client.sadd('sc', 'd', helper.isNumber(1))
client.sadd('sc', 'e', helper.isNumber(1)) client.sadd('sc', 'e', helper.isNumber(1))
client.sunion('sa', 'sb', 'sc', function (err, union) { client.sunion('sa', 'sb', 'sc', (err, union) => {
assert.deepEqual(union.sort(), ['a', 'b', 'c', 'd', 'e']) assert.deepEqual(union.sort(), ['a', 'b', 'c', 'd', 'e'])
return done(err) return done(err)
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,23 +1,23 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'sunionstore\' method', function () { describe('The \'sunionstore\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('stores the result of a union', function (done) { it('stores the result of a union', (done) => {
client.sadd('sa', 'a', helper.isNumber(1)) client.sadd('sa', 'a', helper.isNumber(1))
client.sadd('sa', 'b', helper.isNumber(1)) client.sadd('sa', 'b', helper.isNumber(1))
client.sadd('sa', 'c', helper.isNumber(1)) client.sadd('sa', 'c', helper.isNumber(1))
@@ -32,14 +32,14 @@ describe('The \'sunionstore\' method', function () {
client.sunionstore('foo', 'sa', 'sb', 'sc', helper.isNumber(5)) client.sunionstore('foo', 'sa', 'sb', 'sc', helper.isNumber(5))
client.smembers('foo', function (err, members) { client.smembers('foo', (err, members) => {
assert.strictEqual(members.length, 5) assert.strictEqual(members.length, 5)
assert.deepEqual(members.sort(), ['a', 'b', 'c', 'd', 'e']) assert.deepEqual(members.sort(), ['a', 'b', 'c', 'd', 'e'])
return done(err) return done(err)
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,33 +1,33 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'ttl\' method', function () { describe('The \'ttl\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('returns the current ttl on a key', function (done) { it('returns the current ttl on a key', (done) => {
client.set(['ttl key', 'ttl val'], helper.isString('OK')) client.set(['ttl key', 'ttl val'], helper.isString('OK'))
client.expire(['ttl key', '100'], helper.isNumber(1)) client.expire(['ttl key', '100'], helper.isNumber(1))
client.ttl(['ttl key'], function (err, ttl) { client.ttl(['ttl key'], (err, ttl) => {
assert(ttl >= 99) assert(ttl >= 99)
assert(ttl <= 100) assert(ttl <= 100)
done(err) done(err)
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,51 +1,51 @@
'use strict' 'use strict'
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'type\' method', function () { describe('The \'type\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('reports string type', function (done) { it('reports string type', (done) => {
client.set(['string key', 'should be a string'], helper.isString('OK')) client.set(['string key', 'should be a string'], helper.isString('OK'))
client.type(['string key'], helper.isString('string', done)) client.type(['string key'], helper.isString('string', done))
}) })
it('reports list type', function (done) { it('reports list type', (done) => {
client.rpush(['list key', 'should be a list'], helper.isNumber(1)) client.rpush(['list key', 'should be a list'], helper.isNumber(1))
client.type(['list key'], helper.isString('list', done)) client.type(['list key'], helper.isString('list', done))
}) })
it('reports set type', function (done) { it('reports set type', (done) => {
client.sadd(['set key', 'should be a set'], helper.isNumber(1)) client.sadd(['set key', 'should be a set'], helper.isNumber(1))
client.type(['set key'], helper.isString('set', done)) client.type(['set key'], helper.isString('set', done))
}) })
it('reports zset type', function (done) { it('reports zset type', (done) => {
client.zadd('zset key', ['10.0', 'should be a zset'], helper.isNumber(1)) client.zadd('zset key', ['10.0', 'should be a zset'], helper.isNumber(1))
client.type(['zset key'], helper.isString('zset', done)) client.type(['zset key'], helper.isString('zset', done))
}) })
it('reports hash type', function (done) { it('reports hash type', (done) => {
client.hset('hash key', 'hashtest', 'should be a hash', helper.isNumber(1)) client.hset('hash key', 'hashtest', 'should be a hash', helper.isNumber(1))
client.type(['hash key'], helper.isString('hash', done)) client.type(['hash key'], helper.isString('hash', done))
}) })
it('reports none for null key', function (done) { it('reports none for null key', (done) => {
client.type('not here yet', helper.isString('none', done)) client.type('not here yet', helper.isString('none', done))
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,44 +1,44 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'watch\' method', function () { describe('The \'watch\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
var watched = 'foobar' const watched = 'foobar'
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
it('does not execute transaction if watched key was modified prior to execution', function (done) { it('does not execute transaction if watched key was modified prior to execution', (done) => {
client.watch(watched) client.watch(watched)
client.incr(watched) client.incr(watched)
var multi = client.multi() const multi = client.multi()
multi.incr(watched) multi.incr(watched)
multi.exec(helper.isNull(done)) multi.exec(helper.isNull(done))
}) })
it('successfully modifies other keys independently of transaction', function (done) { it('successfully modifies other keys independently of transaction', (done) => {
client.set('unwatched', 200) client.set('unwatched', 200)
client.set(watched, 0) client.set(watched, 0)
client.watch(watched) client.watch(watched)
client.incr(watched) client.incr(watched)
client.multi().incr(watched).exec(function (err, replies) { client.multi().incr(watched).exec((err, replies) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(replies, null, 'Aborted transaction multi-bulk reply should be null.') assert.strictEqual(replies, null, 'Aborted transaction multi-bulk reply should be null.')

View File

@@ -1,18 +1,18 @@
'use strict' 'use strict'
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var assert = require('assert') const assert = require('assert')
var redis = config.redis const redis = config.redis
describe('The \'zadd\' method', function () { describe('The \'zadd\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
@@ -29,7 +29,7 @@ describe('The \'zadd\' method', function () {
client.zadd('infinity', ['inf', 'should be also be inf'], helper.isNumber(1)) client.zadd('infinity', ['inf', 'should be also be inf'], helper.isNumber(1))
client.zadd('infinity', -Infinity, 'should be negative inf', helper.isNumber(1)) client.zadd('infinity', -Infinity, 'should be negative inf', helper.isNumber(1))
client.zadd('infinity', [99999999999999999999999, 'should not be inf'], helper.isNumber(1)) client.zadd('infinity', [99999999999999999999999, 'should not be inf'], helper.isNumber(1))
client.zrange('infinity', 0, -1, 'WITHSCORES', function (err, res) { client.zrange('infinity', 0, -1, 'WITHSCORES', (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res[5], 'inf') assert.strictEqual(res[5], 'inf')
assert.strictEqual(res[1], '-inf') assert.strictEqual(res[1], '-inf')
@@ -38,7 +38,7 @@ describe('The \'zadd\' method', function () {
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,18 +1,18 @@
'use strict' 'use strict'
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var assert = require('assert') const assert = require('assert')
var redis = config.redis const redis = config.redis
describe('The \'zscan\' method', function () { describe('The \'zscan\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
@@ -20,18 +20,18 @@ describe('The \'zscan\' method', function () {
it('return values', function (done) { it('return values', function (done) {
if (helper.redisProcess().spawnFailed()) this.skip() if (helper.redisProcess().spawnFailed()) this.skip()
helper.serverVersionAtLeast.call(this, client, [2, 8, 0]) helper.serverVersionAtLeast.call(this, client, [2, 8, 0])
var hash = {} const hash = {}
var set = [] const set = []
var zset = ['zset:1'] const zset = ['zset:1']
for (var i = 0; i < 500; i++) { for (let i = 0; i < 500; i++) {
hash['key_' + i] = 'value_' + i hash[`key_${i}`] = `value_${i}`
set.push('member_' + i) set.push(`member_${i}`)
zset.push(i, 'zMember_' + i) zset.push(i, `zMember_${i}`)
} }
client.hmset('hash:1', hash) client.hmset('hash:1', hash)
client.sadd('set:1', set) client.sadd('set:1', set)
client.zadd(zset) client.zadd(zset)
client.zscan('zset:1', 0, 'MATCH', '*', 'COUNT', 500, function (err, res) { client.zscan('zset:1', 0, 'MATCH', '*', 'COUNT', 500, (err, res) => {
assert(!err) assert(!err)
assert.strictEqual(res.length, 2) assert.strictEqual(res.length, 2)
assert.strictEqual(res[1].length, 1000) assert.strictEqual(res[1].length, 1000)
@@ -39,7 +39,7 @@ describe('The \'zscan\' method', function () {
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,27 +1,27 @@
'use strict' 'use strict'
var config = require('../lib/config') const config = require('../lib/config')
var helper = require('../helper') const helper = require('../helper')
var redis = config.redis const redis = config.redis
describe('The \'zscore\' method', function () { describe('The \'zscore\' method', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client let client
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
it('should return the score of member in the sorted set at key', function (done) { it('should return the score of member in the sorted set at key', (done) => {
client.zadd('myzset', 1, 'one') client.zadd('myzset', 1, 'one')
client.zscore('myzset', 'one', helper.isString('1', done)) client.zscore('myzset', 'one', helper.isString('1', done))
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
}) })

View File

@@ -1,36 +1,36 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('./lib/config') const config = require('./lib/config')
var helper = require('./helper') const helper = require('./helper')
var RedisProcess = require('./lib/redis-process') const RedisProcess = require('./lib/redis-process')
var rp let rp
var path = require('path') const path = require('path')
var redis = config.redis const redis = config.redis
// TODO: Fix redis process spawn on windows // TODO: Fix redis process spawn on windows
if (process.platform !== 'win32') { if (process.platform !== 'win32') {
describe('master slave sync', function () { describe('master slave sync', () => {
var master = null let master = null
var slave = null let slave = null
before(function (done) { before((done) => {
helper.stopRedis(function () { helper.stopRedis(() => {
helper.startRedis('./conf/password.conf', done) helper.startRedis('./conf/password.conf', done)
}) })
}) })
before(function (done) { before((done) => {
if (helper.redisProcess().spawnFailed()) return done() if (helper.redisProcess().spawnFailed()) return done()
master = redis.createClient({ master = redis.createClient({
password: 'porkchopsandwiches' password: 'porkchopsandwiches'
}) })
var multi = master.multi() const multi = master.multi()
var i = 0 let i = 0
while (i < 1000) { while (i < 1000) {
i++ i++
// Write some data in the redis instance, so there's something to sync // Write some data in the redis instance, so there's something to sync
multi.set('foo' + i, 'bar' + new Array(500).join(Math.random())) multi.set(`foo${i}`, `bar${new Array(500).join(Math.random())}`)
} }
multi.exec(done) multi.exec(done)
}) })
@@ -38,18 +38,18 @@ if (process.platform !== 'win32') {
it('sync process and no master should delay ready being emitted for slaves', function (done) { it('sync process and no master should delay ready being emitted for slaves', function (done) {
if (helper.redisProcess().spawnFailed()) this.skip() if (helper.redisProcess().spawnFailed()) this.skip()
var port = 6381 const port = 6381
var firstInfo let firstInfo
slave = redis.createClient({ slave = redis.createClient({
port: port, port,
retryStrategy: function (options) { retryStrategy (options) {
// Try to reconnect in very small intervals to catch the master_link_status down before the sync completes // Try to reconnect in very small intervals to catch the master_link_status down before the sync completes
return 10 return 10
} }
}) })
var tmp = slave.info.bind(slave) const tmp = slave.info.bind(slave)
var i = 0 let i = 0
slave.info = function (err, res) { slave.info = function (err, res) {
i++ i++
tmp(err, res) tmp(err, res)
@@ -58,38 +58,38 @@ if (process.platform !== 'win32') {
} }
} }
slave.on('connect', function () { slave.on('connect', () => {
assert.strictEqual(i, 0) assert.strictEqual(i, 0)
}) })
var end = helper.callFuncAfter(done, 2) const end = helper.callFuncAfter(done, 2)
slave.on('ready', function () { slave.on('ready', function () {
assert.strictEqual(this.serverInfo.master_link_status, 'up') assert.strictEqual(this.serverInfo.master_link_status, 'up')
assert.strictEqual(firstInfo.master_link_status, 'down') assert.strictEqual(firstInfo.master_link_status, 'down')
assert(i > 1) assert(i > 1)
this.get('foo300', function (err, res) { this.get('foo300', (err, res) => {
assert.strictEqual(res.substr(0, 3), 'bar') assert.strictEqual(res.substr(0, 3), 'bar')
end(err) end(err)
}) })
}) })
RedisProcess.start(function (err, _rp) { RedisProcess.start((err, _rp) => {
rp = _rp rp = _rp
end(err) end(err)
}, path.resolve(__dirname, './conf/slave.conf'), port) }, path.resolve(__dirname, './conf/slave.conf'), port)
}) })
after(function (done) { after((done) => {
if (helper.redisProcess().spawnFailed()) return done() if (helper.redisProcess().spawnFailed()) return done()
var end = helper.callFuncAfter(done, 3) const end = helper.callFuncAfter(done, 3)
rp.stop(end) rp.stop(end)
slave.end(true) slave.end(true)
master.flushdb(function (err) { master.flushdb((err) => {
end(err) end(err)
master.end(true) master.end(true)
}) })
helper.stopRedis(function () { helper.stopRedis(() => {
helper.startRedis('./conf/redis.conf', end) helper.startRedis('./conf/redis.conf', end)
}) })
}) })

View File

@@ -1,26 +1,26 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('./lib/config') const config = require('./lib/config')
var helper = require('./helper') const helper = require('./helper')
var redis = config.redis const redis = config.redis
var intercept = require('intercept-stdout') const intercept = require('intercept-stdout')
var net = require('net') const net = require('net')
var client let client
describe('connection tests', function () { describe('connection tests', () => {
beforeEach(function () { beforeEach(() => {
client = null client = null
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
it('unofficially support for a private stream', function () { it('unofficially support for a private stream', () => {
// While using a private stream, reconnection and other features are not going to work properly. // While using a private stream, reconnection and other features are not going to work properly.
// Besides that some functions also have to be monkey patched to be safe from errors in this case. // Besides that some functions also have to be monkey patched to be safe from errors in this case.
// Therefore this is not officially supported! // Therefore this is not officially supported!
var socket = new net.Socket() const socket = new net.Socket()
client = new redis.RedisClient({ client = new redis.RedisClient({
prefix: 'test' prefix: 'test'
}, socket) }, socket)
@@ -33,99 +33,92 @@ describe('connection tests', function () {
assert.strictEqual(client.stream.listeners('error').length, 1) assert.strictEqual(client.stream.listeners('error').length, 1)
}) })
describe('quit on lost connections', function () { describe('quit on lost connections', () => {
it('calling quit while the connection is down should not end in reconnecting version a', function (done) { it('calling quit while the connection is down should not end in reconnecting version a', (done) => {
var called = 0 let called = 0
client = redis.createClient({ client = redis.createClient({
port: 9999, port: 9999,
retryStrategy: function (options) { retryStrategy (options) {
var bool = client.quit(function (err, res) { client.quit((err, res) => {
assert.strictEqual(res, 'OK') assert.strictEqual(res, 'OK')
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(called++, -1) assert.strictEqual(called++, -1)
setTimeout(done, 25) setTimeout(done, 25)
}) })
assert.strictEqual(bool, false)
assert.strictEqual(called++, 0) assert.strictEqual(called++, 0)
return 5 return 5
} }
}) })
client.set('foo', 'bar', function (err, res) { client.set('foo', 'bar', (err, res) => {
assert.strictEqual(err.message, 'Stream connection ended and command aborted.') assert.strictEqual(err.message, 'Stream connection ended and command aborted.')
called = -1 called = -1
}) })
}) })
it('calling quit while the connection is down should not end in reconnecting version b', function (done) { it('calling quit while the connection is down should not end in reconnecting version b', (done) => {
var called = false let called = false
client = redis.createClient(9999) client = redis.createClient(9999)
client.set('foo', 'bar', function (err, res) { client.set('foo', 'bar', (err, res) => {
assert.strictEqual(err.message, 'Stream connection ended and command aborted.') assert.strictEqual(err.message, 'Stream connection ended and command aborted.')
called = true called = true
}) })
var bool = client.quit(function (err, res) { client.quit((err, res) => {
assert.strictEqual(res, 'OK') assert.strictEqual(res, 'OK')
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert(called) assert(called)
done() done()
}) })
assert.strictEqual(bool, false)
}) })
it('calling quit while the connection is down without offline queue should end the connection right away', function (done) { it('calling quit while the connection is down without offline queue should end the connection right away', (done) => {
var called = false let called = false
client = redis.createClient(9999, { client = redis.createClient(9999, {
enableOfflineQueue: false enableOfflineQueue: false
}) })
client.set('foo', 'bar', function (err, res) { client.set('foo', 'bar', (err, res) => {
assert.strictEqual(err.message, 'SET can\'t be processed. The connection is not yet established and the offline queue is deactivated.') assert.strictEqual(err.message, 'SET can\'t be processed. The connection is not yet established and the offline queue is deactivated.')
called = true called = true
}) })
var bool = client.quit(function (err, res) { client.quit((err, res) => {
assert.strictEqual(res, 'OK') assert.strictEqual(res, 'OK')
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert(called) assert(called)
done() done()
}) })
// TODO: In v.3 the quit command would be fired right away, so bool should be true
assert.strictEqual(bool, false)
}) })
it('calling quit while connected without offline queue should end the connection when all commands have finished', function (done) { it('calling quit while connected without offline queue should end the connection when all commands have finished', (done) => {
var called = false let called = false
client = redis.createClient({ client = redis.createClient({
enableOfflineQueue: false enableOfflineQueue: false
}) })
client.on('ready', function () { client.on('ready', () => {
client.set('foo', 'bar', function (err, res) { client.set('foo', 'bar', (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res, 'OK') assert.strictEqual(res, 'OK')
called = true called = true
}) })
var bool = client.quit(function (err, res) { client.quit((err, res) => {
assert.strictEqual(res, 'OK') assert.strictEqual(res, 'OK')
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert(called) assert(called)
done() done()
}) })
// TODO: In v.3 the quit command would be fired right away, so bool should be true
assert.strictEqual(bool, true)
}) })
}) })
it('do not quit before connected or a connection issue is detected', function (done) { it('do not quit before connected or a connection issue is detected', (done) => {
client = redis.createClient() client = redis.createClient()
client.set('foo', 'bar', helper.isString('OK')) client.set('foo', 'bar', helper.isString('OK'))
var bool = client.quit(done) client.quit(done)
assert.strictEqual(bool, false)
}) })
it('quit "succeeds" even if the client connection is closed while doing so', function (done) { it('quit "succeeds" even if the client connection is closed while doing so', (done) => {
client = redis.createClient() client = redis.createClient()
client.set('foo', 'bar', function (err, res) { client.set('foo', 'bar', (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res, 'OK') assert.strictEqual(res, 'OK')
client.quit(function (err, res) { client.quit((err, res) => {
assert.strictEqual(res, 'OK') assert.strictEqual(res, 'OK')
done(err) done(err)
}) })
@@ -133,62 +126,61 @@ describe('connection tests', function () {
}) })
}) })
it('quit right away if connection drops while quit command is on the fly', function (done) { it('quit right away if connection drops while quit command is on the fly', (done) => {
client = redis.createClient() client = redis.createClient()
client.once('ready', function () { client.once('ready', () => {
client.set('foo', 'bar', helper.isError()) client.set('foo', 'bar', helper.isError())
var bool = client.quit(done) client.quit(done)
assert.strictEqual(bool, true) process.nextTick(() => {
process.nextTick(function () {
client.stream.destroy() client.stream.destroy()
}) })
}) })
}) })
}) })
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
describe('on lost connection', function () { describe('on lost connection', () => {
it('end connection while retry is still ongoing', function (done) { it('end connection while retry is still ongoing', (done) => {
var connectTimeout = 1000 // in ms const connectTimeout = 1000 // in ms
client = redis.createClient({ client = redis.createClient({
connectTimeout: connectTimeout connectTimeout
}) })
client.once('ready', function () { client.once('ready', () => {
helper.killConnection(client) helper.killConnection(client)
}) })
client.on('reconnecting', function (params) { client.on('reconnecting', (params) => {
client.end(true) client.end(true)
assert.strictEqual(params.timesConnected, 1) assert.strictEqual(params.timesConnected, 1)
setTimeout(done, 5) setTimeout(done, 5)
}) })
}) })
it.skip('can not connect with wrong host / port in the options object', function (done) { it.skip('can not connect with wrong host / port in the options object', (done) => {
var options = { const options = {
host: 'somewhere', host: 'somewhere',
port: 6379, port: 6379,
family: ip, family: ip,
retryStrategy: function () {} retryStrategy () {}
} }
client = redis.createClient(options) client = redis.createClient(options)
assert.strictEqual(client.connectionOptions.family, ip === 'IPv6' ? 6 : 4) assert.strictEqual(client.connectionOptions.family, ip === 'IPv6' ? 6 : 4)
assert.strictEqual(Object.keys(options).length, 4) assert.strictEqual(Object.keys(options).length, 4)
var end = helper.callFuncAfter(done, 2) const end = helper.callFuncAfter(done, 2)
client.on('error', function (err) { client.on('error', (err) => {
assert(/CONNECTION_BROKEN|ENOTFOUND|EAI_AGAIN/.test(err.code)) assert(/CONNECTION_BROKEN|ENOTFOUND|EAI_AGAIN/.test(err.code))
end() end()
}) })
}) })
it('emits error once if reconnecting after command has been executed but not yet returned without callback', function (done) { it('emits error once if reconnecting after command has been executed but not yet returned without callback', (done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.on('ready', function () { client.on('ready', () => {
client.set('foo', 'bar', function (err) { client.set('foo', 'bar', (err) => {
assert.strictEqual(err.code, 'UNCERTAIN_STATE') assert.strictEqual(err.code, 'UNCERTAIN_STATE')
done() done()
}) })
@@ -197,11 +189,11 @@ describe('connection tests', function () {
}) })
}) })
it('retryStrategy used to reconnect with individual error', function (done) { it('retryStrategy used to reconnect with individual error', (done) => {
client = redis.createClient({ client = redis.createClient({
retryStrategy: function (options) { retryStrategy (options) {
if (options.totalRetryTime > 150) { if (options.totalRetryTime > 150) {
client.set('foo', 'bar', function (err, res) { client.set('foo', 'bar', (err, res) => {
assert.strictEqual(err.message, 'Stream connection ended and command aborted.') assert.strictEqual(err.message, 'Stream connection ended and command aborted.')
assert.strictEqual(err.origin.message, 'Connection timeout') assert.strictEqual(err.origin.message, 'Connection timeout')
done() done()
@@ -215,11 +207,11 @@ describe('connection tests', function () {
}) })
}) })
it('retryStrategy used to reconnect', function (done) { it('retryStrategy used to reconnect', (done) => {
client = redis.createClient({ client = redis.createClient({
retryStrategy: function (options) { retryStrategy (options) {
if (options.totalRetryTime > 150) { if (options.totalRetryTime > 150) {
client.set('foo', 'bar', function (err, res) { client.set('foo', 'bar', (err, res) => {
assert.strictEqual(err.message, 'Stream connection ended and command aborted.') assert.strictEqual(err.message, 'Stream connection ended and command aborted.')
assert.strictEqual(err.code, 'NR_CLOSED') assert.strictEqual(err.code, 'NR_CLOSED')
assert.strictEqual(err.origin.code, 'ECONNREFUSED') assert.strictEqual(err.origin.code, 'ECONNREFUSED')
@@ -233,22 +225,22 @@ describe('connection tests', function () {
}) })
}) })
it('retryStrategy used to reconnect with defaults', function (done) { it('retryStrategy used to reconnect with defaults', (done) => {
var unhookIntercept = intercept(function () { const unhookIntercept = intercept(() => {
return '' return ''
}) })
redis.debugMode = true redis.debugMode = true
client = redis.createClient({ client = redis.createClient({
retryStrategy: function (options) { retryStrategy (options) {
client.set('foo', 'bar') client.set('foo', 'bar')
assert(redis.debugMode) assert(redis.debugMode)
return null return null
} }
}) })
setTimeout(function () { setTimeout(() => {
client.stream.destroy() client.stream.destroy()
}, 50) }, 50)
client.on('error', function (err) { client.on('error', (err) => {
assert.strictEqual(err.code, 'NR_CLOSED') assert.strictEqual(err.code, 'NR_CLOSED')
assert.strictEqual(err.message, 'Stream connection ended and command aborted.') assert.strictEqual(err.message, 'Stream connection ended and command aborted.')
unhookIntercept() unhookIntercept()
@@ -258,69 +250,69 @@ describe('connection tests', function () {
}) })
}) })
describe('when not connected', function () { describe('when not connected', () => {
// TODO: Fix this test // TODO: Fix this test
it.skip('emit an error after the socket timeout exceeded the connectTimeout time', function (done) { it.skip('emit an error after the socket timeout exceeded the connectTimeout time', (done) => {
var connectTimeout = 500 // in ms const connectTimeout = 500 // in ms
client = redis.createClient({ client = redis.createClient({
// Auto detect ipv4 and use non routable ip to trigger the timeout // Auto detect ipv4 and use non routable ip to trigger the timeout
host: '10.255.255.1', host: '10.255.255.1',
connectTimeout: connectTimeout connectTimeout
}) })
process.nextTick(function () { process.nextTick(() => {
assert.strictEqual(client.stream.listeners('timeout').length, 1) assert.strictEqual(client.stream.listeners('timeout').length, 1)
}) })
assert.strictEqual(client.address, '10.255.255.1:6379') assert.strictEqual(client.address, '10.255.255.1:6379')
assert.strictEqual(client.connectionOptions.family, 4) assert.strictEqual(client.connectionOptions.family, 4)
client.on('reconnecting', function (params) { client.on('reconnecting', (params) => {
throw new Error('No reconnect, since no connection was ever established') throw new Error('No reconnect, since no connection was ever established')
}) })
var time = Date.now() const time = Date.now()
client.on('error', function (err) { client.on('error', (err) => {
if (err.code === 'ENETUNREACH') { // The test is run without a internet connection. Pretent it works if (err.code === 'ENETUNREACH') { // The test is run without a internet connection. Pretent it works
return done() return done()
} }
assert(/Redis connection in broken state: connection timeout.*?exceeded./.test(err.message), err.message) assert(/Redis connection in broken state: connection timeout.*?exceeded./.test(err.message), err.message)
// The code execution on windows is very slow at times // The code execution on windows is very slow at times
var add = process.platform !== 'win32' ? 15 : 200 const add = process.platform !== 'win32' ? 15 : 200
var now = Date.now() const now = Date.now()
assert(now - time < connectTimeout + add, 'The real timeout time should be below ' + (connectTimeout + add) + 'ms but is: ' + (now - time)) assert(now - time < connectTimeout + add, `The real timeout time should be below ${connectTimeout + add}ms but is: ${now - time}`)
// Timers sometimes trigger early (e.g. 1ms to early) // Timers sometimes trigger early (e.g. 1ms to early)
assert(now - time >= connectTimeout - 5, 'The real timeout time should be above ' + connectTimeout + 'ms, but it is: ' + (now - time)) assert(now - time >= connectTimeout - 5, `The real timeout time should be above ${connectTimeout}ms, but it is: ${now - time}`)
done() done()
}) })
}) })
it('use the system socket timeout if the connectTimeout has not been provided', function (done) { it('use the system socket timeout if the connectTimeout has not been provided', (done) => {
client = redis.createClient({ client = redis.createClient({
host: '2001:db8::ff00:42:8329' // auto detect ip v6 host: '2001:db8::ff00:42:8329' // auto detect ip v6
}) })
assert.strictEqual(client.address, '2001:db8::ff00:42:8329:6379') assert.strictEqual(client.address, '2001:db8::ff00:42:8329:6379')
assert.strictEqual(client.connectionOptions.family, 6) assert.strictEqual(client.connectionOptions.family, 6)
process.nextTick(function () { process.nextTick(() => {
assert.strictEqual(client.stream.listeners('timeout').length, 0) assert.strictEqual(client.stream.listeners('timeout').length, 0)
done() done()
}) })
client.end(true) client.end(true)
}) })
it('clears the socket timeout after a connection has been established', function (done) { it('clears the socket timeout after a connection has been established', (done) => {
client = redis.createClient({ client = redis.createClient({
connectTimeout: 1000 connectTimeout: 1000
}) })
process.nextTick(function () { process.nextTick(() => {
assert.strictEqual(client.stream._idleTimeout, 1000) assert.strictEqual(client.stream._idleTimeout, 1000)
}) })
client.on('connect', function () { client.on('connect', () => {
assert.strictEqual(client.stream._idleTimeout, -1) assert.strictEqual(client.stream._idleTimeout, -1)
assert.strictEqual(client.stream.listeners('timeout').length, 0) assert.strictEqual(client.stream.listeners('timeout').length, 0)
client.on('ready', done) client.on('ready', done)
}) })
}) })
it('connect with host and port provided in the options object', function (done) { it('connect with host and port provided in the options object', (done) => {
client = redis.createClient({ client = redis.createClient({
host: 'localhost', host: 'localhost',
port: '6379', port: '6379',
@@ -339,114 +331,114 @@ describe('connection tests', function () {
connectTimeout: 1000 connectTimeout: 1000
}) })
var end = helper.callFuncAfter(done, 2) const end = helper.callFuncAfter(done, 2)
client.once('ready', end) client.once('ready', end)
client.set('foo', 'bar', end) client.set('foo', 'bar', end)
}) })
it('connects correctly with args', function (done) { it('connects correctly with args', (done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.on('error', done) client.on('error', done)
client.once('ready', function () { client.once('ready', () => {
client.removeListener('error', done) client.removeListener('error', done)
client.get('recon 1', done) client.get('recon 1', done)
}) })
}) })
it('connects correctly with default values', function (done) { it('connects correctly with default values', (done) => {
client = redis.createClient() client = redis.createClient()
client.on('error', done) client.on('error', done)
client.once('ready', function () { client.once('ready', () => {
client.removeListener('error', done) client.removeListener('error', done)
client.get('recon 1', done) client.get('recon 1', done)
}) })
}) })
it('connects with a port only', function (done) { it('connects with a port only', (done) => {
client = redis.createClient(6379) client = redis.createClient(6379)
assert.strictEqual(client.connectionOptions.family, 4) assert.strictEqual(client.connectionOptions.family, 4)
client.on('error', done) client.on('error', done)
client.once('ready', function () { client.once('ready', () => {
client.removeListener('error', done) client.removeListener('error', done)
client.get('recon 1', done) client.get('recon 1', done)
}) })
}) })
it('connects correctly to localhost', function (done) { it('connects correctly to localhost', (done) => {
client = redis.createClient(null, null) client = redis.createClient(null, null)
client.on('error', done) client.on('error', done)
client.once('ready', function () { client.once('ready', () => {
client.removeListener('error', done) client.removeListener('error', done)
client.get('recon 1', done) client.get('recon 1', done)
}) })
}) })
it('connects correctly to the provided host with the port set to null', function (done) { it('connects correctly to the provided host with the port set to null', (done) => {
client = redis.createClient(null, 'localhost') client = redis.createClient(null, 'localhost')
client.on('error', done) client.on('error', done)
assert.strictEqual(client.address, 'localhost:6379') assert.strictEqual(client.address, 'localhost:6379')
client.once('ready', function () { client.once('ready', () => {
client.set('foo', 'bar') client.set('foo', 'bar')
client.get('foo', function (err, res) { client.get('foo', (err, res) => {
assert.strictEqual(res, 'bar') assert.strictEqual(res, 'bar')
done(err) done(err)
}) })
}) })
}) })
it('connects correctly to localhost and no ready check', function (done) { it('connects correctly to localhost and no ready check', (done) => {
client = redis.createClient(undefined, undefined, { client = redis.createClient(undefined, undefined, {
noReadyCheck: true noReadyCheck: true
}) })
client.on('error', done) client.on('error', done)
client.once('ready', function () { client.once('ready', () => {
client.set('foo', 'bar') client.set('foo', 'bar')
client.get('foo', function (err, res) { client.get('foo', (err, res) => {
assert.strictEqual(res, 'bar') assert.strictEqual(res, 'bar')
done(err) done(err)
}) })
}) })
}) })
it('connects correctly to the provided host with the port set to undefined', function (done) { it('connects correctly to the provided host with the port set to undefined', (done) => {
client = redis.createClient(undefined, 'localhost', { client = redis.createClient(undefined, 'localhost', {
noReadyCheck: true noReadyCheck: true
}) })
client.on('error', done) client.on('error', done)
assert.strictEqual(client.address, 'localhost:6379') assert.strictEqual(client.address, 'localhost:6379')
client.once('ready', function () { client.once('ready', () => {
client.set('foo', 'bar') client.set('foo', 'bar')
client.get('foo', function (err, res) { client.get('foo', (err, res) => {
assert.strictEqual(res, 'bar') assert.strictEqual(res, 'bar')
done(err) done(err)
}) })
}) })
}) })
it('connects correctly even if the info command is not present on the redis server', function (done) { it('connects correctly even if the info command is not present on the redis server', (done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.info = function (cb) { client.info = function (cb) {
// Mock the result // Mock the result
cb(new Error('ERR unknown command \'info\'')) cb(new Error('ERR unknown command \'info\''))
} }
client.once('ready', function () { client.once('ready', () => {
assert.strictEqual(Object.keys(client.serverInfo).length, 0) assert.strictEqual(Object.keys(client.serverInfo).length, 0)
done() done()
}) })
}) })
it('fake the stream to mock redis', function () { it('fake the stream to mock redis', () => {
// This is needed for libraries that want to mock the stream like fakeredis // This is needed for libraries that want to mock the stream like fakeredis
var temp = redis.RedisClient.prototype.createStream const temp = redis.RedisClient.prototype.createStream
var createStreamString = String(temp) const createStreamString = String(temp)
redis.RedisClient.prototype.createStream = function () { redis.RedisClient.prototype.createStream = function () {
this.connected = true this.connected = true
this.ready = true this.ready = true
@@ -462,23 +454,23 @@ describe('connection tests', function () {
}) })
if (ip === 'IPv4') { if (ip === 'IPv4') {
it('allows connecting with the redis url to the default host and port, select db 3 and warn about duplicate db option', function (done) { it('allows connecting with the redis url to the default host and port, select db 3 and warn about duplicate db option', (done) => {
client = redis.createClient('redis:///3?db=3') client = redis.createClient('redis:///3?db=3')
assert.strictEqual(client.selectedDb, '3') assert.strictEqual(client.selectedDb, '3')
client.on('ready', done) client.on('ready', done)
}) })
it('allows connecting with the redis url and the default port and auth provided even though it is not required', function (done) { it('allows connecting with the redis url and the default port and auth provided even though it is not required', (done) => {
client = redis.createClient('redis://:porkchopsandwiches@' + config.HOST[ip] + '/') client = redis.createClient(`redis://:porkchopsandwiches@${config.HOST[ip]}/`)
var end = helper.callFuncAfter(done, 2) const end = helper.callFuncAfter(done, 2)
client.on('warning', function (msg) { client.on('warning', (msg) => {
assert.strictEqual(msg, 'Warning: Redis server does not require a password, but a password was supplied.') assert.strictEqual(msg, 'Warning: Redis server does not require a password, but a password was supplied.')
end() end()
}) })
client.on('ready', end) client.on('ready', end)
}) })
it('allows connecting with the redis url as first parameter and the options as second parameter', function (done) { it('allows connecting with the redis url as first parameter and the options as second parameter', (done) => {
client = redis.createClient('//127.0.0.1', { client = redis.createClient('//127.0.0.1', {
connectTimeout: 1000 connectTimeout: 1000
}) })
@@ -486,9 +478,9 @@ describe('connection tests', function () {
client.on('ready', done) client.on('ready', done)
}) })
it('allows connecting with the redis url in the options object and works with protocols other than the redis protocol (e.g. http)', function (done) { it('allows connecting with the redis url in the options object and works with protocols other than the redis protocol (e.g. http)', (done) => {
client = redis.createClient({ client = redis.createClient({
url: 'http://foo:porkchopsandwiches@' + config.HOST[ip] + '/3' url: `http://foo:porkchopsandwiches@${config.HOST[ip]}/3`
}) })
assert.strictEqual(client.authPass, 'porkchopsandwiches') assert.strictEqual(client.authPass, 'porkchopsandwiches')
assert.strictEqual(+client.selectedDb, 3) assert.strictEqual(+client.selectedDb, 3)
@@ -497,32 +489,32 @@ describe('connection tests', function () {
client.on('ready', done) client.on('ready', done)
}) })
it('allows connecting with the redis url and no auth and options as second parameter', function (done) { it('allows connecting with the redis url and no auth and options as second parameter', (done) => {
var options = { const options = {
detectBuffers: false detectBuffers: false
} }
client = redis.createClient('redis://' + config.HOST[ip] + ':' + config.PORT, options) client = redis.createClient(`redis://${config.HOST[ip]}:${config.PORT}`, options)
assert.strictEqual(Object.keys(options).length, 1) assert.strictEqual(Object.keys(options).length, 1)
client.on('ready', done) client.on('ready', done)
}) })
it('allows connecting with the redis url and no auth and options as third parameter', function (done) { it('allows connecting with the redis url and no auth and options as third parameter', (done) => {
client = redis.createClient('redis://' + config.HOST[ip] + ':' + config.PORT, null, { client = redis.createClient(`redis://${config.HOST[ip]}:${config.PORT}`, null, {
detectBuffers: false detectBuffers: false
}) })
client.on('ready', done) client.on('ready', done)
}) })
} }
it('redis still loading <= 500', function (done) { it('redis still loading <= 500', (done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
var tmp = client.info.bind(client) const tmp = client.info.bind(client)
var end = helper.callFuncAfter(done, 3) const end = helper.callFuncAfter(done, 3)
var delayed = false let delayed = false
var time let time
// Mock original function and pretent redis is still loading // Mock original function and pretent redis is still loading
client.info = function (cb) { client.info = function (cb) {
tmp(function (err, res) { tmp((err, res) => {
if (!delayed) { if (!delayed) {
assert(!err) assert(!err)
client.serverInfo.loading = 1 client.serverInfo.loading = 1
@@ -534,25 +526,25 @@ describe('connection tests', function () {
cb(err, res) cb(err, res)
}) })
} }
client.on('ready', function () { client.on('ready', () => {
var rest = Date.now() - time const rest = Date.now() - time
assert(rest >= 495, 'Rest should be equal or above 500 ms but is: ' + rest) // setTimeout might trigger early assert(rest >= 495, `Rest should be equal or above 500 ms but is: ${rest}`) // setTimeout might trigger early
// Be on the safe side and accept 200ms above the original value // Be on the safe side and accept 200ms above the original value
assert(rest - 250 < 500, 'Rest - 250 should be below 500 ms but is: ' + (rest - 250)) assert(rest - 250 < 500, `Rest - 250 should be below 500 ms but is: ${rest - 250}`)
assert(delayed) assert(delayed)
end() end()
}) })
}) })
it('redis still loading > 1000ms', function (done) { it('redis still loading > 1000ms', (done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
var tmp = client.info.bind(client) const tmp = client.info.bind(client)
var end = helper.callFuncAfter(done, 3) const end = helper.callFuncAfter(done, 3)
var delayed = false let delayed = false
var time let time
// Mock original function and pretent redis is still loading // Mock original function and pretent redis is still loading
client.info = function (cb) { client.info = function (cb) {
tmp(function (err, res) { tmp((err, res) => {
if (!delayed) { if (!delayed) {
assert(!err) assert(!err)
// Try reconnecting after one second even if redis tells us the time needed is above one second // Try reconnecting after one second even if redis tells us the time needed is above one second
@@ -565,11 +557,11 @@ describe('connection tests', function () {
cb(err, res) cb(err, res)
}) })
} }
client.on('ready', function () { client.on('ready', () => {
var rest = Date.now() - time const rest = Date.now() - time
assert(rest >= 998, '`rest` should be equal or above 1000 ms but is: ' + rest) // setTimeout might trigger early assert(rest >= 998, `\`rest\` should be equal or above 1000 ms but is: ${rest}`) // setTimeout might trigger early
// Be on the safe side and accept 200ms above the original value // Be on the safe side and accept 200ms above the original value
assert(rest - 250 < 1000, '`rest` - 250 should be below 1000 ms but is: ' + (rest - 250)) assert(rest - 250 < 1000, `\`rest\` - 250 should be below 1000 ms but is: ${rest - 250}`)
assert(delayed) assert(delayed)
end() end()
}) })

View File

@@ -1,12 +1,12 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var errors = require('../lib/customErrors') const errors = require('../lib/customErrors')
describe('errors', function () { describe('errors', () => {
describe('AbortError', function () { describe('AbortError', () => {
it('should inherit from Error', function () { it('should inherit from Error', () => {
var e = new errors.AbortError({}) const e = new errors.AbortError({})
assert.strictEqual(e.message, '') assert.strictEqual(e.message, '')
assert.strictEqual(e.name, 'AbortError') assert.strictEqual(e.name, 'AbortError')
assert.strictEqual(Object.keys(e).length, 0) assert.strictEqual(Object.keys(e).length, 0)
@@ -14,8 +14,8 @@ describe('errors', function () {
assert(e instanceof errors.AbortError) assert(e instanceof errors.AbortError)
}) })
it('should list options properties but not name and message', function () { it('should list options properties but not name and message', () => {
var e = new errors.AbortError({ const e = new errors.AbortError({
name: 'weird', name: 'weird',
message: 'hello world', message: 'hello world',
property: true property: true
@@ -30,8 +30,8 @@ describe('errors', function () {
assert.strictEqual(e.name, 'AbortError') assert.strictEqual(e.name, 'AbortError')
}) })
it('should change name and message', function () { it('should change name and message', () => {
var e = new errors.AbortError({ const e = new errors.AbortError({
message: 'hello world', message: 'hello world',
property: true property: true
}) })
@@ -44,9 +44,9 @@ describe('errors', function () {
}) })
}) })
describe('AggregateError', function () { describe('AggregateError', () => {
it('should inherit from Error and AbortError', function () { it('should inherit from Error and AbortError', () => {
var e = new errors.AggregateError({}) const e = new errors.AggregateError({})
assert.strictEqual(e.message, '') assert.strictEqual(e.message, '')
assert.strictEqual(e.name, 'AggregateError') assert.strictEqual(e.name, 'AggregateError')
assert.strictEqual(Object.keys(e).length, 0) assert.strictEqual(Object.keys(e).length, 0)
@@ -55,8 +55,8 @@ describe('errors', function () {
assert(e instanceof errors.AbortError) assert(e instanceof errors.AbortError)
}) })
it('should list options properties but not name and message', function () { it('should list options properties but not name and message', () => {
var e = new errors.AggregateError({ const e = new errors.AggregateError({
name: 'weird', name: 'weird',
message: 'hello world', message: 'hello world',
property: true property: true
@@ -72,8 +72,8 @@ describe('errors', function () {
assert.strictEqual(e.name, 'AggregateError') assert.strictEqual(e.name, 'AggregateError')
}) })
it('should change name and message', function () { it('should change name and message', () => {
var e = new errors.AggregateError({ const e = new errors.AggregateError({
message: 'hello world', message: 'hello world',
property: true property: true
}) })

View File

@@ -1,22 +1,22 @@
'use strict' 'use strict'
var Buffer = require('safe-buffer').Buffer const Buffer = require('safe-buffer').Buffer
var assert = require('assert') const assert = require('assert')
var config = require('./lib/config') const config = require('./lib/config')
var helper = require('./helper') const helper = require('./helper')
var redis = config.redis const redis = config.redis
describe('detectBuffers', function () { describe('detectBuffers', () => {
var client let client
var args = config.configureClient('localhost', { const args = config.configureClient('localhost', {
detectBuffers: true detectBuffers: true
}) })
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('error', done) client.once('error', done)
client.once('connect', function () { client.once('connect', () => {
client.flushdb(function (err) { client.flushdb((err) => {
client.hmset('hash key 2', 'key 1', 'val 1', 'key 2', 'val 2') client.hmset('hash key 2', 'key 1', 'val 1', 'key 2', 'val 2')
client.set('string key 1', 'string value') client.set('string key 1', 'string value')
return done(err) return done(err)
@@ -24,34 +24,34 @@ describe('detectBuffers', function () {
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
describe('get', function () { describe('get', () => {
describe('first argument is a string', function () { describe('first argument is a string', () => {
it('returns a string', function (done) { it('returns a string', (done) => {
client.get('string key 1', helper.isString('string value', done)) client.get('string key 1', helper.isString('string value', done))
}) })
it('returns a string when executed as part of transaction', function (done) { it('returns a string when executed as part of transaction', (done) => {
client.multi().get('string key 1').exec(function (err, res) { client.multi().get('string key 1').exec((err, res) => {
helper.isString('string value', done)(err, res[0]) helper.isString('string value', done)(err, res[0])
}) })
}) })
}) })
describe('first argument is a buffer', function () { describe('first argument is a buffer', () => {
it('returns a buffer', function (done) { it('returns a buffer', (done) => {
client.get(Buffer.from('string key 1'), function (err, reply) { client.get(Buffer.from('string key 1'), (err, reply) => {
assert.strictEqual(true, Buffer.isBuffer(reply)) assert.strictEqual(true, Buffer.isBuffer(reply))
assert.strictEqual('<Buffer 73 74 72 69 6e 67 20 76 61 6c 75 65>', reply.inspect()) assert.strictEqual('<Buffer 73 74 72 69 6e 67 20 76 61 6c 75 65>', reply.inspect())
return done(err) return done(err)
}) })
}) })
it('returns a bufffer when executed as part of transaction', function (done) { it('returns a bufffer when executed as part of transaction', (done) => {
client.multi().get(Buffer.from('string key 1')).exec(function (err, reply) { client.multi().get(Buffer.from('string key 1')).exec((err, reply) => {
assert.strictEqual(1, reply.length) assert.strictEqual(1, reply.length)
assert.strictEqual(true, Buffer.isBuffer(reply[0])) assert.strictEqual(true, Buffer.isBuffer(reply[0]))
assert.strictEqual('<Buffer 73 74 72 69 6e 67 20 76 61 6c 75 65>', reply[0].inspect()) assert.strictEqual('<Buffer 73 74 72 69 6e 67 20 76 61 6c 75 65>', reply[0].inspect())
@@ -61,14 +61,14 @@ describe('detectBuffers', function () {
}) })
}) })
describe('multi.hget', function () { describe('multi.hget', () => {
it('can interleave string and buffer results', function (done) { it('can interleave string and buffer results', (done) => {
client.multi() client.multi()
.hget('hash key 2', 'key 1') .hget('hash key 2', 'key 1')
.hget(Buffer.from('hash key 2'), 'key 1') .hget(Buffer.from('hash key 2'), 'key 1')
.hget('hash key 2', Buffer.from('key 2')) .hget('hash key 2', Buffer.from('key 2'))
.hget('hash key 2', 'key 2') .hget('hash key 2', 'key 2')
.exec(function (err, reply) { .exec((err, reply) => {
assert.strictEqual(true, Array.isArray(reply)) assert.strictEqual(true, Array.isArray(reply))
assert.strictEqual(4, reply.length) assert.strictEqual(4, reply.length)
assert.strictEqual('val 1', reply[0]) assert.strictEqual('val 1', reply[0])
@@ -82,14 +82,14 @@ describe('detectBuffers', function () {
}) })
}) })
describe('batch.hget', function () { describe('batch.hget', () => {
it('can interleave string and buffer results', function (done) { it('can interleave string and buffer results', (done) => {
client.batch() client.batch()
.hget('hash key 2', 'key 1') .hget('hash key 2', 'key 1')
.hget(Buffer.from('hash key 2'), 'key 1') .hget(Buffer.from('hash key 2'), 'key 1')
.hget('hash key 2', Buffer.from('key 2')) .hget('hash key 2', Buffer.from('key 2'))
.hget('hash key 2', 'key 2') .hget('hash key 2', 'key 2')
.exec(function (err, reply) { .exec((err, reply) => {
assert.strictEqual(true, Array.isArray(reply)) assert.strictEqual(true, Array.isArray(reply))
assert.strictEqual(4, reply.length) assert.strictEqual(4, reply.length)
assert.strictEqual('val 1', reply[0]) assert.strictEqual('val 1', reply[0])
@@ -103,10 +103,10 @@ describe('detectBuffers', function () {
}) })
}) })
describe('hmget', function () { describe('hmget', () => {
describe('first argument is a string', function () { describe('first argument is a string', () => {
it('returns strings for keys requested', function (done) { it('returns strings for keys requested', (done) => {
client.hmget('hash key 2', 'key 1', 'key 2', function (err, reply) { client.hmget('hash key 2', 'key 1', 'key 2', (err, reply) => {
assert.strictEqual(true, Array.isArray(reply)) assert.strictEqual(true, Array.isArray(reply))
assert.strictEqual(2, reply.length) assert.strictEqual(2, reply.length)
assert.strictEqual('val 1', reply[0]) assert.strictEqual('val 1', reply[0])
@@ -115,8 +115,8 @@ describe('detectBuffers', function () {
}) })
}) })
it('returns strings for keys requested in transaction', function (done) { it('returns strings for keys requested in transaction', (done) => {
client.multi().hmget('hash key 2', 'key 1', 'key 2').exec(function (err, reply) { client.multi().hmget('hash key 2', 'key 1', 'key 2').exec((err, reply) => {
assert.strictEqual(true, Array.isArray(reply)) assert.strictEqual(true, Array.isArray(reply))
assert.strictEqual(1, reply.length) assert.strictEqual(1, reply.length)
assert.strictEqual(2, reply[0].length) assert.strictEqual(2, reply[0].length)
@@ -126,8 +126,8 @@ describe('detectBuffers', function () {
}) })
}) })
it('handles array of strings with undefined values (repro #344)', function (done) { it('handles array of strings with undefined values (repro #344)', (done) => {
client.hmget('hash key 2', 'key 3', 'key 4', function (err, reply) { client.hmget('hash key 2', 'key 3', 'key 4', (err, reply) => {
assert.strictEqual(true, Array.isArray(reply)) assert.strictEqual(true, Array.isArray(reply))
assert.strictEqual(2, reply.length) assert.strictEqual(2, reply.length)
assert.strictEqual(null, reply[0]) assert.strictEqual(null, reply[0])
@@ -136,8 +136,8 @@ describe('detectBuffers', function () {
}) })
}) })
it('handles array of strings with undefined values in transaction (repro #344)', function (done) { it('handles array of strings with undefined values in transaction (repro #344)', (done) => {
client.multi().hmget('hash key 2', 'key 3', 'key 4').exec(function (err, reply) { client.multi().hmget('hash key 2', 'key 3', 'key 4').exec((err, reply) => {
assert.strictEqual(true, Array.isArray(reply)) assert.strictEqual(true, Array.isArray(reply))
assert.strictEqual(1, reply.length) assert.strictEqual(1, reply.length)
assert.strictEqual(2, reply[0].length) assert.strictEqual(2, reply[0].length)
@@ -148,9 +148,9 @@ describe('detectBuffers', function () {
}) })
}) })
describe('first argument is a buffer', function () { describe('first argument is a buffer', () => {
it('returns buffers for keys requested', function (done) { it('returns buffers for keys requested', (done) => {
client.hmget(Buffer.from('hash key 2'), 'key 1', 'key 2', function (err, reply) { client.hmget(Buffer.from('hash key 2'), 'key 1', 'key 2', (err, reply) => {
assert.strictEqual(true, Array.isArray(reply)) assert.strictEqual(true, Array.isArray(reply))
assert.strictEqual(2, reply.length) assert.strictEqual(2, reply.length)
assert.strictEqual(true, Buffer.isBuffer(reply[0])) assert.strictEqual(true, Buffer.isBuffer(reply[0]))
@@ -161,8 +161,8 @@ describe('detectBuffers', function () {
}) })
}) })
it('returns buffers for keys requested in transaction', function (done) { it('returns buffers for keys requested in transaction', (done) => {
client.multi().hmget(Buffer.from('hash key 2'), 'key 1', 'key 2').exec(function (err, reply) { client.multi().hmget(Buffer.from('hash key 2'), 'key 1', 'key 2').exec((err, reply) => {
assert.strictEqual(true, Array.isArray(reply)) assert.strictEqual(true, Array.isArray(reply))
assert.strictEqual(1, reply.length) assert.strictEqual(1, reply.length)
assert.strictEqual(2, reply[0].length) assert.strictEqual(2, reply[0].length)
@@ -174,8 +174,8 @@ describe('detectBuffers', function () {
}) })
}) })
it('returns buffers for keys requested in .batch', function (done) { it('returns buffers for keys requested in .batch', (done) => {
client.batch().hmget(Buffer.from('hash key 2'), 'key 1', 'key 2').exec(function (err, reply) { client.batch().hmget(Buffer.from('hash key 2'), 'key 1', 'key 2').exec((err, reply) => {
assert.strictEqual(true, Array.isArray(reply)) assert.strictEqual(true, Array.isArray(reply))
assert.strictEqual(1, reply.length) assert.strictEqual(1, reply.length)
assert.strictEqual(2, reply[0].length) assert.strictEqual(2, reply[0].length)
@@ -189,10 +189,10 @@ describe('detectBuffers', function () {
}) })
}) })
describe('hgetall', function (done) { describe('hgetall', (done) => {
describe('first argument is a string', function () { describe('first argument is a string', () => {
it('returns string values', function (done) { it('returns string values', (done) => {
client.hgetall('hash key 2', function (err, reply) { client.hgetall('hash key 2', (err, reply) => {
assert.strictEqual('object', typeof reply) assert.strictEqual('object', typeof reply)
assert.strictEqual(2, Object.keys(reply).length) assert.strictEqual(2, Object.keys(reply).length)
assert.strictEqual('val 1', reply['key 1']) assert.strictEqual('val 1', reply['key 1'])
@@ -201,8 +201,8 @@ describe('detectBuffers', function () {
}) })
}) })
it('returns string values when executed in transaction', function (done) { it('returns string values when executed in transaction', (done) => {
client.multi().hgetall('hash key 2').exec(function (err, reply) { client.multi().hgetall('hash key 2').exec((err, reply) => {
assert.strictEqual(1, reply.length) assert.strictEqual(1, reply.length)
assert.strictEqual('object', typeof reply[0]) assert.strictEqual('object', typeof reply[0])
assert.strictEqual(2, Object.keys(reply[0]).length) assert.strictEqual(2, Object.keys(reply[0]).length)
@@ -212,8 +212,8 @@ describe('detectBuffers', function () {
}) })
}) })
it('returns string values when executed in .batch', function (done) { it('returns string values when executed in .batch', (done) => {
client.batch().hgetall('hash key 2').exec(function (err, reply) { client.batch().hgetall('hash key 2').exec((err, reply) => {
assert.strictEqual(1, reply.length) assert.strictEqual(1, reply.length)
assert.strictEqual('object', typeof reply[0]) assert.strictEqual('object', typeof reply[0])
assert.strictEqual(2, Object.keys(reply[0]).length) assert.strictEqual(2, Object.keys(reply[0]).length)
@@ -224,9 +224,9 @@ describe('detectBuffers', function () {
}) })
}) })
describe('first argument is a buffer', function () { describe('first argument is a buffer', () => {
it('returns buffer values', function (done) { it('returns buffer values', (done) => {
client.hgetall(Buffer.from('hash key 2'), function (err, reply) { client.hgetall(Buffer.from('hash key 2'), (err, reply) => {
assert.strictEqual(null, err) assert.strictEqual(null, err)
assert.strictEqual('object', typeof reply) assert.strictEqual('object', typeof reply)
assert.strictEqual(2, Object.keys(reply).length) assert.strictEqual(2, Object.keys(reply).length)
@@ -238,8 +238,8 @@ describe('detectBuffers', function () {
}) })
}) })
it('returns buffer values when executed in transaction', function (done) { it('returns buffer values when executed in transaction', (done) => {
client.multi().hgetall(Buffer.from('hash key 2')).exec(function (err, reply) { client.multi().hgetall(Buffer.from('hash key 2')).exec((err, reply) => {
assert.strictEqual(1, reply.length) assert.strictEqual(1, reply.length)
assert.strictEqual('object', typeof reply[0]) assert.strictEqual('object', typeof reply[0])
assert.strictEqual(2, Object.keys(reply[0]).length) assert.strictEqual(2, Object.keys(reply[0]).length)
@@ -251,8 +251,8 @@ describe('detectBuffers', function () {
}) })
}) })
it('returns buffer values when executed in .batch', function (done) { it('returns buffer values when executed in .batch', (done) => {
client.batch().hgetall(Buffer.from('hash key 2')).exec(function (err, reply) { client.batch().hgetall(Buffer.from('hash key 2')).exec((err, reply) => {
assert.strictEqual(1, reply.length) assert.strictEqual(1, reply.length)
assert.strictEqual('object', typeof reply[0]) assert.strictEqual('object', typeof reply[0])
assert.strictEqual(2, Object.keys(reply[0]).length) assert.strictEqual(2, Object.keys(reply[0]).length)

View File

@@ -1,44 +1,44 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('./lib/config') const config = require('./lib/config')
var fork = require('child_process').fork const fork = require('child_process').fork
var redis = config.redis const redis = config.redis
describe('stack traces', function () { describe('stack traces', () => {
it('should return good traces with NODE_ENV=development set', function (done) { it('should return good traces with NODE_ENV=development set', (done) => {
var external = fork('./test/lib/good-traces.js', { const external = fork('./test/lib/good-traces.js', {
env: { env: {
NODE_ENV: 'development' NODE_ENV: 'development'
} }
}) })
var id = setTimeout(function () { const id = setTimeout(() => {
external.kill() external.kill()
done(new Error('Timeout')) done(new Error('Timeout'))
}, 6000) }, 6000)
external.on('close', function (code) { external.on('close', (code) => {
clearTimeout(id) clearTimeout(id)
assert.strictEqual(code, 0) assert.strictEqual(code, 0)
done() done()
}) })
}) })
it('should return good traces with NODE_DEBUG=redis env set', function (done) { it('should return good traces with NODE_DEBUG=redis env set', (done) => {
var external = fork('./test/lib/good-traces.js', { const external = fork('./test/lib/good-traces.js', {
env: { env: {
NODE_DEBUG: 'redis' NODE_DEBUG: 'redis'
}, },
silent: true silent: true
}) })
var id = setTimeout(function () { const id = setTimeout(() => {
external.kill() external.kill()
done(new Error('Timeout')) done(new Error('Timeout'))
}, 6000) }, 6000)
external.on('close', function (code) { external.on('close', (code) => {
clearTimeout(id) clearTimeout(id)
assert.strictEqual(code, 0) assert.strictEqual(code, 0)
done() done()
@@ -46,11 +46,11 @@ describe('stack traces', function () {
}) })
// This is always going to return good stack traces // This is always going to return good stack traces
it('should always return good stack traces for rejected offline commands', function (done) { it('should always return good stack traces for rejected offline commands', (done) => {
var client = redis.createClient({ const client = redis.createClient({
enableOfflineQueue: false enableOfflineQueue: false
}) })
client.set('foo', function (err, res) { client.set('foo', (err, res) => {
assert(/good_traces.spec.js/.test(err.stack)) assert(/good_traces.spec.js/.test(err.stack))
client.quit(done) client.quit(done)
}) })

View File

@@ -1,15 +1,15 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var path = require('path') const path = require('path')
var config = require('./lib/config') const config = require('./lib/config')
var RedisProcess = require('./lib/redis-process') const RedisProcess = require('./lib/redis-process')
var StunnelProcess = require('./lib/stunnel-process') const StunnelProcess = require('./lib/stunnel-process')
var rp let rp
var stunnelProcess let stunnelProcess
function startRedis (conf, done, port) { function startRedis (conf, done, port) {
RedisProcess.start(function (err, _rp) { RedisProcess.start((err, _rp) => {
rp = _rp rp = _rp
return done(err) return done(err)
}, path.resolve(__dirname, conf), port) }, path.resolve(__dirname, conf), port)
@@ -20,11 +20,11 @@ function startRedis (conf, done, port) {
if (!process.env.REDIS_TESTS_STARTED) { if (!process.env.REDIS_TESTS_STARTED) {
process.env.REDIS_TESTS_STARTED = true process.env.REDIS_TESTS_STARTED = true
before(function (done) { before((done) => {
startRedis('./conf/redis.conf', done) startRedis('./conf/redis.conf', done)
}) })
after(function (done) { after((done) => {
if (rp) rp.stop(done) if (rp) rp.stop(done)
}) })
} }
@@ -49,120 +49,120 @@ function toString (res) {
} }
module.exports = { module.exports = {
redisProcess: function () { redisProcess () {
return rp return rp
}, },
stopRedis: function (done) { stopRedis (done) {
rp.stop(done) rp.stop(done)
}, },
startRedis: startRedis, startRedis,
stopStunnel: function (done) { stopStunnel (done) {
if (stunnelProcess) { if (stunnelProcess) {
StunnelProcess.stop(stunnelProcess, done) StunnelProcess.stop(stunnelProcess, done)
} else { } else {
done() done()
} }
}, },
startStunnel: function (done) { startStunnel (done) {
StunnelProcess.start(function (err, _stunnelProcess) { StunnelProcess.start((err, _stunnelProcess) => {
stunnelProcess = _stunnelProcess stunnelProcess = _stunnelProcess
return done(err) return done(err)
}, path.resolve(__dirname, './conf')) }, path.resolve(__dirname, './conf'))
}, },
isNumber: function (expected, done) { isNumber (expected, done) {
return function (err, results) { return function (err, results) {
assert.strictEqual(err, null, 'expected ' + expected + ', got error: ' + err) assert.strictEqual(err, null, `expected ${expected}, got error: ${err}`)
results = arrayHelper(results) results = arrayHelper(results)
assert.strictEqual(results, expected, expected + ' !== ' + results) assert.strictEqual(results, expected, `${expected } !== ${results}`)
assert.strictEqual(typeof results, 'number', 'expected a number, got ' + typeof results) assert.strictEqual(typeof results, 'number', `expected a number, got ${typeof results}`)
if (done) done() if (done) done()
} }
}, },
isString: function (str, done) { isString (str, done) {
str = '' + str // Make sure it's a string str = `${str}` // Make sure it's a string
return function (err, results) { return function (err, results) {
assert.strictEqual(err, null, 'expected string \'' + str + '\', got error: ' + err) assert.strictEqual(err, null, `expected string '${str}', got error: ${err}`)
results = arrayHelper(results) results = arrayHelper(results)
results = toString(results) results = toString(results)
assert.strictEqual(results, str, str + ' does not match ' + results) assert.strictEqual(results, str, `${str } does not match ${results}`)
if (done) done() if (done) done()
} }
}, },
isNull: function (done) { isNull (done) {
return function (err, results) { return function (err, results) {
assert.strictEqual(err, null, 'expected null, got error: ' + err) assert.strictEqual(err, null, `expected null, got error: ${err}`)
results = arrayHelper(results) results = arrayHelper(results)
assert.strictEqual(results, null, results + ' is not null') assert.strictEqual(results, null, `${results } is not null`)
if (done) done() if (done) done()
} }
}, },
isUndefined: function (done) { isUndefined (done) {
return function (err, results) { return function (err, results) {
assert.strictEqual(err, null, 'expected null, got error: ' + err) assert.strictEqual(err, null, `expected null, got error: ${err}`)
results = arrayHelper(results) results = arrayHelper(results)
assert.strictEqual(results, undefined, results + ' is not undefined') assert.strictEqual(results, undefined, `${results } is not undefined`)
if (done) done() if (done) done()
} }
}, },
isError: function (done) { isError (done) {
return function (err, results) { return function (err, results) {
assert(err instanceof Error, 'err is not instance of \'Error\', but an error is expected here.') assert(err instanceof Error, 'err is not instance of \'Error\', but an error is expected here.')
if (done) done() if (done) done()
} }
}, },
isNotError: function (done) { isNotError (done) {
return function (err, results) { return function (err, results) {
assert.strictEqual(err, null, 'expected success, got an error: ' + err) assert.strictEqual(err, null, `expected success, got an error: ${err}`)
if (done) done() if (done) done()
} }
}, },
isDeepEqual: function (args, done) { isDeepEqual (args, done) {
return function (err, res) { return function (err, res) {
assert.strictEqual(err, null, 'expected null, got error: ' + err) assert.strictEqual(err, null, `expected null, got error: ${err}`)
res = toString(res) res = toString(res)
assert.deepStrictEqual(res, args) assert.deepStrictEqual(res, args)
if (done) done() if (done) done()
} }
}, },
isType: { isType: {
number: function (done) { number (done) {
return function (err, results) { return function (err, results) {
assert.strictEqual(err, null, 'expected any number, got error: ' + err) assert.strictEqual(err, null, `expected any number, got error: ${err}`)
assert.strictEqual(typeof results, 'number', results + ' is not a number') assert.strictEqual(typeof results, 'number', `${results } is not a number`)
if (done) done() if (done) done()
} }
}, },
string: function (done) { string (done) {
return function (err, results) { return function (err, results) {
assert.strictEqual(err, null, 'expected any string, got error: ' + err) assert.strictEqual(err, null, `expected any string, got error: ${err}`)
assert.strictEqual(typeof results, 'string', results + ' is not a string') assert.strictEqual(typeof results, 'string', `${results } is not a string`)
if (done) done() if (done) done()
} }
}, },
positiveNumber: function (done) { positiveNumber (done) {
return function (err, results) { return function (err, results) {
assert.strictEqual(err, null, 'expected positive number, got error: ' + err) assert.strictEqual(err, null, `expected positive number, got error: ${err}`)
assert(results > 0, results + ' is not a positive number') assert(results > 0, `${results } is not a positive number`)
if (done) done() if (done) done()
} }
} }
}, },
match: function (pattern, done) { match (pattern, done) {
return function (err, results) { return function (err, results) {
assert.strictEqual(err, null, 'expected ' + pattern.toString() + ', got error: ' + err) assert.strictEqual(err, null, `expected ${pattern.toString()}, got error: ${err}`)
results = arrayHelper(results) results = arrayHelper(results)
assert(pattern.test(results), 'expected string \'' + results + '\' to match ' + pattern.toString()) assert(pattern.test(results), `expected string '${results}' to match ${pattern.toString()}`)
if (done) done() if (done) done()
} }
}, },
serverVersionAtLeast: function (connection, desiredVersion) { serverVersionAtLeast (connection, desiredVersion) {
// Wait until a connection has established (otherwise a timeout is going to be triggered at some point) // Wait until a connection has established (otherwise a timeout is going to be triggered at some point)
if (Object.keys(connection.serverInfo).length === 0) { if (Object.keys(connection.serverInfo).length === 0) {
throw new Error('Version check not possible as the client is not yet ready or did not expose the version') throw new Error('Version check not possible as the client is not yet ready or did not expose the version')
} }
// Return true if the server version >= desiredVersion // Return true if the server version >= desiredVersion
var version = connection.serverInfo.versions const version = connection.serverInfo.versions
for (var i = 0; i < 3; i++) { for (let i = 0; i < 3; i++) {
if (version[i] > desiredVersion[i]) { if (version[i] > desiredVersion[i]) {
return true return true
} }
@@ -173,30 +173,30 @@ module.exports = {
} }
return true return true
}, },
allTests: function (opts, cb) { allTests (opts, cb) {
if (!cb) { if (!cb) {
cb = opts cb = opts
opts = {} opts = {}
} }
var protocols = ['IPv4'] const protocols = ['IPv4']
if (process.platform !== 'win32') { if (process.platform !== 'win32') {
protocols.push('IPv6', '/tmp/redis.sock') protocols.push('IPv6', '/tmp/redis.sock')
} }
var options = [{ const options = [{
detectBuffers: true detectBuffers: true
}, { }, {
detectBuffers: false detectBuffers: false
}] }]
options.forEach(function (options) { options.forEach((options) => {
var strOptions = '' let strOptions = ''
var key let key
for (key in options) { for (key in options) {
if (options.hasOwnProperty(key)) { if (options.hasOwnProperty(key)) {
strOptions += key + ': ' + options[key] + '; ' strOptions += `${key }: ${options[key]}; `
} }
} }
describe('using options: ' + strOptions, function () { describe(`using options: ${strOptions}`, () => {
protocols.forEach(function (ip, i) { protocols.forEach((ip, i) => {
if (i !== 0 && !opts.allConnections) { if (i !== 0 && !opts.allConnections) {
return return
} }
@@ -205,13 +205,13 @@ module.exports = {
}) })
}) })
}, },
removeMochaListener: function () { removeMochaListener () {
var mochaListener = process.listeners('uncaughtException').pop() const mochaListener = process.listeners('uncaughtException').pop()
process.removeListener('uncaughtException', mochaListener) process.removeListener('uncaughtException', mochaListener)
return mochaListener return mochaListener
}, },
callFuncAfter: function (func, max) { callFuncAfter (func, max) {
var i = 0 let i = 0
return function (err) { return function (err) {
if (err) { if (err) {
throw err throw err
@@ -224,7 +224,7 @@ module.exports = {
return false return false
} }
}, },
killConnection: function (client) { killConnection (client) {
// Change the connection option to a non existing one and destroy the stream // Change the connection option to a non existing one and destroy the stream
client.connectionOptions = { client.connectionOptions = {
port: 65535, port: 65535,

View File

@@ -2,22 +2,22 @@
// helpers for configuring a redis client in // helpers for configuring a redis client in
// its various modes, ipV6, ipV4, socket. // its various modes, ipV6, ipV4, socket.
var redis = require('../../index') const redis = require('../../index')
var bluebird = require('bluebird') const bluebird = require('bluebird')
// Promisify everything // Promisify everything
bluebird.promisifyAll(redis.RedisClient.prototype) bluebird.promisifyAll(redis.RedisClient.prototype)
bluebird.promisifyAll(redis.Multi.prototype) bluebird.promisifyAll(redis.Multi.prototype)
var config = { const config = {
redis: redis, redis,
PORT: 6379, PORT: 6379,
HOST: { HOST: {
IPv4: '127.0.0.1', IPv4: '127.0.0.1',
IPv6: '::1' IPv6: '::1'
}, },
configureClient: function (ip, opts) { configureClient (ip, opts) {
var args = [] const args = []
// Do not manipulate the opts => copy them each time // Do not manipulate the opts => copy them each time
opts = opts ? JSON.parse(JSON.stringify(opts)) : {} opts = opts ? JSON.parse(JSON.stringify(opts)) : {}

View File

@@ -1,20 +1,20 @@
// Spawned by the goodStacks.spec.js tests // Spawned by the goodStacks.spec.js tests
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var redis = require('../../index') const redis = require('../../index')
var client = redis.createClient() const client = redis.createClient()
// Both error cases would normally return bad stack traces // Both error cases would normally return bad stack traces
client.set('foo', function (err, res) { client.set('foo', (err, res) => {
assert(/good-traces.js:9:8/.test(err.stack)) assert(/good-traces.js:9:8/.test(err.stack))
client.set('foo', 'bar', function (err, res) { client.set('foo', 'bar', (err, res) => {
assert(/good-traces.js:11:10/.test(err.stack)) assert(/good-traces.js:11:10/.test(err.stack))
client.quit(function () { client.quit(() => {
process.exit(0) process.exit(0)
}) })
}) })
process.nextTick(function () { process.nextTick(() => {
client.stream.destroy() client.stream.destroy()
}) })
}) })

View File

@@ -1,82 +1,82 @@
'use strict' 'use strict'
// helper to start and stop the redis process. // helper to start and stop the redis process.
var config = require('./config') const config = require('./config')
var fs = require('fs') const fs = require('fs')
var path = require('path') const path = require('path')
var spawn = require('win-spawn') const spawn = require('win-spawn')
var tcpPortUsed = require('tcp-port-used') const tcpPortUsed = require('tcp-port-used')
var bluebird = require('bluebird') const bluebird = require('bluebird')
// wait for redis to be listening in // wait for redis to be listening in
// all three modes (ipv4, ipv6, socket). // all three modes (ipv4, ipv6, socket).
function waitForRedis (available, cb, port) { function waitForRedis (available, cb, port) {
if (process.platform === 'win32') return cb() if (process.platform === 'win32') return cb()
var time = Date.now() const time = Date.now()
var running = false let running = false
var socket = '/tmp/redis.sock' let socket = '/tmp/redis.sock'
if (port) { if (port) {
// We have to distinguish the redis sockets if we have more than a single redis instance running // We have to distinguish the redis sockets if we have more than a single redis instance running
socket = '/tmp/redis' + port + '.sock' socket = `/tmp/redis${port}.sock`
} }
port = port || config.PORT port = port || config.PORT
var id = setInterval(function () { const id = setInterval(() => {
if (running) return if (running) return
running = true running = true
bluebird.join( bluebird.join(
tcpPortUsed.check(port, '127.0.0.1'), tcpPortUsed.check(port, '127.0.0.1'),
tcpPortUsed.check(port, '::1'), tcpPortUsed.check(port, '::1'),
function (ipV4, ipV6) { (ipV4, ipV6) => {
if (ipV6 === available && ipV4 === available) { if (ipV6 === available && ipV4 === available) {
if (fs.existsSync(socket) === available) { if (fs.existsSync(socket) === available) {
clearInterval(id) clearInterval(id)
return cb() return cb()
} }
// The same message applies for can't stop but we ignore that case // The same message applies for can't stop but we ignore that case
throw new Error('Port ' + port + ' is already in use. Tests can\'t start.\n') throw new Error(`Port ${port} is already in use. Tests can't start.\n`)
} }
if (Date.now() - time > 6000) { if (Date.now() - time > 6000) {
throw new Error('Redis could not start on port ' + (port || config.PORT) + '\n') throw new Error(`Redis could not start on port ${port || config.PORT}\n`)
} }
running = false running = false
}).catch(function (err) { }).catch((err) => {
console.error('\x1b[31m' + err.stack + '\x1b[0m\n') console.error(`\x1b[31m${err.stack}\x1b[0m\n`)
process.exit(1) process.exit(1)
}) })
}, 100) }, 100)
} }
module.exports = { module.exports = {
start: function (done, conf, port) { start (done, conf, port) {
var spawnFailed = false let spawnFailed = false
// spawn redis with our testing configuration. // spawn redis with our testing configuration.
var confFile = conf || path.resolve(__dirname, '../conf/redis.conf') const confFile = conf || path.resolve(__dirname, '../conf/redis.conf')
var rp = spawn('redis-server', [confFile], {}) const rp = spawn('redis-server', [confFile], {})
// capture a failure booting redis, and give // capture a failure booting redis, and give
// the user running the test some directions. // the user running the test some directions.
rp.once('exit', function (code) { rp.once('exit', (code) => {
if (code !== 0) spawnFailed = true if (code !== 0) spawnFailed = true
}) })
// wait for redis to become available, by // wait for redis to become available, by
// checking the port we bind on. // checking the port we bind on.
waitForRedis(true, function () { waitForRedis(true, () => {
// return an object that can be used in // return an object that can be used in
// an after() block to shutdown redis. // an after() block to shutdown redis.
return done(null, { return done(null, {
spawnFailed: function () { spawnFailed () {
return spawnFailed return spawnFailed
}, },
stop: function (done) { stop (done) {
if (spawnFailed) return done() if (spawnFailed) return done()
rp.once('exit', function (code) { rp.once('exit', (code) => {
var error = null let error = null
if (code !== null && code !== 0) { if (code !== null && code !== 0) {
error = new Error('Redis shutdown failed with code ' + code) error = new Error(`Redis shutdown failed with code ${code}`)
} }
waitForRedis(false, function () { waitForRedis(false, () => {
return done(error) return done(error)
}, port) }, port)
}) })

View File

@@ -1,14 +1,14 @@
'use strict' 'use strict'
// helper to start and stop the stunnel process. // helper to start and stop the stunnel process.
var spawn = require('child_process').spawn const spawn = require('child_process').spawn
var EventEmitter = require('events') const EventEmitter = require('events')
var fs = require('fs') const fs = require('fs')
var path = require('path') const path = require('path')
var util = require('util') const util = require('util')
function once (cb) { function once (cb) {
var called = false let called = false
return function () { return function () {
if (called) return if (called) return
called = true called = true
@@ -20,29 +20,29 @@ function StunnelProcess (confDir) {
EventEmitter.call(this) EventEmitter.call(this)
// set up an stunnel to redis; edit the conf file to include required absolute paths // set up an stunnel to redis; edit the conf file to include required absolute paths
var confFile = path.resolve(confDir, 'stunnel.conf') const confFile = path.resolve(confDir, 'stunnel.conf')
var confText = fs.readFileSync(confFile + '.template').toString().replace(/__dirname,/g, confDir) const confText = fs.readFileSync(`${confFile }.template`).toString().replace(/__dirname,/g, confDir)
fs.writeFileSync(confFile, confText) fs.writeFileSync(confFile, confText)
var stunnel = this.stunnel = spawn('stunnel', [confFile]) const stunnel = this.stunnel = spawn('stunnel', [confFile])
// handle child process events, and failure to set up tunnel // handle child process events, and failure to set up tunnel
var self = this const self = this
this.timer = setTimeout(function () { this.timer = setTimeout(() => {
self.emit('error', new Error('Timeout waiting for stunnel to start')) self.emit('error', new Error('Timeout waiting for stunnel to start'))
}, 8000) }, 8000)
stunnel.on('error', function (err) { stunnel.on('error', (err) => {
self.clear() self.clear()
self.emit('error', err) self.emit('error', err)
}) })
stunnel.on('exit', function (code) { stunnel.on('exit', (code) => {
self.clear() self.clear()
if (code === 0) { if (code === 0) {
self.emit('stopped') self.emit('stopped')
} else { } else {
self.emit('error', new Error('Stunnel exited unexpectedly; code = ' + code)) self.emit('error', new Error(`Stunnel exited unexpectedly; code = ${code}`))
} }
}) })
@@ -68,13 +68,13 @@ StunnelProcess.prototype.stop = function (done) {
} }
module.exports = { module.exports = {
start: function (done, confDir) { start (done, confDir) {
done = once(done) done = once(done)
var stunnel = new StunnelProcess(confDir) const stunnel = new StunnelProcess(confDir)
stunnel.once('error', done.bind(done)) stunnel.once('error', done.bind(done))
stunnel.once('started', done.bind(done, null, stunnel)) stunnel.once('started', done.bind(done, null, stunnel))
}, },
stop: function (stunnel, done) { stop (stunnel, done) {
stunnel.removeAllListeners() stunnel.removeAllListeners()
stunnel.stop() stunnel.stop()
stunnel.once('error', done.bind(done)) stunnel.once('error', done.bind(done))

View File

@@ -3,13 +3,13 @@
// as soon as there are no outstanding commands. // as soon as there are no outstanding commands.
'use strict' 'use strict'
var redis = require('../../index') const redis = require('../../index')
var HOST = process.argv[2] || '127.0.0.1' const HOST = process.argv[2] || '127.0.0.1'
var PORT = process.argv[3] const PORT = process.argv[3]
var args = PORT ? [PORT, HOST] : [HOST] const args = PORT ? [PORT, HOST] : [HOST]
var c = redis.createClient.apply(redis, args) const c = redis.createClient.apply(redis, args)
c.info(function (err, reply) { c.info((err, reply) => {
if (err) process.exit(-1) if (err) process.exit(-1)
if (!reply.length) process.exit(-1) if (!reply.length) process.exit(-1)
process.stdout.write(reply.length.toString()) process.stdout.write(reply.length.toString())

View File

@@ -1,28 +1,28 @@
'use strict' 'use strict'
var Buffer = require('safe-buffer').Buffer const Buffer = require('safe-buffer').Buffer
var assert = require('assert') const assert = require('assert')
var config = require('./lib/config') const config = require('./lib/config')
var helper = require('./helper') const helper = require('./helper')
var utils = require('../lib/utils') const utils = require('../lib/utils')
var redis = config.redis const redis = config.redis
var zlib = require('zlib') const zlib = require('zlib')
var client let client
describe('The \'multi\' method', function () { describe('The \'multi\' method', () => {
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
describe('regression test', function () { describe('regression test', () => {
it('saved buffers with charsets different than utf-8 (issue #913)', function (done) { it('saved buffers with charsets different than utf-8 (issue #913)', function (done) {
this.timeout(12000) // Windows tests on 0.10 are slow this.timeout(12000) // Windows tests on 0.10 are slow
client = redis.createClient() client = redis.createClient()
var end = helper.callFuncAfter(done, 100) const end = helper.callFuncAfter(done, 100)
// Some random object created from http://beta.json-generator.com/ // Some random object created from http://beta.json-generator.com/
var testObj = { const testObj = {
'Id': '5642c4c33d4667c4a1fefd99', 'Id': '5642c4c33d4667c4a1fefd99',
'index': 0, 'index': 0,
'guid': '5baf1f1c-7621-41e7-ae7a-f8c6f3199b0f', 'guid': '5baf1f1c-7621-41e7-ae7a-f8c6f3199b0f',
@@ -53,27 +53,27 @@ describe('The \'multi\' method', function () {
return return
} }
// To demonstrate a big payload for hash set field values, let's create a big array // To demonstrate a big payload for hash set field values, let's create a big array
var testArr = [] const testArr = []
var i = 0 let i = 0
for (; i < 80; i++) { for (; i < 80; i++) {
var newObj = JSON.parse(JSON.stringify(testObj)) const newObj = JSON.parse(JSON.stringify(testObj))
testArr.push(newObj) testArr.push(newObj)
} }
var json = JSON.stringify(testArr) const json = JSON.stringify(testArr)
zlib.deflate(Buffer.from(json), function (err, buffer) { zlib.deflate(Buffer.from(json), (err, buffer) => {
if (err) { if (err) {
done(err) done(err)
return return
} }
var multi = client.multi() const multi = client.multi()
multi.del('SOME_KEY') multi.del('SOME_KEY')
for (i = 0; i < 100; i++) { for (i = 0; i < 100; i++) {
multi.hset('SOME_KEY', 'SOME_FIELD' + i, buffer) multi.hset('SOME_KEY', `SOME_FIELD${i}`, buffer)
} }
multi.exec(function (err, res) { multi.exec((err, res) => {
if (err) { if (err) {
done(err) done(err)
return return
@@ -86,19 +86,19 @@ describe('The \'multi\' method', function () {
}) })
}) })
describe('pipeline limit', function () { describe('pipeline limit', () => {
it('do not exceed maximum string size', function (done) { it('do not exceed maximum string size', function (done) {
this.timeout(process.platform !== 'win32' ? 10000 : 35000) // Windows tests are horribly slow this.timeout(process.platform !== 'win32' ? 10000 : 35000) // Windows tests are horribly slow
// Triggers a RangeError: Invalid string length if not handled properly // Triggers a RangeError: Invalid string length if not handled properly
client = redis.createClient() client = redis.createClient()
var multi = client.multi() const multi = client.multi()
var i = Math.pow(2, 28) let i = Math.pow(2, 28)
while (i > 0) { while (i > 0) {
i -= 10230 i -= 10230
multi.set('foo' + i, 'bar' + new Array(1024).join('1234567890')) multi.set(`foo${i}`, `bar${new Array(1024).join('1234567890')}`)
} }
client.on('ready', function () { client.on('ready', () => {
multi.exec(function (err, res) { multi.exec((err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res.length, 26241) assert.strictEqual(res.length, 26241)
}) })
@@ -107,67 +107,66 @@ describe('The \'multi\' method', function () {
}) })
}) })
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
describe('when not connected', function () { describe('when not connected', () => {
beforeEach(function (done) { beforeEach((done) => {
var end = helper.callFuncAfter(done, 2) const end = helper.callFuncAfter(done, 2)
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.quit(end) client.quit(end)
}) })
client.once('end', end) client.once('end', end)
}) })
it('reports an error', function (done) { it('reports an error', (done) => {
var multi = client.multi() const multi = client.multi()
var notBuffering = multi.exec(function (err, res) { multi.exec((err, res) => {
assert(err.message.match(/The connection is already closed/)) assert(err.message.match(/The connection is already closed/))
done() done()
}) })
assert.strictEqual(notBuffering, false)
}) })
it('reports an error if promisified', function () { it('reports an error if promisified', () => {
return client.multi().execAsync().catch(function (err) { return client.multi().execAsync().catch((err) => {
assert(err.message.match(/The connection is already closed/)) assert(err.message.match(/The connection is already closed/))
}) })
}) })
}) })
describe('when connected', function () { describe('when connected', () => {
beforeEach(function () { beforeEach(() => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
}) })
describe('monitor and transactions do not work together', function () { describe('monitor and transactions do not work together', () => {
it('results in a execabort', function (done) { it('results in a execabort', (done) => {
// Check that transactions in combination with monitor result in an error // Check that transactions in combination with monitor result in an error
client.monitor(function (e) { client.monitor((e) => {
client.on('error', function (err) { client.on('error', (err) => {
assert.strictEqual(err.code, 'EXECABORT') assert.strictEqual(err.code, 'EXECABORT')
client.end(false) client.end(false)
done() done()
}) })
var multi = client.multi() const multi = client.multi()
multi.set('hello', 'world') multi.set('hello', 'world')
multi.exec() multi.exec()
}) })
}) })
it('results in a execabort #2', function (done) { it('results in a execabort #2', (done) => {
// Check that using monitor with a transactions results in an error // Check that using monitor with a transactions results in an error
client.multi().set('foo', 'bar').monitor().exec(function (err, res) { client.multi().set('foo', 'bar').monitor().exec((err, res) => {
assert.strictEqual(err.code, 'EXECABORT') assert.strictEqual(err.code, 'EXECABORT')
client.end(false) client.end(false)
done() done()
}) })
}) })
it('sanity check', function (done) { it('sanity check', (done) => {
// Remove the listener and add it back again after the error // Remove the listener and add it back again after the error
var mochaListener = helper.removeMochaListener() const mochaListener = helper.removeMochaListener()
process.on('uncaughtException', function () { process.on('uncaughtException', () => {
helper.removeMochaListener() helper.removeMochaListener()
process.on('uncaughtException', mochaListener) process.on('uncaughtException', mochaListener)
done() done()
@@ -177,7 +176,7 @@ describe('The \'multi\' method', function () {
client.sendCommand('multi') client.sendCommand('multi')
client.sendCommand('set', ['foo', 'bar']) client.sendCommand('set', ['foo', 'bar'])
client.sendCommand('get', ['foo']) client.sendCommand('get', ['foo'])
client.sendCommand('exec', function (err, res) { client.sendCommand('exec', (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
// res[0] is going to be the monitor result of set // res[0] is going to be the monitor result of set
// res[1] is going to be the result of the set command // res[1] is going to be the result of the set command
@@ -189,30 +188,30 @@ describe('The \'multi\' method', function () {
}) })
}) })
it('executes a pipelined multi properly in combination with the offline queue', function (done) { it('executes a pipelined multi properly in combination with the offline queue', (done) => {
var multi1 = client.multi() const multi1 = client.multi()
multi1.set('m1', '123') multi1.set('m1', '123')
multi1.get('m1') multi1.get('m1')
multi1.exec(done) multi1.exec(done)
assert.strictEqual(client.offlineQueue.length, 4) assert.strictEqual(client.offlineQueue.length, 4)
}) })
it('executes a pipelined multi properly after a reconnect in combination with the offline queue', function (done) { it('executes a pipelined multi properly after a reconnect in combination with the offline queue', (done) => {
client.once('ready', function () { client.once('ready', () => {
client.stream.destroy() client.stream.destroy()
var called = false let called = false
var multi1 = client.multi() const multi1 = client.multi()
multi1.set('m1', '123') multi1.set('m1', '123')
multi1.get('m1') multi1.get('m1')
multi1.exec(function (err, res) { multi1.exec((err, res) => {
assert(!err) assert(!err)
called = true called = true
}) })
client.once('ready', function () { client.once('ready', () => {
var multi1 = client.multi() const multi1 = client.multi()
multi1.set('m2', '456') multi1.set('m2', '456')
multi1.get('m2') multi1.get('m2')
multi1.exec(function (err, res) { multi1.exec((err, res) => {
assert(called) assert(called)
assert(!err) assert(!err)
assert.strictEqual(res[1], '456') assert.strictEqual(res[1], '456')
@@ -223,35 +222,35 @@ describe('The \'multi\' method', function () {
}) })
}) })
describe('when connection is broken', function () { describe('when connection is broken', () => {
it.skip('return an error even if connection is in broken mode if callback is present', function (done) { it.skip('return an error even if connection is in broken mode if callback is present', (done) => {
client = redis.createClient({ client = redis.createClient({
host: 'somewhere', host: 'somewhere',
port: 6379, port: 6379,
retryStrategy: function () {} retryStrategy () {}
}) })
client.on('error', function (err) { client.on('error', (err) => {
if (/Redis connection in broken state/.test(err.message)) { if (/Redis connection in broken state/.test(err.message)) {
done() done()
} }
}) })
client.multi([['set', 'foo', 'bar'], ['get', 'foo']]).exec(function (err, res) { client.multi([['set', 'foo', 'bar'], ['get', 'foo']]).exec((err, res) => {
// assert(/Redis connection in broken state/.test(err.message)); // assert(/Redis connection in broken state/.test(err.message));
assert.strictEqual(err.errors.length, 2) assert.strictEqual(err.errors.length, 2)
assert.strictEqual(err.errors[0].args.length, 2) assert.strictEqual(err.errors[0].args.length, 2)
}) })
}) })
it.skip('does not emit an error twice if connection is in broken mode with no callback', function (done) { it.skip('does not emit an error twice if connection is in broken mode with no callback', (done) => {
client = redis.createClient({ client = redis.createClient({
host: 'somewhere', host: 'somewhere',
port: 6379, port: 6379,
retryStrategy: function () {} retryStrategy () {}
}) })
client.on('error', function (err) { client.on('error', (err) => {
// Results in multiple done calls if test fails // Results in multiple done calls if test fails
if (/Redis connection in broken state/.test(err.message)) { if (/Redis connection in broken state/.test(err.message)) {
done() done()
@@ -262,40 +261,39 @@ describe('The \'multi\' method', function () {
}) })
}) })
describe('when ready', function () { describe('when ready', () => {
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('ready', function () { client.once('ready', () => {
client.flushdb(function (err) { client.flushdb((err) => {
return done(err) return done(err)
}) })
}) })
}) })
it('returns an empty result array', function (done) { it('returns an empty result array', (done) => {
var multi = client.multi() const multi = client.multi()
var notBuffering = multi.exec(function (err, res) { multi.exec((err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res.length, 0) assert.strictEqual(res.length, 0)
done() done()
}) })
assert.strictEqual(notBuffering, true)
}) })
it('runs normal calls in-between multis', function (done) { it('runs normal calls in-between multis', (done) => {
var multi1 = client.multi() const multi1 = client.multi()
multi1.set('m1', '123') multi1.set('m1', '123')
client.set('m2', '456', done) client.set('m2', '456', done)
}) })
it('runs simultaneous multis with the same client', function (done) { it('runs simultaneous multis with the same client', (done) => {
var end = helper.callFuncAfter(done, 2) const end = helper.callFuncAfter(done, 2)
var multi1 = client.multi() const multi1 = client.multi()
multi1.set('m1', '123') multi1.set('m1', '123')
multi1.get('m1') multi1.get('m1')
var multi2 = client.multi() const multi2 = client.multi()
multi2.set('m2', '456') multi2.set('m2', '456')
multi2.get('m2') multi2.get('m2')
@@ -303,10 +301,10 @@ describe('The \'multi\' method', function () {
multi2.exec(helper.isDeepEqual(['OK', '456'], end)) multi2.exec(helper.isDeepEqual(['OK', '456'], end))
}) })
it('runs simultaneous multis with the same client version 2', function (done) { it('runs simultaneous multis with the same client version 2', (done) => {
var end = helper.callFuncAfter(done, 2) const end = helper.callFuncAfter(done, 2)
var multi2 = client.multi() const multi2 = client.multi()
var multi1 = client.multi() const multi1 = client.multi()
multi2.set('m2', '456') multi2.set('m2', '456')
multi1.set('m1', '123') multi1.set('m1', '123')
@@ -318,43 +316,42 @@ describe('The \'multi\' method', function () {
multi2.exec(helper.isDeepEqual(['OK', '123', 'PONG'], end)) multi2.exec(helper.isDeepEqual(['OK', '123', 'PONG'], end))
}) })
it('roles back a transaction when one command in a sequence of commands fails', function (done) { it('roles back a transaction when one command in a sequence of commands fails', (done) => {
var multi1, multi2
// Provoke an error at queue time // Provoke an error at queue time
multi1 = client.multi() const multi1 = client.multi()
multi1.mset('multifoo', '10', 'multibar', '20', helper.isString('OK')) multi1.mset('multifoo', '10', 'multibar', '20', helper.isString('OK'))
multi1.set('foo2', helper.isError()) multi1.set('foo2', helper.isError())
multi1.incr('multifoo') multi1.incr('multifoo')
multi1.incr('multibar') multi1.incr('multibar')
multi1.exec(function () { multi1.exec(() => {
// Redis 2.6.5+ will abort transactions with errors // Redis 2.6.5+ will abort transactions with errors
// see: http://redis.io/topics/transactions // see: http://redis.io/topics/transactions
var multibarExpected = 1 const multibarExpected = 1
var multifooExpected = 1 const multifooExpected = 1
// Confirm that the previous command, while containing an error, still worked. // Confirm that the previous command, while containing an error, still worked.
multi2 = client.multi() const multi2 = client.multi()
multi2.incr('multibar', helper.isNumber(multibarExpected)) multi2.incr('multibar', helper.isNumber(multibarExpected))
multi2.incr('multifoo', helper.isNumber(multifooExpected)) multi2.incr('multifoo', helper.isNumber(multifooExpected))
multi2.exec(helper.isDeepEqual([multibarExpected, multibarExpected], done)) multi2.exec(helper.isDeepEqual([multibarExpected, multibarExpected], done))
}) })
}) })
it('roles back a transaction when one command in an array of commands fails', function (done) { it('roles back a transaction when one command in an array of commands fails', (done) => {
// test nested multi-bulk replies // test nested multi-bulk replies
client.multi([ client.multi([
['mget', 'multifoo', 'multibar', helper.isDeepEqual([null, null])], ['mget', 'multifoo', 'multibar', helper.isDeepEqual([null, null])],
['set', 'foo2', helper.isError()], ['set', 'foo2', helper.isError()],
['incr', 'multifoo'], ['incr', 'multifoo'],
['incr', 'multibar'] ['incr', 'multibar']
]).exec(function (err, replies) { ]).exec((err, replies) => {
assert.notEqual(err, null) assert.notEqual(err, null)
assert.strictEqual(replies, undefined) assert.strictEqual(replies, undefined)
return done() return done()
}) })
}) })
it('handles multiple operations being applied to a set', function (done) { it('handles multiple operations being applied to a set', (done) => {
client.sadd('some set', 'mem 1') client.sadd('some set', 'mem 1')
client.sadd(['some set', 'mem 2']) client.sadd(['some set', 'mem 2'])
client.sadd('some set', 'mem 3') client.sadd('some set', 'mem 3')
@@ -371,7 +368,7 @@ describe('The \'multi\' method', function () {
['smembers', 'some set'] ['smembers', 'some set']
]) ])
.scard('some set') .scard('some set')
.exec(function (err, res) { .exec((err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res[0].length, 4) assert.strictEqual(res[0].length, 4)
assert.strictEqual(res[1], 1) assert.strictEqual(res[1], 1)
@@ -381,13 +378,13 @@ describe('The \'multi\' method', function () {
}) })
}) })
it('allows multiple operations to be performed using constructor with all kinds of syntax', function (done) { it('allows multiple operations to be performed using constructor with all kinds of syntax', (done) => {
var now = Date.now() const now = Date.now()
var arr = ['multihmset', 'multibar', 'multibaz'] const arr = ['multihmset', 'multibar', 'multibaz']
var arr2 = ['some manner of key', 'otherTypes'] const arr2 = ['some manner of key', 'otherTypes']
var arr3 = [5768, 'multibarx', 'multifoox'] const arr3 = [5768, 'multibarx', 'multifoox']
var arr4 = ['mset', [578, 'multibar'], helper.isString('OK')] const arr4 = ['mset', [578, 'multibar'], helper.isString('OK')]
var called = false let called = false
client.multi([ client.multi([
arr4, arr4,
[['mset', 'multifoo2', 'multibar2', 'multifoo3', 'multibar3'], helper.isString('OK')], [['mset', 'multifoo2', 'multibar2', 'multifoo3', 'multibar3'], helper.isString('OK')],
@@ -401,15 +398,15 @@ describe('The \'multi\' method', function () {
['hmset', 'multihmset', ['multibar', 'multibaz'], helper.isString('OK')] ['hmset', 'multihmset', ['multibar', 'multibaz'], helper.isString('OK')]
]) ])
.hmget(now, 123456789, 'otherTypes') .hmget(now, 123456789, 'otherTypes')
.hmget('key2', arr2, function noop () {}) .hmget('key2', arr2, () => {})
.hmget(['multihmset2', 'some manner of key', 'multibar3']) .hmget(['multihmset2', 'some manner of key', 'multibar3'])
.mget('multifoo2', ['multifoo3', 'multifoo'], function (err, res) { .mget('multifoo2', ['multifoo3', 'multifoo'], (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert(res[0], 'multifoo3') assert(res[0], 'multifoo3')
assert(res[1], 'multifoo') assert(res[1], 'multifoo')
called = true called = true
}) })
.exec(function (err, replies) { .exec((err, replies) => {
assert(called) assert(called)
assert.strictEqual(arr.length, 3) assert.strictEqual(arr.length, 3)
assert.strictEqual(arr2.length, 2) assert.strictEqual(arr2.length, 2)
@@ -427,7 +424,7 @@ describe('The \'multi\' method', function () {
}) })
}) })
it('converts a non string key to a string', function (done) { it('converts a non string key to a string', (done) => {
// TODO: Converting the key might change soon again. // TODO: Converting the key might change soon again.
client.multi().hmset(true, { client.multi().hmset(true, {
test: 123, test: 123,
@@ -435,16 +432,15 @@ describe('The \'multi\' method', function () {
}).exec(done) }).exec(done)
}) })
it('runs a multi without any further commands', function (done) { it('runs a multi without any further commands', (done) => {
var buffering = client.multi().exec(function (err, res) { client.multi().exec((err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res.length, 0) assert.strictEqual(res.length, 0)
done() done()
}) })
assert(typeof buffering === 'boolean')
}) })
it('allows multiple operations to be performed using a chaining API', function (done) { it('allows multiple operations to be performed using a chaining API', (done) => {
client.multi() client.multi()
.mset('some', '10', 'keys', '20') .mset('some', '10', 'keys', '20')
.incr('some') .incr('some')
@@ -453,7 +449,7 @@ describe('The \'multi\' method', function () {
.exec(helper.isDeepEqual(['OK', 11, 21, ['11', '21']], done)) .exec(helper.isDeepEqual(['OK', 11, 21, ['11', '21']], done))
}) })
it('allows multiple commands to work the same as normal to be performed using a chaining API', function (done) { it('allows multiple commands to work the same as normal to be performed using a chaining API', (done) => {
client.multi() client.multi()
.mset(['some', '10', 'keys', '20']) .mset(['some', '10', 'keys', '20'])
.incr('some', helper.isNumber(11)) .incr('some', helper.isNumber(11))
@@ -462,14 +458,14 @@ describe('The \'multi\' method', function () {
.exec(helper.isDeepEqual(['OK', 11, 21, ['11', '21']], done)) .exec(helper.isDeepEqual(['OK', 11, 21, ['11', '21']], done))
}) })
it('allows multiple commands to work the same as normal to be performed using a chaining API promisified', function () { it('allows multiple commands to work the same as normal to be performed using a chaining API promisified', () => {
return client.multi() return client.multi()
.mset(['some', '10', 'keys', '20']) .mset(['some', '10', 'keys', '20'])
.incr('some', helper.isNumber(11)) .incr('some', helper.isNumber(11))
.incr(['keys'], helper.isNumber(21)) .incr(['keys'], helper.isNumber(21))
.mget('some', 'keys') .mget('some', 'keys')
.execAsync() .execAsync()
.then(function (replies) { .then((replies) => {
assert.strictEqual('OK', replies[0]) assert.strictEqual('OK', replies[0])
assert.strictEqual(11, replies[1]) assert.strictEqual(11, replies[1])
assert.strictEqual(21, replies[2]) assert.strictEqual(21, replies[2])
@@ -478,7 +474,7 @@ describe('The \'multi\' method', function () {
}) })
}) })
it('allows an array to be provided indicating multiple operations to perform', function (done) { it('allows an array to be provided indicating multiple operations to perform', (done) => {
// test nested multi-bulk replies with nulls. // test nested multi-bulk replies with nulls.
client.multi([ client.multi([
['mget', ['multifoo', 'some', 'random value', 'keys']], ['mget', ['multifoo', 'some', 'random value', 'keys']],
@@ -486,7 +482,7 @@ describe('The \'multi\' method', function () {
]).exec(helper.isDeepEqual([[null, null, null, null], 1], done)) ]).exec(helper.isDeepEqual([[null, null, null, null], 1], done))
}) })
it('allows multiple operations to be performed on a hash', function (done) { it('allows multiple operations to be performed on a hash', (done) => {
client.multi() client.multi()
.hmset('multihash', 'a', 'foo', 'b', 1) .hmset('multihash', 'a', 'foo', 'b', 1)
.hmset('multihash', { .hmset('multihash', {
@@ -494,7 +490,7 @@ describe('The \'multi\' method', function () {
things: 'here' things: 'here'
}) })
.hgetall('multihash') .hgetall('multihash')
.exec(function (err, replies) { .exec((err, replies) => {
assert.strictEqual(null, err) assert.strictEqual(null, err)
assert.strictEqual('OK', replies[0]) assert.strictEqual('OK', replies[0])
assert.strictEqual(Object.keys(replies[2]).length, 4) assert.strictEqual(Object.keys(replies[2]).length, 4)
@@ -506,8 +502,8 @@ describe('The \'multi\' method', function () {
}) })
}) })
it('reports EXECABORT exceptions when they occur (while queueing)', function (done) { it('reports EXECABORT exceptions when they occur (while queueing)', (done) => {
client.multi().config('bar').set('foo').set('bar').exec(function (err, reply) { client.multi().config('bar').set('foo').set('bar').exec((err, reply) => {
assert.strictEqual(err.code, 'EXECABORT') assert.strictEqual(err.code, 'EXECABORT')
assert.strictEqual(reply, undefined, 'The reply should have been discarded') assert.strictEqual(reply, undefined, 'The reply should have been discarded')
assert(err.message.match(/^EXECABORT/), 'Error message should begin with EXECABORT') assert(err.message.match(/^EXECABORT/), 'Error message should begin with EXECABORT')
@@ -520,8 +516,8 @@ describe('The \'multi\' method', function () {
}) })
}) })
it('reports multiple exceptions when they occur (while EXEC is running)', function (done) { it('reports multiple exceptions when they occur (while EXEC is running)', (done) => {
client.multi().config('bar').debug('foo').eval('return {err=\'this is an error\'}', 0).exec(function (err, reply) { client.multi().config('bar').debug('foo').eval('return {err=\'this is an error\'}', 0).exec((err, reply) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(reply.length, 3) assert.strictEqual(reply.length, 3)
assert.strictEqual(reply[0].code, 'ERR') assert.strictEqual(reply[0].code, 'ERR')
@@ -535,8 +531,8 @@ describe('The \'multi\' method', function () {
}) })
}) })
it('reports multiple exceptions when they occur (while EXEC is running) promisified', function () { it('reports multiple exceptions when they occur (while EXEC is running) promisified', () => {
return client.multi().config('bar').debug('foo').eval('return {err=\'this is an error\'}', 0).execAsync().then(function (reply) { return client.multi().config('bar').debug('foo').eval('return {err=\'this is an error\'}', 0).execAsync().then((reply) => {
assert.strictEqual(reply.length, 3) assert.strictEqual(reply.length, 3)
assert.strictEqual(reply[0].code, 'ERR') assert.strictEqual(reply[0].code, 'ERR')
assert.strictEqual(reply[0].command, 'CONFIG') assert.strictEqual(reply[0].command, 'CONFIG')
@@ -548,11 +544,11 @@ describe('The \'multi\' method', function () {
}) })
}) })
it('reports multiple exceptions when they occur (while EXEC is running) and calls cb', function (done) { it('reports multiple exceptions when they occur (while EXEC is running) and calls cb', (done) => {
var multi = client.multi() const multi = client.multi()
multi.config('bar', helper.isError()) multi.config('bar', helper.isError())
multi.set('foo', 'bar', helper.isString('OK')) multi.set('foo', 'bar', helper.isString('OK'))
multi.debug('foo').exec(function (err, reply) { multi.debug('foo').exec((err, reply) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(reply.length, 3) assert.strictEqual(reply.length, 3)
assert.strictEqual(reply[0].code, 'ERR') assert.strictEqual(reply[0].code, 'ERR')
@@ -563,20 +559,20 @@ describe('The \'multi\' method', function () {
}) })
}) })
it('emits an error if no callback has been provided and execabort error occured', function (done) { it('emits an error if no callback has been provided and execabort error occured', (done) => {
var multi = client.multi() const multi = client.multi()
multi.config('bar') multi.config('bar')
multi.set('foo') multi.set('foo')
multi.exec() multi.exec()
client.on('error', function (err) { client.on('error', (err) => {
assert.strictEqual(err.code, 'EXECABORT') assert.strictEqual(err.code, 'EXECABORT')
done() done()
}) })
}) })
it('should work without any callback', function (done) { it('should work without any callback', (done) => {
var multi = client.multi() const multi = client.multi()
multi.set('baz', 'binary') multi.set('baz', 'binary')
multi.set('foo', 'bar') multi.set('foo', 'bar')
multi.exec() multi.exec()
@@ -584,9 +580,9 @@ describe('The \'multi\' method', function () {
client.get('foo', helper.isString('bar', done)) client.get('foo', helper.isString('bar', done))
}) })
it('should not use a transaction with execAtomic if no command is used', function () { it('should not use a transaction with execAtomic if no command is used', () => {
var multi = client.multi() const multi = client.multi()
var test = false let test = false
multi.execBatch = function () { multi.execBatch = function () {
test = true test = true
} }
@@ -594,9 +590,9 @@ describe('The \'multi\' method', function () {
assert(test) assert(test)
}) })
it('should not use a transaction with execAtomic if only one command is used', function () { it('should not use a transaction with execAtomic if only one command is used', () => {
var multi = client.multi() const multi = client.multi()
var test = false let test = false
multi.execBatch = function () { multi.execBatch = function () {
test = true test = true
} }
@@ -605,9 +601,9 @@ describe('The \'multi\' method', function () {
assert(test) assert(test)
}) })
it('should use transaction with execAtomic and more than one command used', function (done) { it('should use transaction with execAtomic and more than one command used', (done) => {
var multi = client.multi() const multi = client.multi()
var test = false let test = false
multi.execBatch = function () { multi.execBatch = function () {
test = true test = true
} }
@@ -617,9 +613,9 @@ describe('The \'multi\' method', function () {
assert(!test) assert(!test)
}) })
it('do not mutate arguments in the multi constructor', function (done) { it('do not mutate arguments in the multi constructor', (done) => {
var input = [['set', 'foo', 'bar'], ['get', 'foo']] const input = [['set', 'foo', 'bar'], ['get', 'foo']]
client.multi(input).exec(function (err, res) { client.multi(input).exec((err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(input.length, 2) assert.strictEqual(input.length, 2)
assert.strictEqual(input[0].length, 3) assert.strictEqual(input[0].length, 3)
@@ -628,13 +624,13 @@ describe('The \'multi\' method', function () {
}) })
}) })
it('works properly after a reconnect. issue #897', function (done) { it('works properly after a reconnect. issue #897', (done) => {
client.stream.destroy() client.stream.destroy()
client.on('error', function (err) { client.on('error', (err) => {
assert.strictEqual(err.code, 'ECONNREFUSED') assert.strictEqual(err.code, 'ECONNREFUSED')
}) })
client.on('ready', function () { client.on('ready', () => {
client.multi([['set', 'foo', 'bar'], ['get', 'foo']]).exec(function (err, res) { client.multi([['set', 'foo', 'bar'], ['get', 'foo']]).exec((err, res) => {
assert(!err) assert(!err)
assert.strictEqual(res[1], 'bar') assert.strictEqual(res[1], 'bar')
done() done()
@@ -642,10 +638,10 @@ describe('The \'multi\' method', function () {
}) })
}) })
it('emits error once if reconnecting after multi has been executed but not yet returned without callback', function (done) { it('emits error once if reconnecting after multi has been executed but not yet returned without callback', (done) => {
// NOTE: If uncork is called async by postponing it to the next tick, this behavior is going to change. // NOTE: If uncork is called async by postponing it to the next tick, this behavior is going to change.
// The command won't be processed anymore two errors are returned instead of one // The command won't be processed anymore two errors are returned instead of one
client.on('error', function (err) { client.on('error', (err) => {
assert.strictEqual(err.code, 'UNCERTAIN_STATE') assert.strictEqual(err.code, 'UNCERTAIN_STATE')
client.get('foo', helper.isString('bar', done)) client.get('foo', helper.isString('bar', done))
}) })
@@ -656,7 +652,7 @@ describe('The \'multi\' method', function () {
client.stream.destroy() client.stream.destroy()
}) })
it('indivdual commands work properly with multi', function (done) { it('indivdual commands work properly with multi', (done) => {
// Neither of the following work properly in a transactions: // Neither of the following work properly in a transactions:
// (This is due to Redis not returning the reply as expected / resulting in undefined behavior) // (This is due to Redis not returning the reply as expected / resulting in undefined behavior)
// (Likely there are more commands that do not work with a transaction) // (Likely there are more commands that do not work with a transaction)
@@ -675,8 +671,8 @@ describe('The \'multi\' method', function () {
} }
assert.strictEqual(client.selectedDb, undefined) assert.strictEqual(client.selectedDb, undefined)
var multi = client.multi() const multi = client.multi()
multi.select(5, function (err, res) { multi.select(5, (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(client.selectedDb, 5) assert.strictEqual(client.selectedDb, 5)
assert.strictEqual(res, 'OK') assert.strictEqual(res, 'OK')
@@ -684,13 +680,13 @@ describe('The \'multi\' method', function () {
}) })
// multi.client('reply', 'on', helper.isString('OK')); // Redis v.3.2 // multi.client('reply', 'on', helper.isString('OK')); // Redis v.3.2
multi.set('foo', 'bar', helper.isString('OK')) multi.set('foo', 'bar', helper.isString('OK'))
multi.info(function (err, res) { multi.info((err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res.indexOf('# Server\r\nredis_version:'), 0) assert.strictEqual(res.indexOf('# Server\r\nredis_version:'), 0)
assert.deepEqual(client.serverInfo.db5, { avg_ttl: 0, expires: 0, keys: 1 }) assert.deepEqual(client.serverInfo.db5, { avg_ttl: 0, expires: 0, keys: 1 })
}) })
multi.get('foo', helper.isString('bar')) multi.get('foo', helper.isString('bar'))
multi.exec(function (err, res) { multi.exec((err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
res[2] = res[2].substr(0, 10) res[2] = res[2].substr(0, 10)
assert.deepEqual(res, ['OK', 'OK', '# Server\r\n', 'bar']) assert.deepEqual(res, ['OK', 'OK', '# Server\r\n', 'bar'])

View File

@@ -1,26 +1,26 @@
'use strict' 'use strict'
var Buffer = require('safe-buffer').Buffer const Buffer = require('safe-buffer').Buffer
var assert = require('assert') const assert = require('assert')
var fs = require('fs') const fs = require('fs')
var path = require('path') const path = require('path')
var intercept = require('intercept-stdout') const intercept = require('intercept-stdout')
var config = require('./lib/config') const config = require('./lib/config')
var helper = require('./helper') const helper = require('./helper')
var fork = require('child_process').fork const fork = require('child_process').fork
var redis = config.redis const redis = config.redis
var client let client
describe('The nodeRedis client', function () { describe('The nodeRedis client', () => {
it('individual commands sanity check', function (done) { it('individual commands sanity check', (done) => {
// All commands should work the same in multi context or without // All commands should work the same in multi context or without
// Therefor individual commands always have to be handled in both cases // Therefor individual commands always have to be handled in both cases
fs.readFile(path.resolve(__dirname, '../lib/individualCommands.js'), 'utf8', function (err, data) { fs.readFile(path.resolve(__dirname, '../lib/individualCommands.js'), 'utf8', (err, data) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
var clientPrototype = data.match(/(\n| = )RedisClient\.prototype.[a-zA-Z_]+/g) const clientPrototype = data.match(/(\n| = )RedisClient\.prototype.[a-zA-Z_]+/g)
var multiPrototype = data.match(/(\n| = )Multi\.prototype\.[a-zA-Z_]+/g) const multiPrototype = data.match(/(\n| = )Multi\.prototype\.[a-zA-Z_]+/g)
// Check that every entry RedisClient entry has a correspondent Multi entry // Check that every entry RedisClient entry has a correspondent Multi entry
assert.strictEqual(clientPrototype.filter(function (entry) { assert.strictEqual(clientPrototype.filter((entry) => {
return multiPrototype.indexOf(entry.replace('RedisClient', 'Multi')) === -1 return multiPrototype.indexOf(entry.replace('RedisClient', 'Multi')) === -1
}).length, 3) // multi and batch are included too }).length, 3) // multi and batch are included too
assert.strictEqual(clientPrototype.length, multiPrototype.length + 3) assert.strictEqual(clientPrototype.length, multiPrototype.length + 3)
@@ -30,74 +30,74 @@ describe('The nodeRedis client', function () {
}) })
}) })
it('convert minus to underscore in Redis function names', function (done) { it('convert minus to underscore in Redis function names', (done) => {
var names = Object.keys(redis.RedisClient.prototype) const names = Object.keys(redis.RedisClient.prototype)
client = redis.createClient() client = redis.createClient()
for (var i = 0; i < names.length; i++) { for (let i = 0; i < names.length; i++) {
assert(/^([a-zA-Z_][a-zA-Z_0-9]*)?$/.test(client[names[i]].name)) assert(/^([a-zA-Z_][a-zA-Z_0-9]*)?$/.test(client[names[i]].name))
} }
client.quit(done) client.quit(done)
}) })
it('reset the parser while reconnecting (See #1190)', function (done) { it('reset the parser while reconnecting (See #1190)', (done) => {
var client = redis.createClient({ const client = redis.createClient({
retryStrategy: function () { retryStrategy () {
return 5 return 5
} }
}) })
client.once('reconnecting', function () { client.once('reconnecting', () => {
process.nextTick(function () { process.nextTick(() => {
assert.strictEqual(client.replyParser.buffer, null) assert.strictEqual(client.replyParser.buffer, null)
done() done()
}) })
}) })
var partialInput = Buffer.from('$100\r\nabcdef') const partialInput = Buffer.from('$100\r\nabcdef')
client.replyParser.execute(partialInput) client.replyParser.execute(partialInput)
assert.strictEqual(client.replyParser.buffer.inspect(), partialInput.inspect()) assert.strictEqual(client.replyParser.buffer.inspect(), partialInput.inspect())
client.stream.destroy() client.stream.destroy()
}) })
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
describe('when connected', function () { describe('when connected', () => {
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
client.once('connect', function () { client.once('connect', () => {
client.flushdb(done) client.flushdb(done)
}) })
}) })
describe('duplicate', function () { describe('duplicate', () => {
it('check if all options got copied properly', function (done) { it('check if all options got copied properly', (done) => {
client.selectedDb = 2 client.selectedDb = 2
var client2 = client.duplicate() const client2 = client.duplicate()
assert.strictEqual(client.connectionId + 1, client2.connectionId) assert.strictEqual(client.connectionId + 1, client2.connectionId)
assert.strictEqual(client2.selectedDb, 2) assert.strictEqual(client2.selectedDb, 2)
assert(client.connected) assert(client.connected)
assert(!client2.connected) assert(!client2.connected)
for (var elem in client.options) { for (const elem in client.options) {
if (client.options.hasOwnProperty(elem)) { if (client.options.hasOwnProperty(elem)) {
assert.strictEqual(client2.options[elem], client.options[elem]) assert.strictEqual(client2.options[elem], client.options[elem])
} }
} }
client2.on('error', function (err) { client2.on('error', (err) => {
assert.strictEqual(err.message, 'Connection forcefully ended and command aborted. It might have been processed.') assert.strictEqual(err.message, 'Connection forcefully ended and command aborted. It might have been processed.')
assert.strictEqual(err.command, 'SELECT') assert.strictEqual(err.command, 'SELECT')
assert(err instanceof Error) assert(err instanceof Error)
assert.strictEqual(err.name, 'AbortError') assert.strictEqual(err.name, 'AbortError')
}) })
client2.on('ready', function () { client2.on('ready', () => {
client2.end(true) client2.end(true)
done() done()
}) })
}) })
it('check if all new options replaced the old ones', function (done) { it('check if all new options replaced the old ones', (done) => {
var client2 = client.duplicate({ const client2 = client.duplicate({
noReadyCheck: true noReadyCheck: true
}) })
assert(client.connected) assert(client.connected)
@@ -105,56 +105,56 @@ describe('The nodeRedis client', function () {
assert.strictEqual(client.options.noReadyCheck, undefined) assert.strictEqual(client.options.noReadyCheck, undefined)
assert.strictEqual(client2.options.noReadyCheck, true) assert.strictEqual(client2.options.noReadyCheck, true)
assert.notDeepEqual(client.options, client2.options) assert.notDeepEqual(client.options, client2.options)
for (var elem in client.options) { for (const elem in client.options) {
if (client.options.hasOwnProperty(elem)) { if (client.options.hasOwnProperty(elem)) {
if (elem !== 'noReadyCheck') { if (elem !== 'noReadyCheck') {
assert.strictEqual(client2.options[elem], client.options[elem]) assert.strictEqual(client2.options[elem], client.options[elem])
} }
} }
} }
client2.on('ready', function () { client2.on('ready', () => {
client2.end(true) client2.end(true)
done() done()
}) })
}) })
it('works with a callback', function (done) { it('works with a callback', (done) => {
client.duplicate(function (err, client) { client.duplicate((err, client) => {
assert(!err) assert(!err)
assert.strictEqual(client.ready, true) assert.strictEqual(client.ready, true)
client.quit(done) client.quit(done)
}) })
}) })
it('works with a callback and errors out', function (done) { it('works with a callback and errors out', (done) => {
client.duplicate({ client.duplicate({
port: '9999' port: '9999'
}, function (err, client) { }, (err, client) => {
assert.strictEqual(err.code, 'ECONNREFUSED') assert.strictEqual(err.code, 'ECONNREFUSED')
done(client) done(client)
}) })
}) })
it('works with a promises', function () { it('works with a promises', () => {
return client.duplicateAsync().then(function (client) { return client.duplicateAsync().then((client) => {
assert.strictEqual(client.ready, true) assert.strictEqual(client.ready, true)
return client.quitAsync() return client.quitAsync()
}) })
}) })
it('works with a promises and errors', function () { it('works with a promises and errors', () => {
return client.duplicateAsync({ return client.duplicateAsync({
port: 9999 port: 9999
}).catch(function (err) { }).catch((err) => {
assert.strictEqual(err.code, 'ECONNREFUSED') assert.strictEqual(err.code, 'ECONNREFUSED')
}) })
}) })
}) })
describe('big data', function () { describe('big data', () => {
// Check if the fast mode for big strings is working correct // Check if the fast mode for big strings is working correct
it('safe strings that are bigger than 30000 characters', function (done) { it('safe strings that are bigger than 30000 characters', (done) => {
var str = 'foo ಠ_ಠ bar ' let str = 'foo ಠ_ಠ bar '
while (str.length < 111111) { while (str.length < 111111) {
str += str str += str
} }
@@ -162,13 +162,13 @@ describe('The nodeRedis client', function () {
client.get('foo', helper.isString(str, done)) client.get('foo', helper.isString(str, done))
}) })
it('safe strings that are bigger than 30000 characters with multi', function (done) { it('safe strings that are bigger than 30000 characters with multi', (done) => {
var str = 'foo ಠ_ಠ bar ' let str = 'foo ಠ_ಠ bar '
while (str.length < 111111) { while (str.length < 111111) {
str += str str += str
} }
var called = false let called = false
var temp = client.writeBuffers.bind(client) const temp = client.writeBuffers.bind(client)
assert(client.fireStrings) assert(client.fireStrings)
client.writeBuffers = function (data) { client.writeBuffers = function (data) {
called = true called = true
@@ -176,7 +176,7 @@ describe('The nodeRedis client', function () {
assert(!client.fireStrings) assert(!client.fireStrings)
temp(data) temp(data)
} }
client.multi().set('foo', str).get('foo', helper.isString(str)).exec(function (err, res) { client.multi().set('foo', str).get('foo', helper.isString(str)).exec((err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(called, true) assert.strictEqual(called, true)
assert.strictEqual(res[1], str) assert.strictEqual(res[1], str)
@@ -186,11 +186,11 @@ describe('The nodeRedis client', function () {
}) })
}) })
describe('sendCommand', function () { describe('sendCommand', () => {
it('omitting args should be fine', function (done) { it('omitting args should be fine', (done) => {
client.serverInfo = {} client.serverInfo = {}
client.sendCommand('info') client.sendCommand('info')
client.sendCommand('ping', function (err, res) { client.sendCommand('ping', (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res, 'PONG') assert.strictEqual(res, 'PONG')
// Check if the previous info command used the internal individual info command // Check if the previous info command used the internal individual info command
@@ -198,7 +198,7 @@ describe('The nodeRedis client', function () {
client.serverInfo = {} client.serverInfo = {}
}) })
client.sendCommand('info', null, undefined) client.sendCommand('info', null, undefined)
client.sendCommand('ping', null, function (err, res) { client.sendCommand('ping', null, (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res, 'PONG') assert.strictEqual(res, 'PONG')
// Check if the previous info command used the internal individual info command // Check if the previous info command used the internal individual info command
@@ -206,14 +206,14 @@ describe('The nodeRedis client', function () {
client.serverInfo = {} client.serverInfo = {}
}) })
client.sendCommand('info', undefined, undefined) client.sendCommand('info', undefined, undefined)
client.sendCommand('ping', function (err, res) { client.sendCommand('ping', (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res, 'PONG') assert.strictEqual(res, 'PONG')
// Check if the previous info command used the internal individual info command // Check if the previous info command used the internal individual info command
assert.notDeepEqual(client.serverInfo, {}) assert.notDeepEqual(client.serverInfo, {})
client.serverInfo = {} client.serverInfo = {}
}) })
client.sendCommand('info', undefined, function (err, res) { client.sendCommand('info', undefined, (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert(/redis_version/.test(res)) assert(/redis_version/.test(res))
// The individual info command should also be called by using sendCommand // The individual info command should also be called by using sendCommand
@@ -222,7 +222,7 @@ describe('The nodeRedis client', function () {
}) })
}) })
it('using multi with sendCommand should work as individual command instead of using the internal multi', function (done) { it('using multi with sendCommand should work as individual command instead of using the internal multi', (done) => {
// This is necessary to keep backwards compatibility and it is the only way to handle multis as you want in nodeRedis // This is necessary to keep backwards compatibility and it is the only way to handle multis as you want in nodeRedis
client.sendCommand('multi') client.sendCommand('multi')
client.sendCommand('set', ['foo', 'bar'], helper.isString('QUEUED')) client.sendCommand('set', ['foo', 'bar'], helper.isString('QUEUED'))
@@ -232,9 +232,9 @@ describe('The nodeRedis client', function () {
client.exec(helper.isDeepEqual(['OK', 'bar'], done)) client.exec(helper.isDeepEqual(['OK', 'bar'], done))
}) })
it('multi should be handled special', function (done) { it('multi should be handled special', (done) => {
client.sendCommand('multi', undefined, helper.isString('OK')) client.sendCommand('multi', undefined, helper.isString('OK'))
var args = ['test', 'bla'] const args = ['test', 'bla']
client.sendCommand('set', args, helper.isString('QUEUED')) client.sendCommand('set', args, helper.isString('QUEUED'))
assert.deepEqual(args, ['test', 'bla']) // Check args manipulation assert.deepEqual(args, ['test', 'bla']) // Check args manipulation
client.get('test', helper.isString('QUEUED')) client.get('test', helper.isString('QUEUED'))
@@ -242,7 +242,7 @@ describe('The nodeRedis client', function () {
client.exec(helper.isDeepEqual(['OK', 'bla'], done)) client.exec(helper.isDeepEqual(['OK', 'bla'], done))
}) })
it('using another type as cb should throw', function () { it('using another type as cb should throw', () => {
try { try {
client.sendCommand('set', ['test', 'bla'], [true]) client.sendCommand('set', ['test', 'bla'], [true])
throw new Error('failed') throw new Error('failed')
@@ -257,28 +257,28 @@ describe('The nodeRedis client', function () {
} }
}) })
it('command argument has to be of type string', function () { it('command argument has to be of type string', () => {
try { try {
client.sendCommand(true, ['test', 'bla'], function () {}) client.sendCommand(true, ['test', 'bla'], () => {})
throw new Error('failed') throw new Error('failed')
} catch (err) { } catch (err) {
assert.strictEqual(err.message, 'Wrong input type "Boolean" for command name') assert.strictEqual(err.message, 'Wrong input type "Boolean" for command name')
} }
try { try {
client.sendCommand(undefined, ['test', 'bla'], function () {}) client.sendCommand(undefined, ['test', 'bla'], () => {})
throw new Error('failed') throw new Error('failed')
} catch (err) { } catch (err) {
assert.strictEqual(err.message, 'Wrong input type "undefined" for command name') assert.strictEqual(err.message, 'Wrong input type "undefined" for command name')
} }
try { try {
client.sendCommand(null, ['test', 'bla'], function () {}) client.sendCommand(null, ['test', 'bla'], () => {})
throw new Error('failed') throw new Error('failed')
} catch (err) { } catch (err) {
assert.strictEqual(err.message, 'Wrong input type "null" for command name') assert.strictEqual(err.message, 'Wrong input type "null" for command name')
} }
}) })
it('args may only be of type Array or undefined', function () { it('args may only be of type Array or undefined', () => {
try { try {
client.sendCommand('info', 123) client.sendCommand('info', 123)
throw new Error('failed') throw new Error('failed')
@@ -287,18 +287,18 @@ describe('The nodeRedis client', function () {
} }
}) })
it('passing a callback as args and as callback should throw', function () { it('passing a callback as args and as callback should throw', () => {
try { try {
client.sendCommand('info', function a () {}, function b () {}) client.sendCommand('info', () => {}, () => {})
throw new Error('failed') throw new Error('failed')
} catch (err) { } catch (err) {
assert.strictEqual(err.message, 'Wrong input type "Function" for args') assert.strictEqual(err.message, 'Wrong input type "Function" for args')
} }
}) })
it('multi should be handled special', function (done) { it('multi should be handled special', (done) => {
client.sendCommand('multi', undefined, helper.isString('OK')) client.sendCommand('multi', undefined, helper.isString('OK'))
var args = ['test', 'bla'] const args = ['test', 'bla']
client.sendCommand('set', args, helper.isString('QUEUED')) client.sendCommand('set', args, helper.isString('QUEUED'))
assert.deepEqual(args, ['test', 'bla']) // Check args manipulation assert.deepEqual(args, ['test', 'bla']) // Check args manipulation
client.get('test', helper.isString('QUEUED')) client.get('test', helper.isString('QUEUED'))
@@ -306,52 +306,52 @@ describe('The nodeRedis client', function () {
client.exec(helper.isDeepEqual(['OK', 'bla'], done)) client.exec(helper.isDeepEqual(['OK', 'bla'], done))
}) })
it('the args array may contain a arbitrary number of arguments', function (done) { it('the args array may contain a arbitrary number of arguments', (done) => {
client.sendCommand('mset', ['foo', 1, 'bar', 2, 'baz', 3], helper.isString('OK')) client.sendCommand('mset', ['foo', 1, 'bar', 2, 'baz', 3], helper.isString('OK'))
// As the multi command is handled individually by the user he also has to handle the return value // As the multi command is handled individually by the user he also has to handle the return value
client.mget(['foo', 'bar', 'baz'], helper.isDeepEqual(['1', '2', '3'], done)) client.mget(['foo', 'bar', 'baz'], helper.isDeepEqual(['1', '2', '3'], done))
}) })
it('sendCommand with callback as args', function (done) { it('sendCommand with callback as args', (done) => {
client.sendCommand('abcdef', function (err, res) { client.sendCommand('abcdef', (err, res) => {
assert.strictEqual(err.message, 'ERR unknown command \'abcdef\'') assert.strictEqual(err.message, 'ERR unknown command \'abcdef\'')
done() done()
}) })
}) })
}) })
describe('retryUnfulfilledCommands', function () { describe('retryUnfulfilledCommands', () => {
it('should retry all commands instead of returning an error if a command did not yet return after a connection loss', function (done) { it('should retry all commands instead of returning an error if a command did not yet return after a connection loss', (done) => {
var bclient = redis.createClient({ const bclient = redis.createClient({
retryUnfulfilledCommands: true retryUnfulfilledCommands: true
}) })
bclient.blpop('blocking list 2', 5, function (err, value) { bclient.blpop('blocking list 2', 5, (err, value) => {
assert.strictEqual(value[0], 'blocking list 2') assert.strictEqual(value[0], 'blocking list 2')
assert.strictEqual(value[1], 'initial value') assert.strictEqual(value[1], 'initial value')
bclient.end(true) bclient.end(true)
done(err) done(err)
}) })
bclient.once('ready', function () { bclient.once('ready', () => {
setTimeout(function () { setTimeout(() => {
bclient.stream.destroy() bclient.stream.destroy()
client.rpush('blocking list 2', 'initial value', helper.isNumber(1)) client.rpush('blocking list 2', 'initial value', helper.isNumber(1))
}, 100) }, 100)
}) })
}) })
it('should retry all commands even if the offline queue is disabled', function (done) { it('should retry all commands even if the offline queue is disabled', (done) => {
var bclient = redis.createClient({ const bclient = redis.createClient({
enableOfflineQueue: false, enableOfflineQueue: false,
retryUnfulfilledCommands: true retryUnfulfilledCommands: true
}) })
bclient.once('ready', function () { bclient.once('ready', () => {
bclient.blpop('blocking list 2', 5, function (err, value) { bclient.blpop('blocking list 2', 5, (err, value) => {
assert.strictEqual(value[0], 'blocking list 2') assert.strictEqual(value[0], 'blocking list 2')
assert.strictEqual(value[1], 'initial value') assert.strictEqual(value[1], 'initial value')
bclient.end(true) bclient.end(true)
done(err) done(err)
}) })
setTimeout(function () { setTimeout(() => {
bclient.stream.destroy() bclient.stream.destroy()
client.rpush('blocking list 2', 'initial value', helper.isNumber(1)) client.rpush('blocking list 2', 'initial value', helper.isNumber(1))
}, 100) }, 100)
@@ -359,41 +359,41 @@ describe('The nodeRedis client', function () {
}) })
}) })
describe('.end', function () { describe('.end', () => {
it('used without flush / flush set to false', function (done) { it('used without flush / flush set to false', (done) => {
var finished = false let finished = false
var end = helper.callFuncAfter(function () { const end = helper.callFuncAfter(() => {
if (!finished) { if (!finished) {
done(new Error('failed')) done(new Error('failed'))
} }
}, 20) }, 20)
var cb = function (err, res) { const cb = function (err, res) {
assert(/Connection forcefully ended|The connection is already closed./.test(err.message)) assert(/Connection forcefully ended|The connection is already closed./.test(err.message))
assert.strictEqual(err.code, 'NR_CLOSED') assert.strictEqual(err.code, 'NR_CLOSED')
end() end()
} }
for (var i = 0; i < 20; i++) { for (let i = 0; i < 20; i++) {
if (i === 10) { if (i === 10) {
client.end() client.end()
} }
client.set('foo', 'bar', cb) client.set('foo', 'bar', cb)
} }
client.on('warning', function () {}) // Ignore deprecation message client.on('warning', () => {}) // Ignore deprecation message
setTimeout(function () { setTimeout(() => {
finished = true finished = true
done() done()
}, 25) }, 25)
}) })
it('used with flush set to true', function (done) { it('used with flush set to true', (done) => {
var end = helper.callFuncAfter(function () { const end = helper.callFuncAfter(() => {
done() done()
}, 20) }, 20)
var cb = function (err, res) { const cb = function (err, res) {
assert(/Connection forcefully ended|The connection is already closed./.test(err.message)) assert(/Connection forcefully ended|The connection is already closed./.test(err.message))
end() end()
} }
for (var i = 0; i < 20; i++) { for (let i = 0; i < 20; i++) {
if (i === 10) { if (i === 10) {
client.end(true) client.end(true)
client.stream.write('foo') // Trigger an error on the closed stream that we ignore client.stream.write('foo') // Trigger an error on the closed stream that we ignore
@@ -402,14 +402,14 @@ describe('The nodeRedis client', function () {
} }
}) })
it('emits an aggregate error if no callback was present for multiple commands in debugMode', function (done) { it('emits an aggregate error if no callback was present for multiple commands in debugMode', (done) => {
redis.debugMode = true redis.debugMode = true
var unhookIntercept = intercept(function (data) { const unhookIntercept = intercept((data) => {
return '' // Don't print the debug messages return '' // Don't print the debug messages
}) })
client.set('foo', 'bar') client.set('foo', 'bar')
client.set('baz', 'hello world') client.set('baz', 'hello world')
client.on('error', function (err) { client.on('error', (err) => {
assert(err instanceof Error) assert(err instanceof Error)
assert(err instanceof redis.AbortError) assert(err instanceof redis.AbortError)
assert(err instanceof redis.AggregateError) assert(err instanceof redis.AggregateError)
@@ -428,13 +428,13 @@ describe('The nodeRedis client', function () {
redis.debugMode = false redis.debugMode = false
}) })
it('emits an abort error if no callback was present for a single commands', function (done) { it('emits an abort error if no callback was present for a single commands', (done) => {
redis.debugMode = true redis.debugMode = true
var unhookIntercept = intercept(function (data) { const unhookIntercept = intercept((data) => {
return '' // Don't print the debug messages return '' // Don't print the debug messages
}) })
client.set('foo', 'bar') client.set('foo', 'bar')
client.on('error', function (err) { client.on('error', (err) => {
assert(err instanceof Error) assert(err instanceof Error)
assert(err instanceof redis.AbortError) assert(err instanceof redis.AbortError)
assert(!(err instanceof redis.AggregateError)) assert(!(err instanceof redis.AggregateError))
@@ -449,22 +449,22 @@ describe('The nodeRedis client', function () {
redis.debugMode = false redis.debugMode = false
}) })
it('does not emit abort errors if no callback was present while not being in debugMode ', function (done) { it('does not emit abort errors if no callback was present while not being in debugMode ', (done) => {
client.set('foo', 'bar') client.set('foo', 'bar')
client.end(true) client.end(true)
setTimeout(done, 100) setTimeout(done, 100)
}) })
}) })
describe('commands after using .quit should fail', function () { describe('commands after using .quit should fail', () => {
it('return an error in the callback', function (done) { it('return an error in the callback', function (done) {
if (helper.redisProcess().spawnFailed()) this.skip() if (helper.redisProcess().spawnFailed()) this.skip()
// TODO: Investigate why this test is failing hard and killing mocha if using '/tmp/redis.sock'. // TODO: Investigate why this test is failing hard and killing mocha if using '/tmp/redis.sock'.
// Seems like something is wrong with nyc while passing a socket connection to create client! // Seems like something is wrong with nyc while passing a socket connection to create client!
client = redis.createClient() client = redis.createClient()
client.quit(function () { client.quit(() => {
client.get('foo', function (err, res) { client.get('foo', (err, res) => {
assert.strictEqual(err.message, 'Stream connection ended and command aborted. It might have been processed.') assert.strictEqual(err.message, 'Stream connection ended and command aborted. It might have been processed.')
assert.strictEqual(client.offlineQueue.length, 0) assert.strictEqual(client.offlineQueue.length, 0)
done() done()
@@ -476,8 +476,8 @@ describe('The nodeRedis client', function () {
if (helper.redisProcess().spawnFailed()) this.skip() if (helper.redisProcess().spawnFailed()) this.skip()
client.quit() client.quit()
setTimeout(function () { setTimeout(() => {
client.get('foo', function (err, res) { client.get('foo', (err, res) => {
assert.strictEqual(err.message, 'GET can\'t be processed. The connection is already closed.') assert.strictEqual(err.message, 'GET can\'t be processed. The connection is already closed.')
assert.strictEqual(err.command, 'GET') assert.strictEqual(err.command, 'GET')
assert.strictEqual(client.offlineQueue.length, 0) assert.strictEqual(client.offlineQueue.length, 0)
@@ -489,23 +489,23 @@ describe('The nodeRedis client', function () {
it('emit an error', function (done) { it('emit an error', function (done) {
if (helper.redisProcess().spawnFailed()) this.skip() if (helper.redisProcess().spawnFailed()) this.skip()
client.quit() client.quit()
client.on('error', function (err) { client.on('error', (err) => {
assert.strictEqual(err.message, 'SET can\'t be processed. The connection is already closed.') assert.strictEqual(err.message, 'SET can\'t be processed. The connection is already closed.')
assert.strictEqual(err.command, 'SET') assert.strictEqual(err.command, 'SET')
assert.strictEqual(client.offlineQueue.length, 0) assert.strictEqual(client.offlineQueue.length, 0)
done() done()
}) })
setTimeout(function () { setTimeout(() => {
client.set('foo', 'bar') client.set('foo', 'bar')
}, 50) }, 50)
}) })
}) })
describe('when redis closes unexpectedly', function () { describe('when redis closes unexpectedly', () => {
it('reconnects and can retrieve the pre-existing data', function (done) { it('reconnects and can retrieve the pre-existing data', (done) => {
client.on('reconnecting', function onRecon (params) { client.on('reconnecting', function onRecon (params) {
client.on('connect', function onConnect () { client.on('connect', function onConnect () {
var end = helper.callFuncAfter(function () { const end = helper.callFuncAfter(() => {
client.removeListener('connect', onConnect) client.removeListener('connect', onConnect)
client.removeListener('reconnecting', onRecon) client.removeListener('reconnecting', onRecon)
assert.strictEqual(client.serverInfo.db0.keys, 2) assert.strictEqual(client.serverInfo.db0.keys, 2)
@@ -520,7 +520,7 @@ describe('The nodeRedis client', function () {
}) })
client.set('recon 1', 'one') client.set('recon 1', 'one')
client.set('recon 2', 'two', function (err, res) { client.set('recon 2', 'two', (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
// Do not do this in normal programs. This is to simulate the server closing on us. // Do not do this in normal programs. This is to simulate the server closing on us.
// For orderly shutdown in normal programs, do client.quit() // For orderly shutdown in normal programs, do client.quit()
@@ -528,7 +528,7 @@ describe('The nodeRedis client', function () {
}) })
}) })
it('reconnects properly when monitoring', function (done) { it('reconnects properly when monitoring', (done) => {
client.on('reconnecting', function onRecon (params) { client.on('reconnecting', function onRecon (params) {
client.on('ready', function onReady () { client.on('ready', function onReady () {
assert.strictEqual(client.monitoring, true, 'monitoring after reconnect') assert.strictEqual(client.monitoring, true, 'monitoring after reconnect')
@@ -540,10 +540,10 @@ describe('The nodeRedis client', function () {
assert.strictEqual(client.monitoring, false, 'monitoring off at start') assert.strictEqual(client.monitoring, false, 'monitoring off at start')
client.set('recon 1', 'one') client.set('recon 1', 'one')
client.monitor(function (err, res) { client.monitor((err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(client.monitoring, true, 'monitoring on after monitor()') assert.strictEqual(client.monitoring, true, 'monitoring on after monitor()')
client.set('recon 2', 'two', function (err, res) { client.set('recon 2', 'two', (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
// Do not do this in normal programs. This is to simulate the server closing on us. // Do not do this in normal programs. This is to simulate the server closing on us.
// For orderly shutdown in normal programs, do client.quit() // For orderly shutdown in normal programs, do client.quit()
@@ -552,13 +552,13 @@ describe('The nodeRedis client', function () {
}) })
}) })
describe('and it\'s subscribed to a channel', function () { describe('and it\'s subscribed to a channel', () => {
// "Connection in subscriber mode, only subscriber commands may be used" // "Connection in subscriber mode, only subscriber commands may be used"
it('reconnects, unsubscribes, and can retrieve the pre-existing data', function (done) { it('reconnects, unsubscribes, and can retrieve the pre-existing data', (done) => {
client.on('ready', function onConnect () { client.on('ready', () => {
client.unsubscribe(helper.isNotError()) client.unsubscribe(helper.isNotError())
client.on('unsubscribe', function (channel, count) { client.on('unsubscribe', (channel, count) => {
// we should now be out of subscriber mode. // we should now be out of subscriber mode.
assert.strictEqual(channel, 'recon channel') assert.strictEqual(channel, 'recon channel')
assert.strictEqual(count, 0) assert.strictEqual(count, 0)
@@ -567,7 +567,7 @@ describe('The nodeRedis client', function () {
}) })
client.set('recon 1', 'one') client.set('recon 1', 'one')
client.subscribe('recon channel', function (err, res) { client.subscribe('recon channel', (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
// Do not do this in normal programs. This is to simulate the server closing on us. // Do not do this in normal programs. This is to simulate the server closing on us.
// For orderly shutdown in normal programs, do client.quit() // For orderly shutdown in normal programs, do client.quit()
@@ -575,11 +575,11 @@ describe('The nodeRedis client', function () {
}) })
}) })
it('reconnects, unsubscribes, and can retrieve the pre-existing data of a explicit channel', function (done) { it('reconnects, unsubscribes, and can retrieve the pre-existing data of a explicit channel', (done) => {
client.on('ready', function onConnect () { client.on('ready', () => {
client.unsubscribe('recon channel', helper.isNotError()) client.unsubscribe('recon channel', helper.isNotError())
client.on('unsubscribe', function (channel, count) { client.on('unsubscribe', (channel, count) => {
// we should now be out of subscriber mode. // we should now be out of subscriber mode.
assert.strictEqual(channel, 'recon channel') assert.strictEqual(channel, 'recon channel')
assert.strictEqual(count, 0) assert.strictEqual(count, 0)
@@ -588,7 +588,7 @@ describe('The nodeRedis client', function () {
}) })
client.set('recon 1', 'one') client.set('recon 1', 'one')
client.subscribe('recon channel', function (err, res) { client.subscribe('recon channel', (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
// Do not do this in normal programs. This is to simulate the server closing on us. // Do not do this in normal programs. This is to simulate the server closing on us.
// For orderly shutdown in normal programs, do client.quit() // For orderly shutdown in normal programs, do client.quit()
@@ -597,13 +597,13 @@ describe('The nodeRedis client', function () {
}) })
}) })
describe('domain', function () { describe('domain', () => {
it('allows client to be executed from within domain', function (done) { it('allows client to be executed from within domain', (done) => {
// eslint-disable-next-line // eslint-disable-next-line
var domain = require('domain').create() var domain = require('domain').create()
domain.run(function () { domain.run(() => {
client.set('domain', 'value', function (err, res) { client.set('domain', 'value', (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.ok(process.domain) assert.ok(process.domain)
throw new Error('ohhhh noooo') throw new Error('ohhhh noooo')
@@ -611,20 +611,20 @@ describe('The nodeRedis client', function () {
}) })
// this is the expected and desired behavior // this is the expected and desired behavior
domain.on('error', function (err) { domain.on('error', (err) => {
assert.strictEqual(err.message, 'ohhhh noooo') assert.strictEqual(err.message, 'ohhhh noooo')
domain.exit() domain.exit()
done() done()
}) })
}) })
it('keeps the same domain by using the offline queue', function (done) { it('keeps the same domain by using the offline queue', (done) => {
client.end(true) client.end(true)
client = redis.createClient() client = redis.createClient()
// eslint-disable-next-line // eslint-disable-next-line
var testDomain = require('domain').create() var testDomain = require('domain').create()
testDomain.run(function () { testDomain.run(() => {
client.set('FOOBAR', 'def', function () { client.set('FOOBAR', 'def', () => {
assert.strictEqual(process.domain, testDomain) assert.strictEqual(process.domain, testDomain)
done() done()
}) })
@@ -633,17 +633,17 @@ describe('The nodeRedis client', function () {
require('domain').create() require('domain').create()
}) })
it('catches all errors from within the domain', function (done) { it('catches all errors from within the domain', (done) => {
// eslint-disable-next-line // eslint-disable-next-line
var domain = require('domain').create() var domain = require('domain').create()
domain.run(function () { domain.run(() => {
// Trigger an error within the domain // Trigger an error within the domain
client.end(true) client.end(true)
client.set('domain', 'value') client.set('domain', 'value')
}) })
domain.on('error', function (err) { domain.on('error', (err) => {
assert.strictEqual(err.message, 'SET can\'t be processed. The connection is already closed.') assert.strictEqual(err.message, 'SET can\'t be processed. The connection is already closed.')
domain.exit() domain.exit()
done() done()
@@ -652,11 +652,11 @@ describe('The nodeRedis client', function () {
}) })
}) })
describe('utf8', function () { describe('utf8', () => {
it('handles utf-8 keys', function (done) { it('handles utf-8 keys', (done) => {
var utf8Sample = 'ಠ_ಠ' const utf8Sample = 'ಠ_ಠ'
client.set(['utf8test', utf8Sample], helper.isString('OK')) client.set(['utf8test', utf8Sample], helper.isString('OK'))
client.get(['utf8test'], function (err, obj) { client.get(['utf8test'], (err, obj) => {
assert.strictEqual(utf8Sample, obj) assert.strictEqual(utf8Sample, obj)
done(err) done(err)
}) })
@@ -664,18 +664,18 @@ describe('The nodeRedis client', function () {
}) })
}) })
describe('unref', function () { describe('unref', () => {
it('exits subprocess as soon as final command is processed', function (done) { it('exits subprocess as soon as final command is processed', function (done) {
this.timeout(12000) this.timeout(12000)
var args = config.HOST[ip] ? [config.HOST[ip], config.PORT] : [ip] const args = config.HOST[ip] ? [config.HOST[ip], config.PORT] : [ip]
var external = fork('./test/lib/unref.js', args) const external = fork('./test/lib/unref.js', args)
var id = setTimeout(function () { const id = setTimeout(() => {
external.kill() external.kill()
done(new Error('unref subprocess timed out')) done(new Error('unref subprocess timed out'))
}, 8000) }, 8000)
external.on('close', function (code) { external.on('close', (code) => {
clearTimeout(id) clearTimeout(id)
assert.strictEqual(code, 0) assert.strictEqual(code, 0)
done() done()
@@ -683,16 +683,16 @@ describe('The nodeRedis client', function () {
}) })
}) })
describe('execution order / fire query while loading', function () { describe('execution order / fire query while loading', () => {
it('keep execution order for commands that may fire while redis is still loading', function (done) { it('keep execution order for commands that may fire while redis is still loading', (done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
var fired = false let fired = false
client.set('foo', 'bar', function (err, res) { client.set('foo', 'bar', (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(fired, false) assert.strictEqual(fired, false)
done() done()
}) })
client.info(function (err, res) { client.info((err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
fired = true fired = true
}) })
@@ -721,19 +721,19 @@ describe('The nodeRedis client', function () {
// }); // });
}) })
describe('protocol error', function () { describe('protocol error', () => {
it('should gracefully recover and only fail on the already send commands', function (done) { it('should gracefully recover and only fail on the already send commands', (done) => {
client = redis.createClient.apply(null, args) client = redis.createClient.apply(null, args)
var error let error
client.on('error', function (err) { client.on('error', (err) => {
assert.strictEqual(err.message, 'Protocol error, got "a" as reply type byte. Please report this.') assert.strictEqual(err.message, 'Protocol error, got "a" as reply type byte. Please report this.')
assert.strictEqual(err, error) assert.strictEqual(err, error)
assert(err instanceof redis.ParserError) assert(err instanceof redis.ParserError)
// After the hard failure work properly again. The set should have been processed properly too // After the hard failure work properly again. The set should have been processed properly too
client.get('foo', helper.isString('bar', done)) client.get('foo', helper.isString('bar', done))
}) })
client.once('ready', function () { client.once('ready', () => {
client.set('foo', 'bar', function (err, res) { client.set('foo', 'bar', (err, res) => {
assert.strictEqual(err.message, 'Fatal error encountered. Command aborted. It might have been processed.') assert.strictEqual(err.message, 'Fatal error encountered. Command aborted. It might have been processed.')
assert.strictEqual(err.code, 'NR_FATAL') assert.strictEqual(err.code, 'NR_FATAL')
assert(err instanceof redis.AbortError) assert(err instanceof redis.AbortError)
@@ -741,7 +741,7 @@ describe('The nodeRedis client', function () {
}) })
// Make sure we call execute out of the reply // Make sure we call execute out of the reply
// ready is called in a reply // ready is called in a reply
process.nextTick(function () { process.nextTick(() => {
// Fail the set answer. Has no corresponding command obj and will therefore land in the error handler and set // Fail the set answer. Has no corresponding command obj and will therefore land in the error handler and set
client.replyParser.execute(Buffer.from('a*1\r*1\r$1`zasd\r\na')) client.replyParser.execute(Buffer.from('a*1\r*1\r$1`zasd\r\na'))
}) })
@@ -749,22 +749,22 @@ describe('The nodeRedis client', function () {
}) })
}) })
describe('enableOfflineQueue', function () { describe('enableOfflineQueue', () => {
describe('true', function () { describe('true', () => {
it('does not return an error and enqueues operation', function (done) { it('does not return an error and enqueues operation', (done) => {
client = redis.createClient(9999) client = redis.createClient(9999)
var finished = false let finished = false
client.on('error', function (e) { client.on('error', (e) => {
// ignore, b/c expecting a "can't connect" error // ignore, b/c expecting a "can't connect" error
}) })
setTimeout(function () { setTimeout(() => {
client.set('foo', 'bar', function (err, result) { client.set('foo', 'bar', (err, result) => {
if (!finished) done(err) if (!finished) done(err)
assert.strictEqual(err.message, 'Connection forcefully ended and command aborted.') assert.strictEqual(err.message, 'Connection forcefully ended and command aborted.')
}) })
setTimeout(function () { setTimeout(() => {
assert.strictEqual(client.offlineQueue.length, 1) assert.strictEqual(client.offlineQueue.length, 1)
finished = true finished = true
done() done()
@@ -772,17 +772,17 @@ describe('The nodeRedis client', function () {
}, 50) }, 50)
}) })
it.skip('enqueues operation and keep the queue while trying to reconnect', function (done) { it.skip('enqueues operation and keep the queue while trying to reconnect', (done) => {
client = redis.createClient(9999, null, { client = redis.createClient(9999, null, {
retryStrategy: function (options) { retryStrategy (options) {
if (options.attempt < 4) { if (options.attempt < 4) {
return 200 return 200
} }
} }
}) })
var i = 0 let i = 0
client.on('error', function (err) { client.on('error', (err) => {
if (err.code === 'CONNECTION_BROKEN') { if (err.code === 'CONNECTION_BROKEN') {
assert(i, 3) assert(i, 3)
assert.strictEqual(client.offlineQueue.length, 0) assert.strictEqual(client.offlineQueue.length, 0)
@@ -799,7 +799,7 @@ describe('The nodeRedis client', function () {
} }
}) })
client.on('reconnecting', function (params) { client.on('reconnecting', (params) => {
i++ i++
assert.strictEqual(params.attempt, i) assert.strictEqual(params.attempt, i)
assert.strictEqual(params.timesConnected, 0) assert.strictEqual(params.timesConnected, 0)
@@ -810,34 +810,34 @@ describe('The nodeRedis client', function () {
// Should work with either a callback or without // Should work with either a callback or without
client.set('baz', 13) client.set('baz', 13)
client.set('foo', 'bar', function (err, result) { client.set('foo', 'bar', (err, result) => {
assert(i, 3) assert(i, 3)
assert(err) assert(err)
assert.strictEqual(client.offlineQueue.length, 0) assert.strictEqual(client.offlineQueue.length, 0)
}) })
}) })
it('flushes the command queue if connection is lost', function (done) { it('flushes the command queue if connection is lost', (done) => {
client = redis.createClient() client = redis.createClient()
client.once('ready', function () { client.once('ready', () => {
var multi = client.multi() const multi = client.multi()
multi.config('bar') multi.config('bar')
var cb = function (err, reply) { const cb = function (err, reply) {
assert.strictEqual(err.code, 'UNCERTAIN_STATE') assert.strictEqual(err.code, 'UNCERTAIN_STATE')
} }
for (var i = 0; i < 12; i += 3) { for (let i = 0; i < 12; i += 3) {
client.set('foo' + i, 'bar' + i) client.set(`foo${i}`, `bar${i}`)
multi.set('foo' + (i + 1), 'bar' + (i + 1), cb) multi.set(`foo${i + 1}`, `bar${i + 1}`, cb)
multi.set('foo' + (i + 2), 'bar' + (i + 2)) multi.set(`foo${i + 2}`, `bar${i + 2}`)
} }
multi.exec() multi.exec()
assert.strictEqual(client.commandQueue.length, 15) assert.strictEqual(client.commandQueue.length, 15)
helper.killConnection(client) helper.killConnection(client)
}) })
var end = helper.callFuncAfter(done, 3) const end = helper.callFuncAfter(done, 3)
client.on('error', function (err) { client.on('error', (err) => {
if (err.command === 'EXEC') { if (err.command === 'EXEC') {
assert.strictEqual(client.commandQueue.length, 0) assert.strictEqual(client.commandQueue.length, 0)
assert.strictEqual(err.errors.length, 9) assert.strictEqual(err.errors.length, 9)
@@ -860,27 +860,27 @@ describe('The nodeRedis client', function () {
}) })
}) })
describe('false', function () { describe('false', () => {
it('stream not writable', function (done) { it('stream not writable', (done) => {
client = redis.createClient({ client = redis.createClient({
enableOfflineQueue: false enableOfflineQueue: false
}) })
client.on('ready', function () { client.on('ready', () => {
client.stream.destroy() client.stream.destroy()
client.set('foo', 'bar', function (err, res) { client.set('foo', 'bar', (err, res) => {
assert.strictEqual(err.message, 'SET can\'t be processed. Stream not writeable.') assert.strictEqual(err.message, 'SET can\'t be processed. Stream not writeable.')
done() done()
}) })
}) })
}) })
it('emit an error and does not enqueues operation', function (done) { it('emit an error and does not enqueues operation', (done) => {
client = redis.createClient(9999, null, { client = redis.createClient(9999, null, {
enableOfflineQueue: false enableOfflineQueue: false
}) })
var end = helper.callFuncAfter(done, 3) const end = helper.callFuncAfter(done, 3)
client.on('error', function (err) { client.on('error', (err) => {
assert(/offline queue is deactivated|ECONNREFUSED/.test(err.message)) assert(/offline queue is deactivated|ECONNREFUSED/.test(err.message))
assert.strictEqual(client.commandQueue.length, 0) assert.strictEqual(client.commandQueue.length, 0)
end() end()
@@ -888,8 +888,8 @@ describe('The nodeRedis client', function () {
client.set('foo', 'bar') client.set('foo', 'bar')
assert.doesNotThrow(function () { assert.doesNotThrow(() => {
client.set('foo', 'bar', function (err) { client.set('foo', 'bar', (err) => {
// should callback with an error // should callback with an error
assert.ok(err) assert.ok(err)
setTimeout(end, 50) setTimeout(end, 50)
@@ -897,33 +897,33 @@ describe('The nodeRedis client', function () {
}) })
}) })
it('flushes the command queue if connection is lost', function (done) { it('flushes the command queue if connection is lost', (done) => {
client = redis.createClient({ client = redis.createClient({
enableOfflineQueue: false enableOfflineQueue: false
}) })
redis.debugMode = true redis.debugMode = true
var unhookIntercept = intercept(function () { const unhookIntercept = intercept(() => {
return '' return ''
}) })
client.once('ready', function () { client.once('ready', () => {
var multi = client.multi() const multi = client.multi()
multi.config('bar') multi.config('bar')
var cb = function (err, reply) { const cb = function (err, reply) {
assert.strictEqual(err.code, 'UNCERTAIN_STATE') assert.strictEqual(err.code, 'UNCERTAIN_STATE')
} }
for (var i = 0; i < 12; i += 3) { for (let i = 0; i < 12; i += 3) {
client.set('foo' + i, 'bar' + i) client.set(`foo${i}`, `bar${i}`)
multi.set('foo' + (i + 1), 'bar' + (i + 1), cb) multi.set(`foo${i + 1}`, `bar${i + 1}`, cb)
multi.set('foo' + (i + 2), 'bar' + (i + 2)) multi.set(`foo${i + 2}`, `bar${i + 2}`)
} }
multi.exec() multi.exec()
assert.strictEqual(client.commandQueue.length, 15) assert.strictEqual(client.commandQueue.length, 15)
helper.killConnection(client) helper.killConnection(client)
}) })
var end = helper.callFuncAfter(done, 3) const end = helper.callFuncAfter(done, 3)
client.on('error', function (err) { client.on('error', (err) => {
assert.strictEqual(client.commandQueue.length, 0) assert.strictEqual(client.commandQueue.length, 0)
if (err.command === 'EXEC') { if (err.command === 'EXEC') {
assert.strictEqual(err.errors.length, 9) assert.strictEqual(err.errors.length, 9)

View File

@@ -1,34 +1,34 @@
'use strict' 'use strict'
var assert = require('assert') const assert = require('assert')
var config = require('./lib/config') const config = require('./lib/config')
var helper = require('./helper') const helper = require('./helper')
var redis = config.redis const redis = config.redis
describe('prefix key names', function () { describe('prefix key names', () => {
helper.allTests(function (ip, args) { helper.allTests((ip, args) => {
describe('using ' + ip, function () { describe(`using ${ip}`, () => {
var client = null let client = null
beforeEach(function (done) { beforeEach((done) => {
client = redis.createClient({ client = redis.createClient({
prefix: 'test:prefix:' prefix: 'test:prefix:'
}) })
client.on('ready', function () { client.on('ready', () => {
client.flushdb(function (err) { client.flushdb((err) => {
done(err) done(err)
}) })
}) })
}) })
afterEach(function () { afterEach(() => {
client.end(true) client.end(true)
}) })
it('auto prefix set / get', function (done) { it('auto prefix set / get', (done) => {
client.set('key', 'value', helper.isString('OK')) client.set('key', 'value', helper.isString('OK'))
client.get('key', helper.isString('value')) client.get('key', helper.isString('value'))
client.getrange('key', 1, -1, function (err, reply) { client.getrange('key', 1, -1, (err, reply) => {
assert.strictEqual(reply, 'alue') assert.strictEqual(reply, 'alue')
assert.strictEqual(err, null) assert.strictEqual(err, null)
}) })
@@ -36,7 +36,7 @@ describe('prefix key names', function () {
// The key will be prefixed itself // The key will be prefixed itself
client.exists('test:prefix:key', helper.isNumber(0)) client.exists('test:prefix:key', helper.isNumber(0))
client.mset('key2', 'value2', 'key3', 'value3') client.mset('key2', 'value2', 'key3', 'value3')
client.keys('*', function (err, res) { client.keys('*', (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res.length, 3) assert.strictEqual(res.length, 3)
assert(res.indexOf('test:prefix:key') !== -1) assert(res.indexOf('test:prefix:key') !== -1)
@@ -46,11 +46,11 @@ describe('prefix key names', function () {
}) })
}) })
it('auto prefix set / get with .batch', function (done) { it('auto prefix set / get with .batch', (done) => {
var batch = client.batch() const batch = client.batch()
batch.set('key', 'value', helper.isString('OK')) batch.set('key', 'value', helper.isString('OK'))
batch.get('key', helper.isString('value')) batch.get('key', helper.isString('value'))
batch.getrange('key', 1, -1, function (err, reply) { batch.getrange('key', 1, -1, (err, reply) => {
assert.strictEqual(reply, 'alue') assert.strictEqual(reply, 'alue')
assert.strictEqual(err, null) assert.strictEqual(err, null)
}) })
@@ -58,7 +58,7 @@ describe('prefix key names', function () {
// The key will be prefixed itself // The key will be prefixed itself
batch.exists('test:prefix:key', helper.isNumber(0)) batch.exists('test:prefix:key', helper.isNumber(0))
batch.mset('key2', 'value2', 'key3', 'value3') batch.mset('key2', 'value2', 'key3', 'value3')
batch.keys('*', function (err, res) { batch.keys('*', (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res.length, 3) assert.strictEqual(res.length, 3)
assert(res.indexOf('test:prefix:key') !== -1) assert(res.indexOf('test:prefix:key') !== -1)
@@ -68,11 +68,11 @@ describe('prefix key names', function () {
batch.exec(done) batch.exec(done)
}) })
it('auto prefix set / get with .multi', function (done) { it('auto prefix set / get with .multi', (done) => {
var multi = client.multi() const multi = client.multi()
multi.set('key', 'value', helper.isString('OK')) multi.set('key', 'value', helper.isString('OK'))
multi.get('key', helper.isString('value')) multi.get('key', helper.isString('value'))
multi.getrange('key', 1, -1, function (err, reply) { multi.getrange('key', 1, -1, (err, reply) => {
assert.strictEqual(reply, 'alue') assert.strictEqual(reply, 'alue')
assert.strictEqual(err, null) assert.strictEqual(err, null)
}) })
@@ -80,7 +80,7 @@ describe('prefix key names', function () {
// The key will be prefixed itself // The key will be prefixed itself
multi.exists('test:prefix:key', helper.isNumber(0)) multi.exists('test:prefix:key', helper.isNumber(0))
multi.mset('key2', 'value2', 'key3', 'value3') multi.mset('key2', 'value2', 'key3', 'value3')
multi.keys('*', function (err, res) { multi.keys('*', (err, res) => {
assert.strictEqual(err, null) assert.strictEqual(err, null)
assert.strictEqual(res.length, 3) assert.strictEqual(res.length, 3)
assert(res.indexOf('test:prefix:key') !== -1) assert(res.indexOf('test:prefix:key') !== -1)

Some files were not shown because too many files have changed in this diff Show More