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

View File

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

View File

@ -8,7 +8,7 @@ Mustache.escape = function (value) {
const interpolateVars = (request, envVars = {}, collectionVariables = {}) => {
const interpolate = (str) => {
if(!str || !str.length || typeof str !== "string") {
if (!str || !str.length || typeof str !== 'string') {
return str;
}
@ -27,29 +27,27 @@ const interpolateVars = (request, envVars = {}, collectionVariables ={}) => {
request.headers[key] = interpolate(value);
});
if(request.headers["content-type"] === "application/json") {
if(typeof request.data === "object") {
if (request.headers['content-type'] === 'application/json') {
if (typeof request.data === 'object') {
try {
let parsed = JSON.stringify(request.data);
parsed = interpolate(parsed);
request.data = JSON.parse(parsed);
} catch (err) {
}
} catch (err) {}
}
if(typeof request.data === "string") {
if (typeof request.data === 'string') {
if (request.data.length) {
request.data = interpolate(request.data);
}
}
} else if(request.headers["content-type"] === "application/x-www-form-urlencoded") {
if(typeof request.data === "object") {
} else if (request.headers['content-type'] === 'application/x-www-form-urlencoded') {
if (typeof request.data === 'object') {
try {
let parsed = JSON.stringify(request.data);
parsed = interpolate(parsed);
request.data = JSON.parse(parsed);
} catch (err) {
}
} catch (err) {}
}
} else {
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');
if (requestScriptFile && requestScriptFile.length) {
const scriptRuntime = new ScriptRuntime();
await scriptRuntime.runRequestScript(requestScriptFile, request, envVariables, collectionVariables, collectionPath);
await scriptRuntime.runRequestScript(
requestScriptFile,
request,
envVariables,
collectionVariables,
collectionPath
);
}
// interpolate variables inside request
@ -50,10 +56,9 @@ const runSingleRequest = async function (filename, bruJson, collectionPath, coll
const httpsAgentRequestFields = {};
if (insecure) {
httpsAgentRequestFields['rejectUnauthorized'] = false;
}
else {
} else {
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) {
try {
caCrt = fs.readFileSync(cacert);
@ -84,14 +89,28 @@ const runSingleRequest = async function (filename, bruJson, collectionPath, coll
const postResponseVars = get(bruJson, 'request.vars.res');
if (postResponseVars && postResponseVars.length) {
const varsRuntime = new VarsRuntime();
varsRuntime.runPostResponseVars(postResponseVars, request, response, envVariables, collectionVariables, collectionPath);
varsRuntime.runPostResponseVars(
postResponseVars,
request,
response,
envVariables,
collectionVariables,
collectionPath
);
}
// run post response script
const responseScriptFile = get(bruJson, 'request.script.res');
if (responseScriptFile && responseScriptFile.length) {
const scriptRuntime = new ScriptRuntime();
await scriptRuntime.runResponseScript(responseScriptFile, request, response, envVariables, collectionVariables, collectionPath);
await scriptRuntime.runResponseScript(
responseScriptFile,
request,
response,
envVariables,
collectionVariables,
collectionPath
);
}
// run assertions
@ -99,7 +118,14 @@ const runSingleRequest = async function (filename, bruJson, collectionPath, coll
const assertions = get(bruJson, 'request.assertions');
if (assertions && assertions.length) {
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) => {
if (r.status === 'pass') {
@ -116,7 +142,14 @@ const runSingleRequest = async function (filename, bruJson, collectionPath, coll
const testFile = get(bruJson, 'request.tests');
if (testFile && testFile.length) {
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', []);
}
@ -136,20 +169,36 @@ const runSingleRequest = async function (filename, bruJson, collectionPath, coll
};
} catch (err) {
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
const postResponseVars = get(bruJson, 'request.vars.res');
if (postResponseVars && postResponseVars.length) {
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
const responseScriptFile = get(bruJson, 'request.script.res');
if (responseScriptFile && responseScriptFile.length) {
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
@ -157,7 +206,14 @@ const runSingleRequest = async function (filename, bruJson, collectionPath, coll
const assertions = get(bruJson, 'request.assertions');
if (assertions && assertions.length) {
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) => {
if (r.status === 'pass') {
@ -174,7 +230,14 @@ const runSingleRequest = async function (filename, bruJson, collectionPath, coll
const testFile = get(bruJson, 'request.tests');
if (testFile && testFile.length) {
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', []);
}

View File

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

View File

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

View File

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