test: Test all CLI flags.

This commit is contained in:
Ruben Verborgh 2020-12-01 14:24:10 +01:00
parent e8f0304b40
commit c3b5387efb
3 changed files with 100 additions and 85 deletions

View File

@ -1,4 +1,4 @@
#!/usr/bin/env node #!/usr/bin/env node
import * as Path from 'path'; import * as Path from 'path';
import { runCli } from '../src/init/CliRunner'; import { runCli } from '../src/init/CliRunner';
runCli(Path.join(__dirname, '..')); runCli(Path.join(__dirname, '..'), process.argv);

View File

@ -1,4 +1,4 @@
import * as Path from 'path'; import * as path from 'path';
import type { ReadStream, WriteStream } from 'tty'; import type { ReadStream, WriteStream } from 'tty';
import type { LoaderProperties } from 'componentsjs'; import type { LoaderProperties } from 'componentsjs';
import { Loader } from 'componentsjs'; import { Loader } from 'componentsjs';
@ -23,22 +23,22 @@ export const runCustom = function(
stderr: WriteStream, stderr: WriteStream,
properties: LoaderProperties, properties: LoaderProperties,
): void { ): void {
const { argv } = yargs const { argv } = yargs(args)
.usage('node ./bin/server.js [args]') .usage('node ./bin/server.js [args]')
.options({ .options({
port: { type: 'number', alias: 'p', default: 3000 }, port: { type: 'number', alias: 'p', default: 3000 },
config: { type: 'string', alias: 'c' }, config: { type: 'string', alias: 'c' },
rootFilePath: { type: 'string', alias: 'f' }, rootFilePath: { type: 'string', alias: 'f' },
sparqlEndpoint: { type: 'string', alias: 's' }, sparqlEndpoint: { type: 'string', alias: 's' },
level: { type: 'string', alias: 'l', default: 'info' }, loggingLevel: { type: 'string', alias: 'l', default: 'info' },
}) })
.help(); .help();
(async(): Promise<string> => { (async(): Promise<string> => {
// Load provided or default config file // Load provided or default config file
const configPath = argv.config ? const configPath = argv.config ?
Path.join(process.cwd(), argv.config) : path.join(process.cwd(), argv.config) :
`${__dirname}/../../config/config-default.json`; path.join(__dirname, '/../../config/config-default.json');
// Setup from config file // Setup from config file
const loader = new Loader(properties); const loader = new Loader(properties);
@ -50,7 +50,7 @@ export const runCustom = function(
'urn:solid-server:default:variable:base': `http://localhost:${argv.port}/`, 'urn:solid-server:default:variable:base': `http://localhost:${argv.port}/`,
'urn:solid-server:default:variable:rootFilePath': argv.rootFilePath ?? process.cwd(), 'urn:solid-server:default:variable:rootFilePath': argv.rootFilePath ?? process.cwd(),
'urn:solid-server:default:variable:sparqlEndpoint': argv.sparqlEndpoint, 'urn:solid-server:default:variable:sparqlEndpoint': argv.sparqlEndpoint,
'urn:solid-server:default:variable:loggingLevel': argv.level, 'urn:solid-server:default:variable:loggingLevel': argv.loggingLevel,
}, },
}) as Setup; }) as Setup;
return await setup.setup(); return await setup.setup();
@ -66,7 +66,6 @@ export const runCustom = function(
* Run function for starting the server from the command line * Run function for starting the server from the command line
* @param moduleRootPath - Path to the module's root. * @param moduleRootPath - Path to the module's root.
*/ */
export const runCli = function(moduleRootPath: string): void { export const runCli = function(mainModulePath: string, argv: string[]): void {
const argv = process.argv.slice(2); runCustom(argv, process.stdin, process.stdout, process.stderr, { mainModulePath });
runCustom(argv, process.stdin, process.stdout, process.stderr, { mainModulePath: moduleRootPath });
}; };

View File

@ -1,98 +1,114 @@
import * as Path from 'path'; import * as path from 'path';
import type { Loader } from 'componentsjs'; import type { Loader } from 'componentsjs';
import { runCli } from '../../../src/init/CliRunner'; import { runCli } from '../../../src/init/CliRunner';
import type { Setup } from '../../../src/init/Setup'; import type { Setup } from '../../../src/init/Setup';
let calledInstantiateFromUrl: boolean; const mainModulePath = path.join(__dirname, '..');
let calledRegisterAvailableModuleResources: boolean;
let throwError: boolean;
let outsideResolve: () => void;
let functionToResolve: Promise<unknown>;
const mockSetup = { const mockSetup = {
setup: jest.fn(), setup: jest.fn(async(): Promise<any> => null),
} as unknown as jest.Mocked<Setup>; } as unknown as jest.Mocked<Setup>;
const loader = {
instantiateFromUrl: jest.fn(async(): Promise<any> => mockSetup),
registerAvailableModuleResources: jest.fn(async(): Promise<any> => mockSetup),
} as unknown as jest.Mocked<Loader>;
// Mock the Loader class. // Mock the Loader class.
jest.mock('componentsjs', (): any => ( jest.mock('componentsjs', (): any => ({
// eslint-disable-next-line @typescript-eslint/naming-convention, object-shorthand // eslint-disable-next-line @typescript-eslint/naming-convention
{ Loader: function(): Loader { Loader: jest.fn((): Loader => loader),
return {
instantiateFromUrl(): any {
calledInstantiateFromUrl = true;
if (throwError) {
throw new Error('Error! :o');
}
return mockSetup;
},
registerAvailableModuleResources(): any {
calledRegisterAvailableModuleResources = true;
},
} as unknown as Loader;
} }
));
jest.mock('yargs', (): any => ({
usage(): any {
return this;
},
options(): any {
return this;
},
help(): any {
// Return once with and once without values so that both branches are tested.
if (throwError) {
return {
argv: { config: 'value', rootFilePath: 'root' },
};
}
return {
argv: { },
};
},
})); }));
describe('CliRunner', (): void => { describe('CliRunner', (): void => {
beforeAll(async(): Promise<void> => { afterEach((): void => {
mockSetup.setup.mockImplementation(async(): Promise<any> => { jest.clearAllMocks();
// The info method will be called when all other code has been executed, so end the waiting function.
outsideResolve();
});
}); });
beforeEach(async(): Promise<void> => { it('starts the server with default settings.', async(): Promise<void> => {
calledInstantiateFromUrl = false; runCli(mainModulePath, [ 'node', 'script' ]);
calledRegisterAvailableModuleResources = false; await mockSetup.setup();
throwError = false;
// Initialize a function that will be resolved as soon as all necessary but asynchronous calls are completed. expect(loader.instantiateFromUrl).toHaveBeenCalledTimes(1);
functionToResolve = new Promise((resolve): any => { expect(loader.instantiateFromUrl).toHaveBeenCalledWith(
outsideResolve = resolve; 'urn:solid-server:default',
}); path.join(__dirname, '/../../../config/config-default.json'),
}); undefined,
{
it('Runs function for starting the server from the command line.', async(): Promise<void> => { variables: {
runCli(Path.join(__dirname, '..')); 'urn:solid-server:default:variable:port': 3000,
'urn:solid-server:default:variable:base': `http://localhost:3000/`,
await functionToResolve; 'urn:solid-server:default:variable:rootFilePath': process.cwd(),
'urn:solid-server:default:variable:sparqlEndpoint': undefined,
expect(calledInstantiateFromUrl).toBeTruthy(); 'urn:solid-server:default:variable:loggingLevel': 'info',
expect(calledRegisterAvailableModuleResources).toBeTruthy(); },
},
);
expect(loader.registerAvailableModuleResources).toHaveBeenCalledTimes(1);
expect(loader.registerAvailableModuleResources).toHaveBeenCalledWith();
expect(mockSetup.setup).toHaveBeenCalledTimes(1); expect(mockSetup.setup).toHaveBeenCalledTimes(1);
expect(mockSetup.setup).toHaveBeenCalledWith();
}); });
it('Writes to stderr when an exception occurs.', async(): Promise<void> => { it('accepts abbreviated flags.', async(): Promise<void> => {
const mockStderr = jest.spyOn(process.stderr, 'write').mockImplementation((): any => { runCli(mainModulePath, [ 'node', 'script',
// This method will be called when an error has occurred, so end the waiting function. '-p', '4000',
outsideResolve(); '-c', 'myconfig.json',
}); '-f', '/root',
throwError = true; '-s', 'http://localhost:5000/sparql',
'-l', 'debug',
]);
await mockSetup.setup();
runCli(Path.join(__dirname, '..')); expect(loader.instantiateFromUrl).toHaveBeenCalledWith(
'urn:solid-server:default',
path.join(process.cwd(), 'myconfig.json'),
undefined,
{
variables: {
'urn:solid-server:default:variable:port': 4000,
'urn:solid-server:default:variable:base': `http://localhost:4000/`,
'urn:solid-server:default:variable:rootFilePath': '/root',
'urn:solid-server:default:variable:sparqlEndpoint': 'http://localhost:5000/sparql',
'urn:solid-server:default:variable:loggingLevel': 'debug',
},
},
);
});
await functionToResolve; it('accepts full flags.', async(): Promise<void> => {
runCli(mainModulePath, [ 'node', 'script',
'--port', '4000',
'--config', 'myconfig.json',
'--rootFilePath', '/root',
'--sparqlEndpoint', 'http://localhost:5000/sparql',
'--loggingLevel', 'debug',
]);
await mockSetup.setup();
expect(mockStderr).toHaveBeenCalledTimes(1); expect(loader.instantiateFromUrl).toHaveBeenCalledWith(
mockStderr.mockRestore(); 'urn:solid-server:default',
path.join(process.cwd(), 'myconfig.json'),
undefined,
{
variables: {
'urn:solid-server:default:variable:port': 4000,
'urn:solid-server:default:variable:base': `http://localhost:4000/`,
'urn:solid-server:default:variable:rootFilePath': '/root',
'urn:solid-server:default:variable:sparqlEndpoint': 'http://localhost:5000/sparql',
'urn:solid-server:default:variable:loggingLevel': 'debug',
},
},
);
});
it('writes to stderr when an error occurs.', async(): Promise<void> => {
jest.spyOn(process.stderr, 'write');
loader.instantiateFromUrl.mockRejectedValueOnce(new Error('Fatal'));
runCli(mainModulePath, [ 'node', 'script' ]);
await new Promise((resolve): any => setImmediate(resolve));
expect(process.stderr.write).toHaveBeenCalledTimes(1);
expect(process.stderr.write).toHaveBeenCalledWith('Error: Fatal\n');
}); });
}); });