diff --git a/package-lock.json b/package-lock.json index c6856f98d..4d0871eed 100644 --- a/package-lock.json +++ b/package-lock.json @@ -24287,10 +24287,30 @@ "name": "@usebruno/schema", "version": "0.7.0", "license": "MIT", + "dependencies": { + "nanoid": "3.3.8" + }, "peerDependencies": { "yup": "^0.32.11" } }, + "packages/bruno-schema/node_modules/nanoid": { + "version": "3.3.8", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.8.tgz", + "integrity": "sha512-WNLf5Sd8oZxOm+TzppcYk8gVOgP+l58xNy58D0nbUnOxOWRWvlcCV4kUF7ltmI6PsrLl/BgKEyS4mqsGChFN0w==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, "packages/bruno-tests": { "name": "@usebruno/tests", "version": "0.0.1", diff --git a/packages/bruno-app/src/components/CodeEditor/index.js b/packages/bruno-app/src/components/CodeEditor/index.js index aa0238ef0..168a3b02b 100644 --- a/packages/bruno-app/src/components/CodeEditor/index.js +++ b/packages/bruno-app/src/components/CodeEditor/index.js @@ -76,7 +76,11 @@ if (!SERVER_RENDERED) { 'bru.getRequestVar(key)', 'bru.sleep(ms)', 'bru.getGlobalEnvVar(key)', - 'bru.setGlobalEnvVar(key, value)' + 'bru.setGlobalEnvVar(key, value)', + 'bru.runner', + 'bru.runner.setNextRequest(requestName)', + 'bru.runner.skipRequest()', + 'bru.runner.stopExecution()' ]; CodeMirror.registerHelper('hint', 'brunoJS', (editor, options) => { const cursor = editor.getCursor(); @@ -98,7 +102,7 @@ if (!SERVER_RENDERED) { if (curWordBru) { hintWords.forEach((h) => { if (h.includes('.') == curWordBru.includes('.') && h.startsWith(curWordBru)) { - result.list.push(curWordBru.includes('.') ? h.split('.')[1] : h); + result.list.push(curWordBru.includes('.') ? h.split('.')?.at(-1) : h); } }); result.list?.sort(); diff --git a/packages/bruno-app/src/components/GlobalEnvironments/EnvironmentSelector/index.js b/packages/bruno-app/src/components/GlobalEnvironments/EnvironmentSelector/index.js index 869978572..5bf55809c 100644 --- a/packages/bruno-app/src/components/GlobalEnvironments/EnvironmentSelector/index.js +++ b/packages/bruno-app/src/components/GlobalEnvironments/EnvironmentSelector/index.js @@ -23,7 +23,7 @@ const EnvironmentSelector = () => { { - activeEnvironment ?
{activeEnvironment?.name}
: null + activeEnvironment ?
{activeEnvironment?.name}
: null }
diff --git a/packages/bruno-app/src/components/GlobalEnvironments/EnvironmentSettings/EnvironmentList/StyledWrapper.js b/packages/bruno-app/src/components/GlobalEnvironments/EnvironmentSettings/EnvironmentList/StyledWrapper.js index 330ae082c..dd9761532 100644 --- a/packages/bruno-app/src/components/GlobalEnvironments/EnvironmentSettings/EnvironmentList/StyledWrapper.js +++ b/packages/bruno-app/src/components/GlobalEnvironments/EnvironmentSettings/EnvironmentList/StyledWrapper.js @@ -23,6 +23,10 @@ const StyledWrapper = styled.div` padding: 8px 10px; border-left: solid 2px transparent; text-decoration: none; + max-width: 200px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; &:hover { text-decoration: none; diff --git a/packages/bruno-app/src/components/GlobalEnvironments/EnvironmentSettings/EnvironmentList/index.js b/packages/bruno-app/src/components/GlobalEnvironments/EnvironmentSettings/EnvironmentList/index.js index ebd953a0d..d04edd838 100644 --- a/packages/bruno-app/src/components/GlobalEnvironments/EnvironmentSettings/EnvironmentList/index.js +++ b/packages/bruno-app/src/components/GlobalEnvironments/EnvironmentSettings/EnvironmentList/index.js @@ -8,6 +8,7 @@ import ConfirmSwitchEnv from './ConfirmSwitchEnv'; import ManageSecrets from 'components/Environments/EnvironmentSettings/ManageSecrets/index'; import ImportEnvironment from '../ImportEnvironment'; import { isEqual } from 'lodash'; +import ToolHint from 'components/ToolHint/index'; const EnvironmentList = ({ environments, activeEnvironmentUid, selectedEnvironment, setSelectedEnvironment, isModified, setIsModified }) => { const [openCreateModal, setOpenCreateModal] = useState(false); @@ -112,13 +113,15 @@ const EnvironmentList = ({ environments, activeEnvironmentUid, selectedEnvironme {environments && environments.length && environments.map((env) => ( -
handleEnvironmentClick(env)} // Use handleEnvironmentClick to handle clicks - > - {env.name} -
+ +
handleEnvironmentClick(env)} // Use handleEnvironmentClick to handle click + > + {env.name} +
+
))}
handleCreateEnvClick()}> + Create diff --git a/packages/bruno-app/src/components/ResponsePane/ResponseSave/index.js b/packages/bruno-app/src/components/ResponsePane/ResponseSave/index.js index 7c183b0a6..dae5bad4d 100644 --- a/packages/bruno-app/src/components/ResponsePane/ResponseSave/index.js +++ b/packages/bruno-app/src/components/ResponsePane/ResponseSave/index.js @@ -11,7 +11,7 @@ const ResponseSave = ({ item }) => { const saveResponseToFile = () => { return new Promise((resolve, reject) => { ipcRenderer - .invoke('renderer:save-response-to-file', response, item.requestSent.url) + .invoke('renderer:save-response-to-file', response, item?.requestSent?.url) .then(resolve) .catch((err) => { toast.error(get(err, 'error.message') || 'Something went wrong!'); diff --git a/packages/bruno-app/src/components/ResponsePane/Timeline/index.js b/packages/bruno-app/src/components/ResponsePane/Timeline/index.js index 925b4b77b..9aafb41bb 100644 --- a/packages/bruno-app/src/components/ResponsePane/Timeline/index.js +++ b/packages/bruno-app/src/components/ResponsePane/Timeline/index.js @@ -43,7 +43,7 @@ const Timeline = ({ request, response }) => {
-          {'<'} {response.status} {response.statusText}
+          {'<'} {response.status} - {response.statusText}
         
{responseHeaders.map((h) => { diff --git a/packages/bruno-app/src/components/RunnerResults/index.jsx b/packages/bruno-app/src/components/RunnerResults/index.jsx index 4b0b68cba..f7c1e4d9c 100644 --- a/packages/bruno-app/src/components/RunnerResults/index.jsx +++ b/packages/bruno-app/src/components/RunnerResults/index.jsx @@ -59,7 +59,7 @@ export default function RunnerResults({ collection }) { pathname: info.pathname, relativePath: getRelativePath(collection.pathname, info.pathname) }; - if (newItem.status !== 'error') { + if (newItem.status !== 'error' && newItem.status !== 'skipped') { if (newItem.testResults) { const failed = newItem.testResults.filter((result) => result.status === 'fail'); newItem.testStatus = failed.length ? 'fail' : 'pass'; @@ -163,29 +163,35 @@ export default function RunnerResults({ collection }) {
Total Requests: {items.length}, Passed: {passedRequests.length}, Failed: {failedRequests.length}
+ {runnerInfo?.statusText ? +
+ {runnerInfo?.statusText} +
+ : null} {items.map((item) => { return (
- {item.status !== 'error' && item.testStatus === 'pass' ? ( + {item.status !== 'error' && item.testStatus === 'pass' && item.status !== 'skipped' ? ( ) : ( )} {item.relativePath} - {item.status !== 'error' && item.status !== 'completed' ? ( + {item.status !== 'error' && item.status !== 'skipped' && item.status !== 'completed' ? ( ) : item.responseReceived?.status ? ( setSelectedItem(item)}> - ({item.responseReceived?.status} - {item.responseReceived?.statusText}) + {item.responseReceived?.status} + -  + {item.responseReceived?.statusText} ) : ( setSelectedItem(item)}> diff --git a/packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js b/packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js index 2b5a532c3..10f552ec5 100644 --- a/packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js +++ b/packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js @@ -1675,6 +1675,9 @@ export const collectionsSlice = createSlice({ if (type === 'testrun-ended') { const info = collection.runnerResult.info; info.status = 'ended'; + if (action.payload.statusText) { + info.statusText = action.payload.statusText; + } } if (type === 'request-queued') { @@ -1712,6 +1715,12 @@ export const collectionsSlice = createSlice({ item.responseReceived = action.payload.responseReceived; item.status = 'error'; } + + if (type === 'runner-request-skipped') { + const item = collection.runnerResult.items.findLast((i) => i.uid === request.uid); + item.status = 'skipped'; + item.responseReceived = action.payload.responseReceived; + } } }, resetCollectionRunner: (state, action) => { diff --git a/packages/bruno-cli/src/runner/run-single-request.js b/packages/bruno-cli/src/runner/run-single-request.js index 07af15c22..29ed749b9 100644 --- a/packages/bruno-cli/src/runner/run-single-request.js +++ b/packages/bruno-cli/src/runner/run-single-request.js @@ -17,7 +17,7 @@ const { HttpProxyAgent } = require('http-proxy-agent'); const { SocksProxyAgent } = require('socks-proxy-agent'); const { makeAxiosInstance } = require('../utils/axios-instance'); const { addAwsV4Interceptor, resolveAwsV4Credentials } = require('./awsv4auth-helper'); -const { shouldUseProxy, PatchedHttpsProxyAgent } = require('../utils/proxy-util'); +const { shouldUseProxy, PatchedHttpsProxyAgent, getSystemProxyEnvVariables } = require('../utils/proxy-util'); const path = require('path'); const { parseDataFromResponse } = require('../utils/common'); const { getCookieStringForUrl, saveCookies, shouldUseCookies } = require('../utils/cookies'); @@ -43,7 +43,7 @@ const runSingleRequest = async function ( try { let request; let nextRequestName; - let item = { + let item = { pathname: path.join(collectionPath, filename), ...bruJson } @@ -141,39 +141,85 @@ const runSingleRequest = async function ( } } - // set proxy if enabled - const proxyEnabled = get(brunoConfig, 'proxy.enabled', false); - const shouldProxy = shouldUseProxy(request.url, get(brunoConfig, 'proxy.bypassProxy', '')); - if (proxyEnabled && shouldProxy) { - const proxyProtocol = interpolateString(get(brunoConfig, 'proxy.protocol'), interpolationOptions); - const proxyHostname = interpolateString(get(brunoConfig, 'proxy.hostname'), interpolationOptions); - const proxyPort = interpolateString(get(brunoConfig, 'proxy.port'), interpolationOptions); - const proxyAuthEnabled = get(brunoConfig, 'proxy.auth.enabled', false); - const socksEnabled = proxyProtocol.includes('socks'); + let proxyMode = 'off'; + let proxyConfig = {}; - let uriPort = isUndefined(proxyPort) || isNull(proxyPort) ? '' : `:${proxyPort}`; - let proxyUri; - if (proxyAuthEnabled) { - const proxyAuthUsername = interpolateString(get(brunoConfig, 'proxy.auth.username'), interpolationOptions); - const proxyAuthPassword = interpolateString(get(brunoConfig, 'proxy.auth.password'), interpolationOptions); - - proxyUri = `${proxyProtocol}://${proxyAuthUsername}:${proxyAuthPassword}@${proxyHostname}${uriPort}`; - } else { - proxyUri = `${proxyProtocol}://${proxyHostname}${uriPort}`; + const collectionProxyConfig = get(brunoConfig, 'proxy', {}); + const collectionProxyEnabled = get(collectionProxyConfig, 'enabled', false); + if (collectionProxyEnabled === true) { + proxyConfig = collectionProxyConfig; + proxyMode = 'on'; + } else { + // if the collection level proxy is not set, pick the system level proxy by default, to maintain backward compatibility + const { http_proxy, https_proxy } = getSystemProxyEnvVariables(); + if (http_proxy?.length || https_proxy?.length) { + proxyMode = 'system'; } + } - if (socksEnabled) { - request.httpsAgent = new SocksProxyAgent( - proxyUri, - Object.keys(httpsAgentRequestFields).length > 0 ? { ...httpsAgentRequestFields } : undefined - ); - request.httpAgent = new SocksProxyAgent(proxyUri); + if (proxyMode === 'on') { + const shouldProxy = shouldUseProxy(request.url, get(proxyConfig, 'bypassProxy', '')); + if (shouldProxy) { + const proxyProtocol = interpolateString(get(proxyConfig, 'protocol'), interpolationOptions); + const proxyHostname = interpolateString(get(proxyConfig, 'hostname'), interpolationOptions); + const proxyPort = interpolateString(get(proxyConfig, 'port'), interpolationOptions); + const proxyAuthEnabled = get(proxyConfig, 'auth.enabled', false); + const socksEnabled = proxyProtocol.includes('socks'); + let uriPort = isUndefined(proxyPort) || isNull(proxyPort) ? '' : `:${proxyPort}`; + let proxyUri; + if (proxyAuthEnabled) { + const proxyAuthUsername = interpolateString(get(proxyConfig, 'auth.username'), interpolationOptions); + const proxyAuthPassword = interpolateString(get(proxyConfig, 'auth.password'), interpolationOptions); + + proxyUri = `${proxyProtocol}://${proxyAuthUsername}:${proxyAuthPassword}@${proxyHostname}${uriPort}`; + } else { + proxyUri = `${proxyProtocol}://${proxyHostname}${uriPort}`; + } + if (socksEnabled) { + request.httpsAgent = new SocksProxyAgent( + proxyUri, + Object.keys(httpsAgentRequestFields).length > 0 ? { ...httpsAgentRequestFields } : undefined + ); + request.httpAgent = new SocksProxyAgent(proxyUri); + } else { + request.httpsAgent = new PatchedHttpsProxyAgent( + proxyUri, + Object.keys(httpsAgentRequestFields).length > 0 ? { ...httpsAgentRequestFields } : undefined + ); + request.httpAgent = new HttpProxyAgent(proxyUri); + } } else { - request.httpsAgent = new PatchedHttpsProxyAgent( - proxyUri, - Object.keys(httpsAgentRequestFields).length > 0 ? { ...httpsAgentRequestFields } : undefined - ); - request.httpAgent = new HttpProxyAgent(proxyUri); + request.httpsAgent = new https.Agent({ + ...httpsAgentRequestFields + }); + } + } else if (proxyMode === 'system') { + const { http_proxy, https_proxy, no_proxy } = getSystemProxyEnvVariables(); + const shouldUseSystemProxy = shouldUseProxy(request.url, no_proxy || ''); + if (shouldUseSystemProxy) { + try { + if (http_proxy?.length) { + new URL(http_proxy); + request.httpAgent = new HttpProxyAgent(http_proxy); + } + } catch (error) { + throw new Error('Invalid system http_proxy'); + } + try { + if (https_proxy?.length) { + new URL(https_proxy); + request.httpsAgent = new PatchedHttpsProxyAgent( + https_proxy, + Object.keys(httpsAgentRequestFields).length > 0 ? { ...httpsAgentRequestFields } : undefined + ); + } + } catch (error) { + throw new Error('Invalid system https_proxy'); + } + } else { + request.httpsAgent = new https.Agent({ + ...httpsAgentRequestFields + }); } } else if (Object.keys(httpsAgentRequestFields).length > 0) { request.httpsAgent = new https.Agent({ diff --git a/packages/bruno-cli/src/utils/axios-instance.js b/packages/bruno-cli/src/utils/axios-instance.js index 8f61066c5..834cda2a8 100644 --- a/packages/bruno-cli/src/utils/axios-instance.js +++ b/packages/bruno-cli/src/utils/axios-instance.js @@ -10,6 +10,7 @@ const { CLI_VERSION } = require('../constants'); function makeAxiosInstance() { /** @type {axios.AxiosInstance} */ const instance = axios.create({ + proxy: false, headers: { "User-Agent": `bruno-runtime/${CLI_VERSION}` } diff --git a/packages/bruno-cli/src/utils/proxy-util.js b/packages/bruno-cli/src/utils/proxy-util.js index 729e03356..2a93d517e 100644 --- a/packages/bruno-cli/src/utils/proxy-util.js +++ b/packages/bruno-cli/src/utils/proxy-util.js @@ -79,7 +79,18 @@ class PatchedHttpsProxyAgent extends HttpsProxyAgent { } } + +const getSystemProxyEnvVariables = () => { + const { http_proxy, HTTP_PROXY, https_proxy, HTTPS_PROXY, no_proxy, NO_PROXY } = process.env; + return { + http_proxy: http_proxy || HTTP_PROXY, + https_proxy: https_proxy || HTTPS_PROXY, + no_proxy: no_proxy || NO_PROXY + }; +} + module.exports = { shouldUseProxy, - PatchedHttpsProxyAgent + PatchedHttpsProxyAgent, + getSystemProxyEnvVariables }; diff --git a/packages/bruno-electron/src/ipc/network/index.js b/packages/bruno-electron/src/ipc/network/index.js index e8e0b0030..5133a1f1d 100644 --- a/packages/bruno-electron/src/ipc/network/index.js +++ b/packages/bruno-electron/src/ipc/network/index.js @@ -39,6 +39,7 @@ const Oauth2Store = require('../../store/oauth2'); const iconv = require('iconv-lite'); const FormData = require('form-data'); const { createFormData } = require('../../utils/form-data'); +const { findItemInCollectionByPathname } = require('../../utils/collection'); const safeStringifyJSON = (data) => { try { @@ -397,7 +398,8 @@ const registerNetworkIpc = (mainWindow) => { collectionUid, runtimeVariables, processEnvVars, - scriptingConfig + scriptingConfig, + runRequestByItemPathname ) => { // run pre-request script let scriptResult; @@ -412,7 +414,8 @@ const registerNetworkIpc = (mainWindow) => { collectionPath, onConsoleLog, processEnvVars, - scriptingConfig + scriptingConfig, + runRequestByItemPathname ); mainWindow.webContents.send('main:script-environment-update', { @@ -462,7 +465,8 @@ const registerNetworkIpc = (mainWindow) => { collectionUid, runtimeVariables, processEnvVars, - scriptingConfig + scriptingConfig, + runRequestByItemPathname ) => { // run post-response vars const postResponseVars = get(request, 'vars.res', []); @@ -510,7 +514,8 @@ const registerNetworkIpc = (mainWindow) => { collectionPath, onConsoleLog, processEnvVars, - scriptingConfig + scriptingConfig, + runRequestByItemPathname ); mainWindow.webContents.send('main:script-environment-update', { @@ -527,14 +532,28 @@ const registerNetworkIpc = (mainWindow) => { return scriptResult; }; - // handler for sending http request - ipcMain.handle('send-http-request', async (event, item, collection, environment, runtimeVariables) => { + const runRequest = async ({ item, collection, environment, runtimeVariables, runInBackground = false }) => { const collectionUid = collection.uid; const collectionPath = collection.pathname; const cancelTokenUid = uuid(); const requestUid = uuid(); - mainWindow.webContents.send('main:run-request-event', { + const runRequestByItemPathname = async (relativeItemPathname) => { + return new Promise(async (resolve, reject) => { + let itemPathname = path.join(collection?.pathname, relativeItemPathname); + if (itemPathname && !itemPathname?.endsWith('.bru')) { + itemPathname = `${itemPathname}.bru`; + } + const _item = findItemInCollectionByPathname(collection, itemPathname); + if(_item) { + const res = await runRequest({ item: _item, collection, environment, runtimeVariables, runInBackground: true }); + resolve(res); + } + reject(`bru.runRequest: invalid request path - ${itemPathname}`); + }); + } + + !runInBackground && mainWindow.webContents.send('main:run-request-event', { type: 'request-queued', requestUid, collectionUid, @@ -565,7 +584,8 @@ const registerNetworkIpc = (mainWindow) => { collectionUid, runtimeVariables, processEnvVars, - scriptingConfig + scriptingConfig, + runRequestByItemPathname ); const axiosInstance = await configureRequest( @@ -577,7 +597,7 @@ const registerNetworkIpc = (mainWindow) => { collectionPath ); - mainWindow.webContents.send('main:run-request-event', { + !runInBackground && mainWindow.webContents.send('main:run-request-event', { type: 'request-sent', requestSent: { url: request.url, @@ -649,7 +669,8 @@ const registerNetworkIpc = (mainWindow) => { collectionUid, runtimeVariables, processEnvVars, - scriptingConfig + scriptingConfig, + runRequestByItemPathname ); // run assertions @@ -665,7 +686,7 @@ const registerNetworkIpc = (mainWindow) => { processEnvVars ); - mainWindow.webContents.send('main:run-request-event', { + !runInBackground && mainWindow.webContents.send('main:run-request-event', { type: 'assertion-results', results: results, itemUid: item.uid, @@ -686,10 +707,11 @@ const registerNetworkIpc = (mainWindow) => { collectionPath, onConsoleLog, processEnvVars, - scriptingConfig + scriptingConfig, + runRequestByItemPathname ); - mainWindow.webContents.send('main:run-request-event', { + !runInBackground && mainWindow.webContents.send('main:run-request-event', { type: 'test-results', results: testResults.results, itemUid: item.uid, @@ -723,6 +745,11 @@ const registerNetworkIpc = (mainWindow) => { return Promise.reject(error); } + } + + // handler for sending http request + ipcMain.handle('send-http-request', async (event, item, collection, environment, runtimeVariables) => { + return await runRequest({ item, collection, environment, runtimeVariables }); }); ipcMain.handle('send-collection-oauth2-request', async (event, collection, environment, runtimeVariables) => { @@ -914,10 +941,26 @@ const registerNetworkIpc = (mainWindow) => { const scriptingConfig = get(brunoConfig, 'scripts', {}); scriptingConfig.runtime = getJsSandboxRuntime(collection); const collectionRoot = get(collection, 'root', {}); + let stopRunnerExecution = false; const abortController = new AbortController(); saveCancelToken(cancelTokenUid, abortController); + const runRequestByItemPathname = async (relativeItemPathname) => { + return new Promise(async (resolve, reject) => { + let itemPathname = path.join(collection?.pathname, relativeItemPathname); + if (itemPathname && !itemPathname?.endsWith('.bru')) { + itemPathname = `${itemPathname}.bru`; + } + const _item = findItemInCollectionByPathname(collection, itemPathname); + if(_item) { + const res = await runRequest({ item: _item, collection, environment, runtimeVariables, runInBackground: true }); + resolve(res); + } + reject(`bru.runRequest: invalid request path - ${itemPathname}`); + }); + } + if (!folder) { folder = collection; } @@ -960,6 +1003,8 @@ const registerNetworkIpc = (mainWindow) => { throw error; } + stopRunnerExecution = false; + const item = folderRequests[currentRequestIndex]; let nextRequestName; const itemUid = item.uid; @@ -993,13 +1038,33 @@ const registerNetworkIpc = (mainWindow) => { collectionUid, runtimeVariables, processEnvVars, - scriptingConfig + scriptingConfig, + runRequestByItemPathname ); if (preRequestScriptResult?.nextRequestName !== undefined) { nextRequestName = preRequestScriptResult.nextRequestName; } + if (preRequestScriptResult?.stopExecution) { + stopRunnerExecution = true; + } + + if (preRequestScriptResult?.skipRequest) { + mainWindow.webContents.send('main:run-folder-event', { + type: 'runner-request-skipped', + error: 'Request has been skipped from pre-request script', + responseReceived: { + status: 'skipped', + statusText: 'request skipped via pre-request script', + data: null + }, + ...eventData + }); + currentRequestIndex++; + continue; + } + // todo: // i have no clue why electron can't send the request object // without safeParseJSON(safeStringifyJSON(request.data)) @@ -1111,13 +1176,18 @@ const registerNetworkIpc = (mainWindow) => { collectionUid, runtimeVariables, processEnvVars, - scriptingConfig + scriptingConfig, + runRequestByItemPathname ); if (postRequestScriptResult?.nextRequestName !== undefined) { nextRequestName = postRequestScriptResult.nextRequestName; } + if (postRequestScriptResult?.stopExecution) { + stopRunnerExecution = true; + } + // run assertions const assertions = get(item, 'request.assertions'); if (assertions) { @@ -1151,7 +1221,8 @@ const registerNetworkIpc = (mainWindow) => { collectionPath, onConsoleLog, processEnvVars, - scriptingConfig + scriptingConfig, + runRequestByItemPathname ); if (testResults?.nextRequestName !== undefined) { @@ -1182,6 +1253,18 @@ const registerNetworkIpc = (mainWindow) => { ...eventData }); } + + if (stopRunnerExecution) { + deleteCancelToken(cancelTokenUid); + mainWindow.webContents.send('main:run-folder-event', { + type: 'testrun-ended', + collectionUid, + folderUid, + statusText: 'collection run was terminated!' + }); + break; + } + if (nextRequestName !== undefined) { nJumps++; if (nJumps > 10000) { diff --git a/packages/bruno-electron/src/utils/collection.js b/packages/bruno-electron/src/utils/collection.js index 5b9c3452e..15d5574e2 100644 --- a/packages/bruno-electron/src/utils/collection.js +++ b/packages/bruno-electron/src/utils/collection.js @@ -203,9 +203,31 @@ const getTreePathFromCollectionToItem = (collection, _item) => { return path; }; +const slash = (path) => { + const isExtendedLengthPath = /^\\\\\?\\/.test(path); + if (isExtendedLengthPath) { + return path; + } + return path?.replace?.(/\\/g, '/'); +}; + +const findItemByPathname = (items = [], pathname) => { + return find(items, (i) => slash(i.pathname) === slash(pathname)); +}; + +const findItemInCollectionByPathname = (collection, pathname) => { + let flattenedItems = flattenItems(collection.items); + + return findItemByPathname(flattenedItems, pathname); +}; + + module.exports = { mergeHeaders, mergeVars, mergeScripts, - getTreePathFromCollectionToItem + getTreePathFromCollectionToItem, + slash, + findItemByPathname, + findItemInCollectionByPathname } \ No newline at end of file diff --git a/packages/bruno-js/src/bru.js b/packages/bruno-js/src/bru.js index 5a4d69426..9fa9d8f0c 100644 --- a/packages/bruno-js/src/bru.js +++ b/packages/bruno-js/src/bru.js @@ -13,6 +13,17 @@ class Bru { this.requestVariables = requestVariables || {}; this.globalEnvironmentVariables = globalEnvironmentVariables || {}; this.collectionPath = collectionPath; + this.runner = { + skipRequest: () => { + this.skipRequest = true; + }, + stopExecution: () => { + this.stopExecution = true; + }, + setNextRequest: (nextRequest) => { + this.nextRequest = nextRequest; + } + }; } _interpolate = (str) => { diff --git a/packages/bruno-js/src/runtime/assert-runtime.js b/packages/bruno-js/src/runtime/assert-runtime.js index 4132fea9c..558dcaba1 100644 --- a/packages/bruno-js/src/runtime/assert-runtime.js +++ b/packages/bruno-js/src/runtime/assert-runtime.js @@ -408,6 +408,8 @@ class AssertRuntime { } } + request.assertionResults = assertionResults; + return assertionResults; } } diff --git a/packages/bruno-js/src/runtime/script-runtime.js b/packages/bruno-js/src/runtime/script-runtime.js index 0f82114b2..dcde3f27c 100644 --- a/packages/bruno-js/src/runtime/script-runtime.js +++ b/packages/bruno-js/src/runtime/script-runtime.js @@ -45,7 +45,8 @@ class ScriptRuntime { collectionPath, onConsoleLog, processEnvVars, - scriptingConfig + scriptingConfig, + runRequestByItemPathname ) { const globalEnvironmentVariables = request?.globalEnvironmentVariables || {}; const collectionVariables = request?.collectionVariables || {}; @@ -92,6 +93,10 @@ class ScriptRuntime { }; } + if(runRequestByItemPathname) { + context.bru.runRequest = runRequestByItemPathname; + } + if (this.runtime === 'quickjs') { await executeQuickJsVmAsync({ script: script, @@ -104,7 +109,9 @@ class ScriptRuntime { envVariables: cleanJson(envVariables), runtimeVariables: cleanJson(runtimeVariables), globalEnvironmentVariables: cleanJson(globalEnvironmentVariables), - nextRequestName: bru.nextRequest + nextRequestName: bru.nextRequest, + skipRequest: bru.skipRequest, + stopExecution: bru.stopExecution }; } @@ -152,7 +159,9 @@ class ScriptRuntime { envVariables: cleanJson(envVariables), runtimeVariables: cleanJson(runtimeVariables), globalEnvironmentVariables: cleanJson(globalEnvironmentVariables), - nextRequestName: bru.nextRequest + nextRequestName: bru.nextRequest, + skipRequest: bru.skipRequest, + stopExecution: bru.stopExecution }; } @@ -165,7 +174,8 @@ class ScriptRuntime { collectionPath, onConsoleLog, processEnvVars, - scriptingConfig + scriptingConfig, + runRequestByItemPathname ) { const globalEnvironmentVariables = request?.globalEnvironmentVariables || {}; const collectionVariables = request?.collectionVariables || {}; @@ -209,6 +219,10 @@ class ScriptRuntime { }; } + if(runRequestByItemPathname) { + context.bru.runRequest = runRequestByItemPathname; + } + if (this.runtime === 'quickjs') { await executeQuickJsVmAsync({ script: script, @@ -221,7 +235,9 @@ class ScriptRuntime { envVariables: cleanJson(envVariables), runtimeVariables: cleanJson(runtimeVariables), globalEnvironmentVariables: cleanJson(globalEnvironmentVariables), - nextRequestName: bru.nextRequest + nextRequestName: bru.nextRequest, + skipRequest: bru.skipRequest, + stopExecution: bru.stopExecution }; } @@ -269,7 +285,9 @@ class ScriptRuntime { envVariables: cleanJson(envVariables), runtimeVariables: cleanJson(runtimeVariables), globalEnvironmentVariables: cleanJson(globalEnvironmentVariables), - nextRequestName: bru.nextRequest + nextRequestName: bru.nextRequest, + skipRequest: bru.skipRequest, + stopExecution: bru.stopExecution }; } } diff --git a/packages/bruno-js/src/runtime/test-runtime.js b/packages/bruno-js/src/runtime/test-runtime.js index 5391f7e10..71db9d83e 100644 --- a/packages/bruno-js/src/runtime/test-runtime.js +++ b/packages/bruno-js/src/runtime/test-runtime.js @@ -32,6 +32,25 @@ const CryptoJS = require('crypto-js'); const NodeVault = require('node-vault'); const { executeQuickJsVmAsync } = require('../sandbox/quickjs'); +const getResultsSummary = (results) => { + const summary = { + total: results.length, + passed: 0, + failed: 0, + skipped: 0, + }; + + results.forEach((r) => { + const passed = r.status === "pass"; + if (passed) summary.passed += 1; + else if (r.status === "fail") summary.failed += 1; + else summary.skipped += 1; + }); + + return summary; +} + + class TestRuntime { constructor(props) { this.runtime = props?.runtime || 'vm2'; @@ -46,12 +65,14 @@ class TestRuntime { collectionPath, onConsoleLog, processEnvVars, - scriptingConfig + scriptingConfig, + runRequestByItemPathname ) { const globalEnvironmentVariables = request?.globalEnvironmentVariables || {}; const collectionVariables = request?.collectionVariables || {}; const folderVariables = request?.folderVariables || {}; const requestVariables = request?.requestVariables || {}; + const assertionResults = request?.assertionResults || []; const bru = new Bru(envVariables, runtimeVariables, processEnvVars, collectionPath, collectionVariables, folderVariables, requestVariables, globalEnvironmentVariables); const req = new BrunoRequest(request); const res = new BrunoResponse(response); @@ -75,6 +96,7 @@ class TestRuntime { } const __brunoTestResults = new TestResults(); + const test = Test(__brunoTestResults, chai); if (!testsFile || !testsFile.length) { @@ -88,6 +110,36 @@ class TestRuntime { }; } + bru.getTestResults = async () => { + let results = await __brunoTestResults.getResults(); + const summary = getResultsSummary(results); + return { + summary, + results: results?.map?.(r => ({ + status: r?.status, + description: r?.description, + expected: r?.expected, + actual: r?.actual, + error: r?.error + })) + }; + } + bru.getAssertionResults = async () => { + let results = assertionResults; + const summary = getResultsSummary(results); + return { + summary, + results: results?.map?.(r => ({ + status: r?.status, + lhsExpr: r?.lhsExpr, + rhsExpr: r?.rhsExpr, + operator: r?.operator, + rhsOperand: r?.rhsOperand, + error: r?.error + })) + }; + } + const context = { test, bru, @@ -113,6 +165,10 @@ class TestRuntime { }; } + if(runRequestByItemPathname) { + context.bru.runRequest = runRequestByItemPathname; + } + if (this.runtime === 'quickjs') { await executeQuickJsVmAsync({ script: testsFile, diff --git a/packages/bruno-js/src/sandbox/quickjs/shims/bru.js b/packages/bruno-js/src/sandbox/quickjs/shims/bru.js index 297add66a..fa4cbf341 100644 --- a/packages/bruno-js/src/sandbox/quickjs/shims/bru.js +++ b/packages/bruno-js/src/sandbox/quickjs/shims/bru.js @@ -1,7 +1,9 @@ +const { cleanJson } = require('../../../utils'); const { marshallToVm } = require('../utils'); const addBruShimToContext = (vm, bru) => { const bruObject = vm.newObject(); + const bruRunnerObject = vm.newObject(); let cwd = vm.newFunction('cwd', function () { return marshallToVm(bru.cwd(), vm); @@ -93,6 +95,24 @@ const addBruShimToContext = (vm, bru) => { vm.setProp(bruObject, 'setNextRequest', setNextRequest); setNextRequest.dispose(); + let runnerSkipRequest = vm.newFunction('skipRequest', function () { + bru?.runner?.skipRequest(); + }); + vm.setProp(bruRunnerObject, 'skipRequest', runnerSkipRequest); + runnerSkipRequest.dispose(); + + let runnerStopExecution = vm.newFunction('stopExecution', function () { + bru?.runner?.stopExecution(); + }); + vm.setProp(bruRunnerObject, 'stopExecution', runnerStopExecution); + runnerStopExecution.dispose(); + + let runnerSetNextRequest = vm.newFunction('setNextRequest', function (nextRequest) { + bru?.runner?.setNextRequest(vm.dump(nextRequest)); + }); + vm.setProp(bruRunnerObject, 'setNextRequest', runnerSetNextRequest); + runnerSetNextRequest.dispose(); + let visualize = vm.newFunction('visualize', function (htmlString) { bru.visualize(vm.dump(htmlString)); }); @@ -123,6 +143,70 @@ const addBruShimToContext = (vm, bru) => { vm.setProp(bruObject, 'getCollectionVar', getCollectionVar); getCollectionVar.dispose(); + let getTestResults = vm.newFunction('getTestResults', () => { + const promise = vm.newPromise(); + bru.getTestResults() + .then((results) => { + promise.resolve(marshallToVm(cleanJson(results), vm)); + }) + .catch((err) => { + promise.resolve( + marshallToVm( + cleanJson({ + message: err.message + }), + vm + ) + ); + }); + promise.settled.then(vm.runtime.executePendingJobs); + return promise.handle; + }); + getTestResults.consume((handle) => vm.setProp(bruObject, 'getTestResults', handle)); + + let getAssertionResults = vm.newFunction('getAssertionResults', () => { + const promise = vm.newPromise(); + bru.getAssertionResults() + .then((results) => { + promise.resolve(marshallToVm(cleanJson(results), vm)); + }) + .catch((err) => { + promise.resolve( + marshallToVm( + cleanJson({ + message: err.message + }), + vm + ) + ); + }); + promise.settled.then(vm.runtime.executePendingJobs); + return promise.handle; + }); + getAssertionResults.consume((handle) => vm.setProp(bruObject, 'getAssertionResults', handle)); + + let runRequestHandle = vm.newFunction('runRequest', (args) => { + const promise = vm.newPromise(); + bru.runRequest(vm.dump(args)) + .then((response) => { + const { status, headers, data, dataBuffer, size } = response || {}; + promise.resolve(marshallToVm(cleanJson({ status, headers, data, dataBuffer, size }), vm)); + }) + .catch((err) => { + promise.resolve( + marshallToVm( + cleanJson({ + message: err.message + }), + vm + ) + ); + }); + promise.settled.then(vm.runtime.executePendingJobs); + return promise.handle; + }); + runRequestHandle.consume((handle) => vm.setProp(bruObject, 'runRequest', handle)); + const sleep = vm.newFunction('sleep', (timer) => { const t = vm.getString(timer); const promise = vm.newPromise(); @@ -134,6 +218,7 @@ const addBruShimToContext = (vm, bru) => { }); sleep.consume((handle) => vm.setProp(bruObject, 'sleep', handle)); + vm.setProp(bruObject, 'runner', bruRunnerObject); vm.setProp(vm.global, 'bru', bruObject); bruObject.dispose(); }; diff --git a/packages/bruno-schema/package.json b/packages/bruno-schema/package.json index 1e91a9a1a..61542cf69 100644 --- a/packages/bruno-schema/package.json +++ b/packages/bruno-schema/package.json @@ -12,5 +12,8 @@ }, "peerDependencies": { "yup": "^0.32.11" + }, + "dependencies": { + "nanoid": "3.3.8" } }