remove appDataDir and fix tests (#7579)

This commit is contained in:
Jack Kavanagh 2024-06-24 13:21:21 +02:00 committed by GitHub
parent 536fbcb27e
commit b301c633f1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
15 changed files with 78 additions and 223 deletions

View File

@ -7,7 +7,7 @@ module.exports = {
tsconfig: '../../tsconfig.base.json',
},
},
collectCoverage: true,
collectCoverage: false,
coveragePathIgnorePatterns: ['/node_modules/'],
coverageThreshold: {
global: {

View File

@ -8,13 +8,12 @@ A CLI for Insomnia!
Options:
-v, --version output the version number
-w, --workingDir <dir> set working directory
-a, --appDataDir <dir> set the app data directory (deprecated; use --src
instead)
--config <path> path to configuration file
--src <file|dir> set the target source file or directory (git path or
insomnia db path)
--verbose show additional logs while running the command
--src <file|dir> set the app data source
--printOptions print the loaded options
--ci run in CI, disables all prompts
--config <path> path to configuration file containing above options
--printOptions print the loaded options
-h, --help display help for command
Commands:
@ -33,13 +32,12 @@ A CLI for Insomnia!
Options:
-v, --version output the version number
-w, --workingDir <dir> set working directory
-a, --appDataDir <dir> set the app data directory (deprecated; use --src
instead)
--config <path> path to configuration file
--src <file|dir> set the target source file or directory (git path or
insomnia db path)
--verbose show additional logs while running the command
--src <file|dir> set the app data source
--printOptions print the loaded options
--ci run in CI, disables all prompts
--config <path> path to configuration file containing above options
--printOptions print the loaded options
-h, --help display help for command
Commands:
@ -82,13 +80,12 @@ A CLI for Insomnia!
Options:
-v, --version output the version number
-w, --workingDir <dir> set working directory
-a, --appDataDir <dir> set the app data directory (deprecated; use --src
instead)
--config <path> path to configuration file
--src <file|dir> set the target source file or directory (git path or
insomnia db path)
--verbose show additional logs while running the command
--src <file|dir> set the app data source
--printOptions print the loaded options
--ci run in CI, disables all prompts
--config <path> path to configuration file containing above options
--printOptions print the loaded options
-h, --help display help for command
Commands:
@ -107,13 +104,12 @@ A CLI for Insomnia!
Options:
-v, --version output the version number
-w, --workingDir <dir> set working directory
-a, --appDataDir <dir> set the app data directory (deprecated; use --src
instead)
--config <path> path to configuration file
--src <file|dir> set the target source file or directory (git path or
insomnia db path)
--verbose show additional logs while running the command
--src <file|dir> set the app data source
--printOptions print the loaded options
--ci run in CI, disables all prompts
--config <path> path to configuration file containing above options
--printOptions print the loaded options
-h, --help display help for command
Commands:

View File

@ -50,14 +50,6 @@ describe('cli', () => {
});
describe('global options', () => {
it('should throw error if app data dir argument is missing', () => {
expect(() => inso('-a')).toThrowError();
});
it('should throw error if working dir argument is missing', () => {
expect(() => inso('-w')).toThrowError();
});
it.each(['-v', '--version'])('inso %s should print version from package.json', args => {
logger.wrapAll();
expect(() => inso(args)).toThrowError(packageJson.version);
@ -78,10 +70,9 @@ describe('cli', () => {
});
it('should call generateConfig with global options', () => {
inso('lint spec file.yaml -w dir1 -a dir2 --src src --ci');
inso('lint spec file.yaml -w dir1 --src src --ci');
expect(lintSpecification).toHaveBeenCalledWith('file.yaml', {
workingDir: 'dir1',
appDataDir: 'dir2',
src: 'src',
ci: true,
});
@ -120,12 +111,11 @@ describe('cli', () => {
});
it('should call runInsomniaTests with global options', () => {
inso('run test uts_123 -w dir1 -a dir2 --src src --ci');
inso('run test uts_123 -w dir1 --src src --ci');
expect(runInsomniaTests).toHaveBeenCalledWith(
'uts_123',
expect.objectContaining({
workingDir: 'dir1',
appDataDir: 'dir2',
src: 'src',
ci: true,
}),

View File

@ -147,12 +147,11 @@ export const go = (args?: string[], exitOverride?: boolean) => {
// Global options
cmd
.option('-w, --workingDir <dir>', 'set working directory')
.option('-a, --appDataDir <dir>', 'set the app data directory (deprecated; use --src instead)')
.option('--config <path>', 'path to configuration file')
.option('--src <file|dir>', 'set the target source file or directory (git path or insomnia db path)')
.option('--verbose', 'show additional logs while running the command')
.option('--src <file|dir>', 'set the app data source')
.option('--printOptions', 'print the loaded options')
.option('--ci', 'run in CI, disables all prompts');
.option('--ci', 'run in CI, disables all prompts')
.option('--config <path>', 'path to configuration file containing above options')
.option('--printOptions', 'print the loaded options');
// Add commands and sub commands
cmd

View File

@ -23,11 +23,10 @@ function deleteField(obj: any, field: any): void {
export async function exportSpecification(
identifier: string | null | undefined,
{ output, skipAnnotations, workingDir, appDataDir, ci, src }: ExportSpecificationOptions,
{ output, skipAnnotations, workingDir, ci, src }: ExportSpecificationOptions,
) {
const db = await loadDb({
workingDir,
appDataDir,
filterTypes: ['ApiSpec'],
src,
});

View File

@ -18,7 +18,7 @@ describe('lint specification', () => {
jest.restoreAllMocks();
});
it('should return true for linting passed', async () => {
it.only('should return true for linting passed', async () => {
const result = await lintSpecification('spc_46c5a4a40e83445a9bd9d9758b86c16c', {
workingDir: 'src/db/fixtures/git-repo',
});

View File

@ -16,11 +16,10 @@ export type LintSpecificationOptions = GlobalOptions;
export async function lintSpecification(
identifier: string | null | undefined,
{ workingDir, appDataDir, ci, src }: LintSpecificationOptions,
{ workingDir, ci, src }: LintSpecificationOptions,
) {
const db = await loadDb({
workingDir,
appDataDir,
filterTypes: ['ApiSpec'],
src,
});

View File

@ -43,7 +43,7 @@ describe('runInsomniaTests()', () => {
]);
});
it('should forward options to insomnia-testing', async () => {
it.only('should forward options to insomnia-testing', async () => {
const contents = 'generated test contents';
generate.mockReturnValue(contents);

View File

@ -56,10 +56,9 @@ export async function runInsomniaTests(
return false;
}
const { reporter, bail, keepFile, appDataDir, workingDir, env, ci, testNamePattern, disableCertValidation, src } = options;
const { reporter, bail, keepFile, workingDir, env, ci, testNamePattern, disableCertValidation, src } = options;
const db = await loadDb({
workingDir,
appDataDir,
filterTypes: [],
src,
});

View File

@ -7,8 +7,14 @@ import { emptyDb } from '../index';
const gitAdapter: DbAdapter = async (dir, filterTypes) => {
// Confirm if model directories exist
dir = path.join(dir, '.insomnia');
if (!fs.existsSync(path.join(dir, 'Workspace'))) {
if (!dir) {
return null;
}
const workspaceFolder = path.join(dir, '.insomnia', 'Workspace');
try {
await fs.promises.readdir(workspaceFolder);
} catch (error) {
// console.error(`Failed to read "${workspaceFolder}"`, error);
return null;
}
@ -19,8 +25,14 @@ const gitAdapter: DbAdapter = async (dir, filterTypes) => {
fileName: string,
): Promise<void> => {
// Get contents of each file in type dir and insert into data
const contents = await fs.promises.readFile(fileName);
const obj = YAML.parse(contents.toString());
let contents = '';
try {
contents = await fs.promises.readFile(fileName, 'utf8');
} catch (error) {
console.error(`Failed to read "${fileName}"`, error);
return;
}
const obj = YAML.parse(contents);
(db[type] as {}[]).push(obj);
};
@ -28,17 +40,18 @@ const gitAdapter: DbAdapter = async (dir, filterTypes) => {
await Promise.all(
types.map(async t => {
// Get all files in type dir
const typeDir = path.join(dir, t);
if (!fs.existsSync(typeDir)) {
const typeDir = path.join(dir, '.insomnia', t);
let files: string[] = [];
try {
files = await fs.promises.readdir(typeDir);
} catch (error) {
console.error(`Failed to read "${typeDir}"`, error);
return;
}
const files = await fs.promises.readdir(typeDir);
return Promise.all(
// Insert each file from each type
files.map(file =>
readAndInsertDoc(t, path.join(dir, t, file)),
readAndInsertDoc(t, path.join(dir, '.insomnia', t, file)),
),
);
}),

View File

@ -1,136 +0,0 @@
import { beforeAll, beforeEach, describe, expect, it, jest } from '@jest/globals';
import { MockedFunction } from 'jest-mock';
import path from 'path';
import { globalBeforeAll, globalBeforeEach } from '../jest/before';
import { logger } from '../logger';
import _gitAdapter from './adapters/git-adapter';
import _insomniaAdapter from './adapters/insomnia-adapter';
import _neDbAdapter from './adapters/ne-db-adapter';
import { emptyDb, loadDb } from './index';
jest.mock('./adapters/git-adapter');
jest.mock('./adapters/ne-db-adapter');
jest.mock('./adapters/insomnia-adapter');
const gitAdapter = _gitAdapter as MockedFunction<typeof _gitAdapter>;
const neDbAdapter = _neDbAdapter as MockedFunction<typeof _neDbAdapter>;
const insomniaAdapter = _insomniaAdapter as MockedFunction<typeof _insomniaAdapter>;
describe('loadDb()', () => {
beforeAll(() => {
globalBeforeAll();
});
beforeEach(() => {
jest.clearAllMocks();
globalBeforeEach();
});
it('should load database from file if --src is provided', async () => {
insomniaAdapter.mockResolvedValue(emptyDb());
await loadDb({ src: '.' });
expect(logger.__getLogs().debug).toEqual([
`Data store configured from file at \`${path.resolve('.')}\``,
]);
});
it('should default to current directory if working dir not defined', async () => {
gitAdapter.mockResolvedValue(emptyDb());
await loadDb({
workingDir: undefined,
});
expect(logger.__getLogs().debug).toEqual([
`Data store configured from git repository at \`${path.resolve('.')}\``,
]);
expect(gitAdapter).toHaveBeenCalledWith('.', undefined);
expect(neDbAdapter).not.toHaveBeenCalled();
});
it('should load git data from working directory', async () => {
gitAdapter.mockResolvedValue(emptyDb());
await loadDb({
workingDir: 'dir',
filterTypes: ['Environment'],
});
expect(logger.__getLogs().debug).toEqual([
`Data store configured from git repository at \`${path.resolve('dir')}\``,
]);
expect(gitAdapter).toHaveBeenCalledWith('dir', ['Environment']);
expect(neDbAdapter).not.toHaveBeenCalled();
});
it('should load nedb from src', async () => {
gitAdapter.mockResolvedValue(null);
neDbAdapter.mockResolvedValue(emptyDb());
await loadDb({
src: 'dir',
filterTypes: ['Environment'],
});
expect(logger.__getLogs().debug).toEqual([
`Data store configured from app data directory at \`${path.resolve('dir')}\``,
]);
expect(gitAdapter).toHaveBeenCalledWith('dir', ['Environment']);
expect(neDbAdapter).toHaveBeenCalledWith('dir', ['Environment']);
});
it('should load nedb from appDataDir', async () => {
gitAdapter.mockResolvedValue(emptyDb());
neDbAdapter.mockResolvedValue(emptyDb());
await loadDb({
appDataDir: 'dir',
filterTypes: ['Environment'],
});
expect(logger.__getLogs().debug).toEqual([
`Data store configured from app data directory at \`${path.resolve('dir')}\``,
]);
expect(gitAdapter).not.toHaveBeenCalled();
expect(neDbAdapter).toHaveBeenCalledWith('dir', ['Environment']);
});
it('should not load from git if src is defined', async () => {
neDbAdapter.mockResolvedValue(emptyDb());
await loadDb({
src: 'dir',
});
expect(logger.__getLogs().debug).toEqual([
`Data store configured from app data directory at \`${path.resolve('dir')}\``,
]);
expect(gitAdapter).toHaveBeenCalled();
expect(neDbAdapter).toHaveBeenCalled();
});
it('should not load from git if appDataDir is defined', async () => {
neDbAdapter.mockResolvedValue(emptyDb());
await loadDb({
appDataDir: 'dir',
});
expect(logger.__getLogs().debug).toEqual([
`Data store configured from app data directory at \`${path.resolve('dir')}\``,
]);
expect(gitAdapter).not.toHaveBeenCalled();
expect(neDbAdapter).toHaveBeenCalled();
});
it('should load from neDb if not loaded from git', async () => {
gitAdapter.mockResolvedValue(null);
neDbAdapter.mockResolvedValue(emptyDb());
await loadDb(); // Cannot assert the full path because it is application data
expect(logger.__getLogs().debug).toEqual([
expect.stringContaining('Data store configured from app data directory at'),
]);
expect(gitAdapter).toHaveBeenCalled();
expect(neDbAdapter).toHaveBeenCalled();
});
it('should warn and return empty db if nothing loaded from git or nedb', async () => {
gitAdapter.mockResolvedValue(null);
neDbAdapter.mockResolvedValue(null);
const db = await loadDb();
expect(logger.__getLogs().warn).toEqual([
'No git, app data store or Insomnia V4 export file found, re-run `inso` with `--verbose` to see tracing information',
]);
expect(db).toEqual(emptyDb());
});
});

View File

@ -42,43 +42,41 @@ export type DbAdapter = (
interface Options {
workingDir?: string;
appDataDir?: string;
filterTypes?: (keyof Database)[];
src?: string;
}
export const loadDb = async ({
workingDir,
appDataDir,
filterTypes,
src,
}: Options = {}) => {
let db: Database | null = null;
// try load from git
if (!appDataDir) {
const dir = src || workingDir || '.';
db = await gitAdapter(dir, filterTypes);
db && logger.debug(`Data store configured from git repository at \`${path.resolve(dir)}\``);
let userSpecifiedDirectory = '.';
if (workingDir) {
userSpecifiedDirectory = path.resolve(workingDir, src || '');
}
if (!workingDir && src) {
userSpecifiedDirectory = path.resolve('.', src);
}
const fullPath = userSpecifiedDirectory || '.';
// try load from git
db = await gitAdapter(fullPath, filterTypes);
db && logger.debug(`Data store configured from git repository at \`${fullPath}\``);
// try load from file (higher priority)
if (!db && src) {
db = await insomniaAdapter(src, filterTypes);
db && logger.debug(`Data store configured from file at \`${path.resolve(src)}\``);
if (!db) {
db = await insomniaAdapter(fullPath, filterTypes);
db && logger.debug(`Data store configured from file at \`${fullPath}\``);
}
// try load from nedb
if (!db) {
const dir = src || appDataDir || getAppDataDir(getDefaultProductName());
const dir = userSpecifiedDirectory || getAppDataDir(getDefaultProductName());
db = await neDbAdapter(dir, filterTypes);
db && logger.debug(`Data store configured from app data directory at \`${path.resolve(dir)}\``); // Try to load from the Designer data dir, if the Core data directory does not exist
db && logger.debug(`Data store configured from app data directory at \`${dir}\``); // Try to load from the Designer data dir, if the Core data directory does not exist
} // return empty db
appDataDir && logger.warn(
'The option `--appDataDir` has been deprecated and will be removed in future releases. Please use `--src` as an alternative',
);
if (!db) {
logger.warn(
'No git, app data store or Insomnia V4 export file found, re-run `inso` with `--verbose` to see tracing information',

View File

@ -1,5 +1,5 @@
options:
appDataDir: configFile
src: configFile
workingDir: workingDir
ci: true
shouldBeIgnored: this should be ignored because it is not a global option

View File

@ -35,7 +35,7 @@ describe('loadCosmiConfig()', () => {
expect(result).toEqual({
__configFile: {
options: {
appDataDir: 'configFile',
src: 'configFile',
workingDir: 'workingDir',
ci: true,
},
@ -80,27 +80,27 @@ describe('getOptions', () => {
opts: () => ({}),
};
const defaultOptions = {
appDataDir: 'default',
src: 'default',
};
const result = getOptions(commandOptions, defaultOptions);
expect(result).toEqual({
appDataDir: 'default',
src: 'default',
});
});
it('should combine default options with command options, favouring command', () => {
const commandOptions = {
opts: () => ({
appDataDir: 'command',
src: 'command',
}),
};
const defaultOptions = {
appDataDir: 'default',
src: 'default',
anotherDefault: '0',
};
const result = getOptions(commandOptions, defaultOptions);
expect(result).toEqual({
appDataDir: 'command',
src: 'command',
anotherDefault: '0',
});
});
@ -113,19 +113,19 @@ describe('getOptions', () => {
}),
};
const defaultOptions = {
appDataDir: 'default',
src: 'default',
anotherDefault: '0',
};
const result = getOptions(commandOptions, defaultOptions);
expect(result).toEqual({
appDataDir: 'configFile',
src: 'configFile',
workingDir: 'workingDir',
ci: true,
anotherDefault: '0',
config: path.join(fixturesDir, '.insorc.yaml'),
__configFile: {
options: {
appDataDir: 'configFile',
src: 'configFile',
workingDir: 'workingDir',
ci: true,
},
@ -148,12 +148,12 @@ describe('getOptions', () => {
}),
};
const defaultOptions = {
appDataDir: 'default',
src: 'default',
anotherDefault: '0',
};
const result = getOptions(commandOptions, defaultOptions);
expect(result).toEqual({
appDataDir: 'default',
src: 'default',
anotherDefault: '0',
config: configFilePath,
});

View File

@ -11,7 +11,6 @@ interface ConfigFileOptions {
}
export type GlobalOptions = {
appDataDir?: string;
workingDir?: string;
ci?: boolean;
verbose?: boolean;
@ -21,7 +20,6 @@ export type GlobalOptions = {
} & ConfigFileOptions;
export const OptionsSupportedInConfigFile: (keyof GlobalOptions)[] = [
'appDataDir',
'workingDir',
'ci',
'verbose',