All files / lib test-utils.ts

100% Statements 31/31
100% Branches 4/4
100% Functions 8/8
100% Lines 31/31

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 811x 1x     1x 1x 1x   1x   1x 1x 1x     1x   1x 1x             1x           1x             1x 27x 27x     27x   27x 27x   27x 27x         1x   1x     2x 2x                   2x   2x 2x 2x     2x      
import assert from 'assert/strict';
import RedisClient, { RedisClientType } from './client';
import { RedisModules } from './commands';
import { RedisLuaScripts } from './lua-script';
import { spawn } from 'child_process';
import { once } from 'events';
import tcpPortUsed from 'tcp-port-used';
import { RedisSocketOptions } from './socket';
import which from 'which';
 
export enum TestRedisServers {
    OPEN,
    PASSWORD
}
 
export const TEST_REDIS_SERVERS: Partial<Record<TestRedisServers, RedisSocketOptions>> = {};
 
before(() => {
    return Promise.all([
        spawnOpenServer(),
        spawnPasswordServer()
    ]);
});
 
async function spawnOpenServer(): Promise<void> {
    TEST_REDIS_SERVERS[TestRedisServers.OPEN] = {
        port: await spawnRedisServer()
    };
}
 
async function spawnPasswordServer(): Promise<void> {
    TEST_REDIS_SERVERS[TestRedisServers.PASSWORD] = {
        port: await spawnRedisServer(['--requirepass', 'password']),
        username: 'default',
        password: 'password'
    };
}
 
export function itWithClient(type: TestRedisServers, title: string, fn: (client: RedisClientType<RedisModules, RedisLuaScripts>) => Promise<void>) {
    it(title, async () => {
        const client = RedisClient.create({
            socket: TEST_REDIS_SERVERS[type]
        });
        await client.connect();
 
        try {
            await fn(client);
        } finally {
            await client.flushAll();
            await client.disconnect();
        }
    });
}
 
const REDIS_PATH = which.sync('redis-server');
 
let port = 6379;
 
async function spawnRedisServer(args?: Array<string>): Promise<number> {
    const currentPort = port++,
        process = spawn(REDIS_PATH, [
            '--save',
            '',
            '--port',
            currentPort.toString(),
            ...(args ?? [])
        ]);
 
    // TODO: catch process exit
 
    await tcpPortUsed.waitForStatus(currentPort, '127.0.0.1', true, 10, 1000);
 
    after(() => {
        assert.ok(process.kill());
        return once(process, 'close');
    });
 
    return currentPort;
}