Skip to content

Commit

Permalink
refactor: migrate tests to TypeScript (#905)
Browse files Browse the repository at this point in the history
  • Loading branch information
luin authored Jun 23, 2019
1 parent afff43c commit 224df78
Show file tree
Hide file tree
Showing 69 changed files with 651 additions and 545 deletions.
8 changes: 0 additions & 8 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,3 @@ deploy:
tags: false
all_branches: true
node: '10'

# when master is merged to release, promote "next" to "latest"
- provider: script
script: npm ci && node bin/promote-next.js
skip_cleanup: true
on:
branch: release
node: '10'
20 changes: 13 additions & 7 deletions benchmarks/single_node.js → benchmarks/single_node.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
'use strict';

var childProcess = require('child_process');
var Redis = require('../');
import {execSync} from 'child_process';
import Redis from '../lib/redis';

console.log('==========================');
console.log('redis: ' + require('../package.json').version);
var os = require('os');
console.log('CPU: ' + os.cpus().length);
console.log('OS: ' + os.platform() + ' ' + os.arch());
console.log('node version: ' + process.version);
console.log('current commit: ' + childProcess.execSync('git rev-parse --short HEAD'));
console.log('current commit: ' + execSync('git rev-parse --short HEAD'));
console.log('==========================');

var redisJD, redisJ;
Expand All @@ -20,8 +18,8 @@ var waitReady = function (next) {
next();
}
}
redisJD = new Redis({ parser: 'javascript', dropBufferSupport: true });
redisJ = new Redis({ parser: 'javascript', dropBufferSupport: false });
redisJD = new Redis({ dropBufferSupport: true });
redisJ = new Redis({ dropBufferSupport: false });
redisJD.on('ready', check);
redisJ.on('ready', check);
};
Expand All @@ -32,16 +30,20 @@ var quit = function () {
};

