chore(#197): ran prettier on packages/bruno-cli

This commit is contained in:
Anoop M D 2023-09-22 00:34:11 +05:30
parent 1c4c5cc0c0
commit ae692dde06
7 changed files with 202 additions and 157 deletions

View File

@ -33,7 +33,7 @@ const printRunSummary = (assertionResults, testResults) => {
} }
testSummary += `, ${totalAssertions} total`; testSummary += `, ${totalAssertions} total`;
console.log("\n" + chalk.bold(assertSummary)); console.log('\n' + chalk.bold(assertSummary));
console.log(chalk.bold(testSummary)); console.log(chalk.bold(testSummary));
return { return {
@ -43,7 +43,7 @@ const printRunSummary = (assertionResults, testResults) => {
totalTests, totalTests,
passedTests, passedTests,
failedTests failedTests
} };
}; };
const getBruFilesRecursively = (dir) => { const getBruFilesRecursively = (dir) => {
@ -64,10 +64,11 @@ const getBruFilesRecursively = (dir) => {
const stats = fs.lstatSync(filePath); const stats = fs.lstatSync(filePath);
// todo: we might need a ignore config inside bruno.json // todo: we might need a ignore config inside bruno.json
if (stats.isDirectory() && if (
stats.isDirectory() &&
filePath !== environmentsPath && filePath !== environmentsPath &&
!filePath.startsWith(".git") && !filePath.startsWith('.git') &&
!filePath.startsWith("node_modules") !filePath.startsWith('node_modules')
) { ) {
traverse(filePath); traverse(filePath);
} }
@ -119,7 +120,7 @@ const builder = async (yargs) => {
}) })
.option('env', { .option('env', {
describe: 'Environment variables', describe: 'Environment variables',
type: 'string', type: 'string'
}) })
.option('insecure', { .option('insecure', {
type: 'boolean', type: 'boolean',
@ -128,18 +129,12 @@ const builder = async (yargs) => {
.example('$0 run request.bru', 'Run a request') .example('$0 run request.bru', 'Run a request')
.example('$0 run request.bru --env local', 'Run a request with the environment set to local') .example('$0 run request.bru --env local', 'Run a request with the environment set to local')
.example('$0 run folder', 'Run all requests in a folder') .example('$0 run folder', 'Run all requests in a folder')
.example('$0 run folder -r', 'Run all requests in a folder recursively') .example('$0 run folder -r', 'Run all requests in a folder recursively');
}; };
const handler = async function (argv) { const handler = async function (argv) {
try { try {
let { let { filename, cacert, env, insecure, r: recursive } = argv;
filename,
cacert,
env,
insecure,
r: recursive
} = argv;
const collectionPath = process.cwd(); const collectionPath = process.cwd();
// todo // todo
@ -159,7 +154,7 @@ const handler = async function (argv) {
return; return;
} }
} else { } else {
filename = "./"; filename = './';
recursive = true; recursive = true;
} }
@ -182,18 +177,16 @@ const handler = async function (argv) {
const options = getOptions(); const options = getOptions();
if (insecure) { if (insecure) {
options['insecure'] = true options['insecure'] = true;
} }
if (cacert && cacert.length) { if (cacert && cacert.length) {
if (insecure) { if (insecure) {
console.error(chalk.red(`Ignoring the cacert option since insecure connections are enabled`)); console.error(chalk.red(`Ignoring the cacert option since insecure connections are enabled`));
} } else {
else {
const pathExists = await exists(cacert); const pathExists = await exists(cacert);
if (pathExists) { if (pathExists) {
options['cacert'] = cacert options['cacert'] = cacert;
} } else {
else {
console.error(chalk.red(`Cacert File ${cacert} does not exist`)); console.error(chalk.red(`Cacert File ${cacert} does not exist`));
} }
} }
@ -207,10 +200,7 @@ const handler = async function (argv) {
const result = await runSingleRequest(filename, bruJson, collectionPath, collectionVariables, envVars); const result = await runSingleRequest(filename, bruJson, collectionPath, collectionVariables, envVars);
if (result) { if (result) {
const { const { assertionResults, testResults } = result;
assertionResults,
testResults
} = result;
const summary = printRunSummary(assertionResults, testResults); const summary = printRunSummary(assertionResults, testResults);
console.log(chalk.dim(chalk.grey('Done.'))); console.log(chalk.dim(chalk.grey('Done.')));
@ -232,7 +222,7 @@ const handler = async function (argv) {
const bruFiles = files.filter((file) => file.endsWith('.bru')); const bruFiles = files.filter((file) => file.endsWith('.bru'));
for (const bruFile of bruFiles) { for (const bruFile of bruFiles) {
const bruFilepath = path.join(filename, bruFile) const bruFilepath = path.join(filename, bruFile);
const bruContent = fs.readFileSync(bruFilepath, 'utf8'); const bruContent = fs.readFileSync(bruFilepath, 'utf8');
const bruJson = bruToJson(bruContent); const bruJson = bruToJson(bruContent);
bruJsons.push({ bruJsons.push({
@ -257,17 +247,11 @@ const handler = async function (argv) {
let testResults = []; let testResults = [];
for (const iter of bruJsons) { for (const iter of bruJsons) {
const { const { bruFilepath, bruJson } = iter;
bruFilepath,
bruJson
} = iter;
const result = await runSingleRequest(bruFilepath, bruJson, collectionPath, collectionVariables, envVars); const result = await runSingleRequest(bruFilepath, bruJson, collectionPath, collectionVariables, envVars);
if (result) { if (result) {
const { const { assertionResults: _assertionResults, testResults: _testResults } = result;
assertionResults: _assertionResults,
testResults: _testResults
} = result;
assertionResults = assertionResults.concat(_assertionResults); assertionResults = assertionResults.concat(_assertionResults);
testResults = testResults.concat(_testResults); testResults = testResults.concat(_testResults);
@ -282,7 +266,7 @@ const handler = async function (argv) {
} }
} }
} catch (err) { } catch (err) {
console.log("Something went wrong"); console.log('Something went wrong');
console.error(chalk.red(err.message)); console.error(chalk.red(err.message));
process.exit(1); process.exit(1);
} }

View File

@ -5,7 +5,7 @@ const { CLI_EPILOGUE, CLI_VERSION } = require('./constants');
const printBanner = () => { const printBanner = () => {
console.log(chalk.yellow(`Bru CLI ${CLI_VERSION}`)); console.log(chalk.yellow(`Bru CLI ${CLI_VERSION}`));
} };
const run = async () => { const run = async () => {
const argLength = process.argv.length; const argLength = process.argv.length;

View File

@ -8,7 +8,7 @@ Mustache.escape = function (value) {
const interpolateVars = (request, envVars = {}, collectionVariables = {}) => { const interpolateVars = (request, envVars = {}, collectionVariables = {}) => {
const interpolate = (str) => { const interpolate = (str) => {
if(!str || !str.length || typeof str !== "string") { if (!str || !str.length || typeof str !== 'string') {
return str; return str;
} }
@ -27,29 +27,27 @@ const interpolateVars = (request, envVars = {}, collectionVariables ={}) => {
request.headers[key] = interpolate(value); request.headers[key] = interpolate(value);
}); });
if(request.headers["content-type"] === "application/json") { if (request.headers['content-type'] === 'application/json') {
if(typeof request.data === "object") { if (typeof request.data === 'object') {
try { try {
let parsed = JSON.stringify(request.data); let parsed = JSON.stringify(request.data);
parsed = interpolate(parsed); parsed = interpolate(parsed);
request.data = JSON.parse(parsed); request.data = JSON.parse(parsed);
} catch (err) { } catch (err) {}
}
} }
if(typeof request.data === "string") { if (typeof request.data === 'string') {
if (request.data.length) { if (request.data.length) {
request.data = interpolate(request.data); request.data = interpolate(request.data);
} }
} }
} else if(request.headers["content-type"] === "application/x-www-form-urlencoded") { } else if (request.headers['content-type'] === 'application/x-www-form-urlencoded') {
if(typeof request.data === "object") { if (typeof request.data === 'object') {
try { try {
let parsed = JSON.stringify(request.data); let parsed = JSON.stringify(request.data);
parsed = interpolate(parsed); parsed = interpolate(parsed);
request.data = JSON.parse(parsed); request.data = JSON.parse(parsed);
} catch (err) { } catch (err) {}
}
} }
} else { } else {
request.data = interpolate(request.data); request.data = interpolate(request.data);

View File

@ -39,7 +39,13 @@ const runSingleRequest = async function (filename, bruJson, collectionPath, coll
const requestScriptFile = get(bruJson, 'request.script.req'); const requestScriptFile = get(bruJson, 'request.script.req');
if (requestScriptFile && requestScriptFile.length) { if (requestScriptFile && requestScriptFile.length) {
const scriptRuntime = new ScriptRuntime(); const scriptRuntime = new ScriptRuntime();
await scriptRuntime.runRequestScript(requestScriptFile, request, envVariables, collectionVariables, collectionPath); await scriptRuntime.runRequestScript(
requestScriptFile,
request,
envVariables,
collectionVariables,
collectionPath
);
} }
// interpolate variables inside request // interpolate variables inside request
@ -50,10 +56,9 @@ const runSingleRequest = async function (filename, bruJson, collectionPath, coll
const httpsAgentRequestFields = {}; const httpsAgentRequestFields = {};
if (insecure) { if (insecure) {
httpsAgentRequestFields['rejectUnauthorized'] = false; httpsAgentRequestFields['rejectUnauthorized'] = false;
} } else {
else {
const cacertArray = [options['cacert'], process.env.SSL_CERT_FILE, process.env.NODE_EXTRA_CA_CERTS]; const cacertArray = [options['cacert'], process.env.SSL_CERT_FILE, process.env.NODE_EXTRA_CA_CERTS];
const cacert = cacertArray.find(el => el); const cacert = cacertArray.find((el) => el);
if (cacert && cacert.length > 1) { if (cacert && cacert.length > 1) {
try { try {
caCrt = fs.readFileSync(cacert); caCrt = fs.readFileSync(cacert);
@ -84,14 +89,28 @@ const runSingleRequest = async function (filename, bruJson, collectionPath, coll
const postResponseVars = get(bruJson, 'request.vars.res'); const postResponseVars = get(bruJson, 'request.vars.res');
if (postResponseVars && postResponseVars.length) { if (postResponseVars && postResponseVars.length) {
const varsRuntime = new VarsRuntime(); const varsRuntime = new VarsRuntime();
varsRuntime.runPostResponseVars(postResponseVars, request, response, envVariables, collectionVariables, collectionPath); varsRuntime.runPostResponseVars(
postResponseVars,
request,
response,
envVariables,
collectionVariables,
collectionPath
);
} }
// run post response script // run post response script
const responseScriptFile = get(bruJson, 'request.script.res'); const responseScriptFile = get(bruJson, 'request.script.res');
if (responseScriptFile && responseScriptFile.length) { if (responseScriptFile && responseScriptFile.length) {
const scriptRuntime = new ScriptRuntime(); const scriptRuntime = new ScriptRuntime();
await scriptRuntime.runResponseScript(responseScriptFile, request, response, envVariables, collectionVariables, collectionPath); await scriptRuntime.runResponseScript(
responseScriptFile,
request,
response,
envVariables,
collectionVariables,
collectionPath
);
} }
// run assertions // run assertions
@ -99,7 +118,14 @@ const runSingleRequest = async function (filename, bruJson, collectionPath, coll
const assertions = get(bruJson, 'request.assertions'); const assertions = get(bruJson, 'request.assertions');
if (assertions && assertions.length) { if (assertions && assertions.length) {
const assertRuntime = new AssertRuntime(); const assertRuntime = new AssertRuntime();
assertionResults = assertRuntime.runAssertions(assertions, request, response, envVariables, collectionVariables, collectionPath); assertionResults = assertRuntime.runAssertions(
assertions,
request,
response,
envVariables,
collectionVariables,
collectionPath
);
each(assertionResults, (r) => { each(assertionResults, (r) => {
if (r.status === 'pass') { if (r.status === 'pass') {
@ -116,7 +142,14 @@ const runSingleRequest = async function (filename, bruJson, collectionPath, coll
const testFile = get(bruJson, 'request.tests'); const testFile = get(bruJson, 'request.tests');
if (testFile && testFile.length) { if (testFile && testFile.length) {
const testRuntime = new TestRuntime(); const testRuntime = new TestRuntime();
const result = testRuntime.runTests(testFile, request, response, envVariables, collectionVariables, collectionPath); const result = testRuntime.runTests(
testFile,
request,
response,
envVariables,
collectionVariables,
collectionPath
);
testResults = get(result, 'results', []); testResults = get(result, 'results', []);
} }
@ -136,20 +169,36 @@ const runSingleRequest = async function (filename, bruJson, collectionPath, coll
}; };
} catch (err) { } catch (err) {
if (err && err.response) { if (err && err.response) {
console.log(chalk.green(stripExtension(filename)) + chalk.dim(` (${err.response.status} ${err.response.statusText})`)); console.log(
chalk.green(stripExtension(filename)) + chalk.dim(` (${err.response.status} ${err.response.statusText})`)
);
// run post-response vars // run post-response vars
const postResponseVars = get(bruJson, 'request.vars.res'); const postResponseVars = get(bruJson, 'request.vars.res');
if (postResponseVars && postResponseVars.length) { if (postResponseVars && postResponseVars.length) {
const varsRuntime = new VarsRuntime(); const varsRuntime = new VarsRuntime();
varsRuntime.runPostResponseVars(postResponseVars, request, err.response, envVariables, collectionVariables, collectionPath); varsRuntime.runPostResponseVars(
postResponseVars,
request,
err.response,
envVariables,
collectionVariables,
collectionPath
);
} }
// run post response script // run post response script
const responseScriptFile = get(bruJson, 'request.script.res'); const responseScriptFile = get(bruJson, 'request.script.res');
if (responseScriptFile && responseScriptFile.length) { if (responseScriptFile && responseScriptFile.length) {
const scriptRuntime = new ScriptRuntime(); const scriptRuntime = new ScriptRuntime();
await scriptRuntime.runResponseScript(responseScriptFile, request, err.response, envVariables, collectionVariables, collectionPath); await scriptRuntime.runResponseScript(
responseScriptFile,
request,
err.response,
envVariables,
collectionVariables,
collectionPath
);
} }
// run assertions // run assertions
@ -157,7 +206,14 @@ const runSingleRequest = async function (filename, bruJson, collectionPath, coll
const assertions = get(bruJson, 'request.assertions'); const assertions = get(bruJson, 'request.assertions');
if (assertions && assertions.length) { if (assertions && assertions.length) {
const assertRuntime = new AssertRuntime(); const assertRuntime = new AssertRuntime();
assertionResults = assertRuntime.runAssertions(assertions, request, err.response, envVariables, collectionVariables, collectionPath); assertionResults = assertRuntime.runAssertions(
assertions,
request,
err.response,
envVariables,
collectionVariables,
collectionPath
);
each(assertionResults, (r) => { each(assertionResults, (r) => {
if (r.status === 'pass') { if (r.status === 'pass') {
@ -174,7 +230,14 @@ const runSingleRequest = async function (filename, bruJson, collectionPath, coll
const testFile = get(bruJson, 'request.tests'); const testFile = get(bruJson, 'request.tests');
if (testFile && testFile.length) { if (testFile && testFile.length) {
const testRuntime = new TestRuntime(); const testRuntime = new TestRuntime();
const result = testRuntime.runTests(testFile, request, err.response, envVariables, collectionVariables, collectionPath); const result = testRuntime.runTests(
testFile,
request,
err.response,
envVariables,
collectionVariables,
collectionPath
);
testResults = get(result, 'results', []); testResults = get(result, 'results', []);
} }

View File

@ -20,35 +20,35 @@ const bruToJson = (bru) => {
try { try {
const json = bruToJsonV2(bru); const json = bruToJsonV2(bru);
let requestType = _.get(json, "meta.type"); let requestType = _.get(json, 'meta.type');
if(requestType === "http") { if (requestType === 'http') {
requestType = "http-request" requestType = 'http-request';
} else if(requestType === "graphql") { } else if (requestType === 'graphql') {
requestType = "graphql-request"; requestType = 'graphql-request';
} else { } else {
requestType = "http"; requestType = 'http';
} }
const sequence = _.get(json, "meta.seq") const sequence = _.get(json, 'meta.seq');
const transformedJson = { const transformedJson = {
"type": requestType, type: requestType,
"name": _.get(json, "meta.name"), name: _.get(json, 'meta.name'),
"seq": !isNaN(sequence) ? Number(sequence) : 1, seq: !isNaN(sequence) ? Number(sequence) : 1,
"request": { request: {
"method": _.upperCase(_.get(json, "http.method")), method: _.upperCase(_.get(json, 'http.method')),
"url": _.get(json, "http.url"), url: _.get(json, 'http.url'),
"params": _.get(json, "query", []), params: _.get(json, 'query', []),
"headers": _.get(json, "headers", []), headers: _.get(json, 'headers', []),
"body": _.get(json, "body", {}), body: _.get(json, 'body', {}),
"vars": _.get(json, "vars", []), vars: _.get(json, 'vars', []),
"assertions": _.get(json, "assertions", []), assertions: _.get(json, 'assertions', []),
"script": _.get(json, "script", ""), script: _.get(json, 'script', ''),
"tests": _.get(json, "tests", "") tests: _.get(json, 'tests', '')
} }
}; };
transformedJson.request.body.mode = _.get(json, "http.body", "none"); transformedJson.request.body.mode = _.get(json, 'http.body', 'none');
return transformedJson; return transformedJson;
} catch (err) { } catch (err) {
@ -83,7 +83,7 @@ const getEnvVars = (environment = {}) => {
const options = {}; const options = {};
const getOptions = () => { const getOptions = () => {
return options; return options;
} };
module.exports = { module.exports = {
bruToJson, bruToJson,

View File

@ -12,7 +12,7 @@ const rpad = (str, width) => {
paddedStr = paddedStr + ' '; paddedStr = paddedStr + ' ';
} }
return paddedStr; return paddedStr;
} };
module.exports = { module.exports = {
lpad, lpad,

View File

@ -2,7 +2,7 @@ const path = require('path');
const fs = require('fs-extra'); const fs = require('fs-extra');
const fsPromises = require('fs/promises'); const fsPromises = require('fs/promises');
const exists = async p => { const exists = async (p) => {
try { try {
await fsPromises.access(p); await fsPromises.access(p);
return true; return true;
@ -11,7 +11,7 @@ const exists = async p => {
} }
}; };
const isSymbolicLink = filepath => { const isSymbolicLink = (filepath) => {
try { try {
return fs.existsSync(filepath) && fs.lstatSync(filepath).isSymbolicLink(); return fs.existsSync(filepath) && fs.lstatSync(filepath).isSymbolicLink();
} catch (_) { } catch (_) {
@ -19,7 +19,7 @@ const isSymbolicLink = filepath => {
} }
}; };
const isFile = filepath => { const isFile = (filepath) => {
try { try {
return fs.existsSync(filepath) && fs.lstatSync(filepath).isFile(); return fs.existsSync(filepath) && fs.lstatSync(filepath).isFile();
} catch (_) { } catch (_) {
@ -27,7 +27,7 @@ const isFile = filepath => {
} }
}; };
const isDirectory = dirPath => { const isDirectory = (dirPath) => {
try { try {
return fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory(); return fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory();
} catch (_) { } catch (_) {
@ -35,14 +35,14 @@ const isDirectory = dirPath => {
} }
}; };
const normalizeAndResolvePath = pathname => { const normalizeAndResolvePath = (pathname) => {
if (isSymbolicLink(pathname)) { if (isSymbolicLink(pathname)) {
const absPath = path.dirname(pathname); const absPath = path.dirname(pathname);
const targetPath = path.resolve(absPath, fs.readlinkSync(pathname)); const targetPath = path.resolve(absPath, fs.readlinkSync(pathname));
if (isFile(targetPath) || isDirectory(targetPath)) { if (isFile(targetPath) || isDirectory(targetPath)) {
return path.resolve(targetPath); return path.resolve(targetPath);
} }
console.error(`Cannot resolve link target "${pathname}" (${targetPath}).`) console.error(`Cannot resolve link target "${pathname}" (${targetPath}).`);
return ''; return '';
} }
return path.resolve(pathname); return path.resolve(pathname);
@ -51,22 +51,22 @@ const normalizeAndResolvePath = pathname => {
const writeFile = async (pathname, content) => { const writeFile = async (pathname, content) => {
try { try {
fs.writeFileSync(pathname, content, { fs.writeFileSync(pathname, content, {
encoding: "utf8" encoding: 'utf8'
}); });
} catch (err) { } catch (err) {
return Promise.reject(err); return Promise.reject(err);
} }
}; };
const hasJsonExtension = filename => { const hasJsonExtension = (filename) => {
if (!filename || typeof filename !== 'string') return false if (!filename || typeof filename !== 'string') return false;
return ['json'].some(ext => filename.toLowerCase().endsWith(`.${ext}`)) return ['json'].some((ext) => filename.toLowerCase().endsWith(`.${ext}`));
} };
const hasBruExtension = filename => { const hasBruExtension = (filename) => {
if (!filename || typeof filename !== 'string') return false if (!filename || typeof filename !== 'string') return false;
return ['bru'].some(ext => filename.toLowerCase().endsWith(`.${ext}`)) return ['bru'].some((ext) => filename.toLowerCase().endsWith(`.${ext}`));
} };
const createDirectory = async (dir) => { const createDirectory = async (dir) => {
if (!dir) { if (!dir) {
@ -93,15 +93,15 @@ const searchForFiles = (dir, extension) => {
} }
} }
return results; return results;
} };
const searchForBruFiles = (dir) => { const searchForBruFiles = (dir) => {
return searchForFiles(dir, '.bru'); return searchForFiles(dir, '.bru');
}; };
const stripExtension = (filename = '') => { const stripExtension = (filename = '') => {
return filename.replace(/\.[^/.]+$/, ""); return filename.replace(/\.[^/.]+$/, '');
} };
const getSubDirectories = (dir) => { const getSubDirectories = (dir) => {
try { try {