suite('SET foo bar', function () {
// @ts-ignore
set('mintime', 5000);
// @ts-ignore
set('concurrency', 300);
before(function (start) {
waitReady(start);
});

// @ts-ignore
bench('javascript parser + dropBufferSupport: true', function (next) {
redisJD.set('foo', 'bar', next);
});

// @ts-ignore
bench('javascript parser', function (next) {
redisJ.set('foo', 'bar', next);
});
Expand All @@ -50,7 +52,9 @@ suite('SET foo bar', function () {
});

suite('LRANGE foo 0 99', function () {
// @ts-ignore
set('mintime', 5000);
// @ts-ignore
set('concurrency', 300);
before(function (start) {
var redis = new Redis();
Expand All @@ -64,10 +68,12 @@ suite('LRANGE foo 0 99', function () {
});
});

// @ts-ignore
bench('javascript parser + dropBufferSupport: true', function (next) {
redisJD.lrange('foo', 0, 99, next);
});

// @ts-ignore
bench('javascript parser', function (next) {
redisJ.lrange('foo', 0, 99, next);
});
Expand Down
30 changes: 0 additions & 30 deletions bin/promote-next.js

This file was deleted.

2 changes: 1 addition & 1 deletion lib/cluster/ClusterOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export interface IClusterOptions {
*
* @default (times) => Math.min(100 + times * 2, 2000)
*/
clusterRetryStrategy?: (times: number, reason?: Error) => number | null
clusterRetryStrategy?: (times: number, reason?: Error) => number | void | null

/**
* See Redis class.
Expand Down
2 changes: 1 addition & 1 deletion lib/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ export default class Command implements ICommand {
* If omit, the response will be handled via Promise
* @memberof Command
*/
constructor (public name: string, args: Array<string | Buffer | number> = [], options: ICommandOptions = {}, callback?: CallbackFunction) {
constructor (public name: string, args: Array<string | Buffer | number | Array<string | Buffer | number | any[]>> = [], options: ICommandOptions = {}, callback?: CallbackFunction) {
this.replyEncoding = options.replyEncoding
this.errorStack = options.errorStack

Expand Down
8 changes: 4 additions & 4 deletions lib/connectors/SentinelConnector/SentinelIterator.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import {ISentinelAddress} from './types'

function isSentinelEql (a: ISentinelAddress, b: ISentinelAddress): boolean {
function isSentinelEql (a: Partial<ISentinelAddress>, b: Partial<ISentinelAddress>): boolean {
return ((a.host || '127.0.0.1') === (b.host || '127.0.0.1')) &&
((a.port || 26379) === (b.port || 26379))
}

export default class SentinelIterator {
private cursor: number = 0

constructor (private sentinels: ISentinelAddress[]) {}
constructor (private sentinels: Partial<ISentinelAddress>[]) {}

hasNext (): boolean {
return this.cursor < this.sentinels.length
}

next (): ISentinelAddress | null {
next (): Partial<ISentinelAddress> | null {
return this.hasNext() ? this.sentinels[this.cursor++] : null
}

Expand All @@ -40,4 +40,4 @@ export default class SentinelIterator {
toString (): string {
return `${JSON.stringify(this.sentinels)} @${this.cursor}`
}
}
}
8 changes: 4 additions & 4 deletions lib/connectors/SentinelConnector/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@ interface IAddressFromResponse {

type NodeCallback<T = void> = (err: Error | null, result?: T) => void
type PreferredSlaves =
((slaves: Array<IAddressFromResponse>) => IAddressFromResponse) |
((slaves: Array<IAddressFromResponse>) => IAddressFromResponse | null) |
Array<{port: string, ip: string, prio?: number}> |
{port: string, ip: string, prio?: number}

export interface ISentinelConnectionOptions extends ITcpConnectionOptions {
role: 'master' | 'slave'
name: 'string'
sentinelPassword?: 'string'
sentinels: ISentinelAddress[]
name: string
sentinelPassword?: string
sentinels: Partial<ISentinelAddress>[]
sentinelRetryStrategy?: (retryAttempts: number) => number
preferredSlaves?: PreferredSlaves
connectTimeout?: number
Expand Down
10 changes: 5 additions & 5 deletions lib/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
exports = module.exports = require('./redis').default

export {ReplyError} from 'redis-errors'
exports.Cluster = require('./cluster').default
exports.Command = require('./command').default
exports.ScanStream = require('./ScanStream').default
exports.Pipeline = require('./pipeline').default
export const Cluster = require('./cluster').default
export const Command = require('./command').default
export const ScanStream = require('./ScanStream').default
export const Pipeline = require('./pipeline').default

const PromiseContainer = require('./promiseContainer')
Object.defineProperty(exports, 'Promise', {
Expand All @@ -16,7 +16,7 @@ Object.defineProperty(exports, 'Promise', {
}
})

exports.print = function (err, reply) {
export function print(err: Error | null, reply?: any) {
if (err) {
console.log('Error: ' + err)
} else {
Expand Down
4 changes: 2 additions & 2 deletions lib/redis/RedisOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {ICommanderOptions} from '../commander';
export type ReconnectOnError = (err: Error) => boolean | 1 | 2;

export interface IRedisOptions extends Partial<ISentinelConnectionOptions>, Partial<ICommanderOptions>, Partial<IClusterOptions> {
retryStrategy?: (times: number) => number,
retryStrategy?: (times: number) => number | void | null,
keepAlive?: number,
noDelay?: boolean,
connectionName?: string,
Expand Down Expand Up @@ -60,4 +60,4 @@ export const DEFAULT_REDIS_OPTIONS: IRedisOptions = {
stringNumbers: false,
maxRetriesPerRequest: 20,
maxLoadingRetryTime: 10000
};
};
2 changes: 2 additions & 0 deletions lib/redis/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,12 @@ var debug = Debug('redis')
export default Redis;
function Redis(port: number, host: string, options: IRedisOptions): void
function Redis(path: string, options: IRedisOptions): void
function Redis(port: number, options: IRedisOptions): void
function Redis(port: number, host: string): void
function Redis(options: IRedisOptions): void
function Redis(port: number): void
function Redis(path: string): void
function Redis(): void
function Redis() {
if (!(this instanceof Redis)) {
console.error(new Error('Calling `Redis()` like a function is deprecated. Using `new Redis()` instead.').stack.replace('Error', 'Warning'));
Expand Down
2 changes: 1 addition & 1 deletion lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {TLSSocket} from 'tls'
export type CallbackFunction<T = any> = (err?: NodeJS.ErrnoException | null, result?: T) => void
export type NetStream = Socket | TLSSocket

export type CommandParameter = string | Buffer | number
export type CommandParameter = string | Buffer | number | any[]
export interface ICommand {
name: string
args: CommandParameter[]
Expand Down
8 changes: 4 additions & 4 deletions lib/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export function bufferEqual (a: Buffer, b: Buffer): boolean {
* ```
* @private
*/
export function convertBufferToString (value, encoding) {
export function convertBufferToString (value: any, encoding?: string) {
if (value instanceof Buffer) {
return value.toString(encoding)
}
Expand Down Expand Up @@ -189,9 +189,9 @@ export function convertObjectToArray (obj) {
* [1, '2']
* ```
*/
export function convertMapToArray (map) {
var result = []
var pos = 0
export function convertMapToArray<K, V>(map: Map<K, V>): Array<K | V> {
const result = []
let pos = 0
map.forEach(function (value, key) {
result[pos] = key
result[pos + 1] = value
Expand Down
18 changes: 18 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
"built/"
],
"scripts": {
"test": "NODE_ENV=test mocha",
"test:cov": "NODE_ENV=test node ./node_modules/istanbul/lib/cli.js cover --preserve-comments ./node_modules/mocha/bin/_mocha -- -r ts-node/register -R spec --exit",
"test": "NODE_ENV=test mocha test/**/*.ts",
"test:cov": "NODE_ENV=test node ./node_modules/istanbul/lib/cli.js cover --preserve-comments ./node_modules/mocha/bin/_mocha -- -r ts-node/register -R spec --exit test/**/*.ts",
"build": "rm -rf built && tsc",
"prepublishOnly": "npm run build && npm test",
"bench": "matcha benchmarks/*.js",
Expand Down Expand Up @@ -40,11 +40,14 @@
"devDependencies": {
"@semantic-release/changelog": "^3.0.4",
"@semantic-release/git": "^7.0.12",
"@types/bluebird": "^3.5.27",
"@types/debug": "^4.1.4",
"@types/lodash.defaults": "^4.2.6",
"@types/lodash.flatten": "^4.4.6",
"@types/mocha": "^5.2.7",
"@types/node": "^12.0.2",
"@types/redis-errors": "1.2.0",
"@types/sinon": "^7.0.13",
"bluebird": "^3.5.4",
"chai": "^4.2.0",
"cz-conventional-changelog": "^2.0.0",
Expand Down
11 changes: 7 additions & 4 deletions test/functional/auth.js → test/functional/auth.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
'use strict';
import MockServer from '../helpers/mock_server'
import {expect} from 'chai'
import Redis from '../../lib/redis'
import * as sinon from 'sinon'

describe('auth', function () {
it('should send auth before other commands', function (done) {
var authed = false;
new MockServer(17379, function (argv) {
new MockServer(17379, (argv) => {
if (argv[0] === 'auth' && argv[1] === 'pass') {
authed = true;
} else if (argv[0] === 'get' && argv[1] === 'foo') {
Expand Down Expand Up @@ -50,9 +53,9 @@ describe('auth', function () {
redis.on('error', function () {
errorEmited = true;
});
stub(console, 'warn').callsFake(warn => {
const stub = sinon.stub(console, 'warn').callsFake(warn => {
if (warn.indexOf('but a password was supplied') !== -1) {
console.warn.restore();
stub.restore();
setTimeout(function () {
expect(errorEmited).to.eql(false);
redis.disconnect();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
var calculateSlot = require('cluster-key-slot');
import MockServer from '../../helpers/mock_server'
import calculateSlot from 'cluster-key-slot'
import {expect} from 'chai'
import {Cluster} from '../../../lib';

describe('cluster:ASK', function () {
it('should support ASK', function (done) {
Expand Down Expand Up @@ -34,7 +37,7 @@ describe('cluster:ASK', function () {
}
});

var cluster = new Redis.Cluster([
var cluster = new Cluster([
{ host: '127.0.0.1', port: '30001' }
], { lazyConnect: false });
cluster.get('foo', function () {
Expand Down Expand Up @@ -64,7 +67,7 @@ describe('cluster:ASK', function () {
}
});

var cluster = new Redis.Cluster([
var cluster = new Cluster([
{ host: '127.0.0.1', port: '30002' }
]);
cluster.get('foo', function (err, res) {
Expand Down
Loading

0 comments on commit 224df78

Please sign in to comment.