From 1a89410289841d75c4a599787ff981c1b2bc896f Mon Sep 17 00:00:00 2001 From: George He Date: Thu, 31 Oct 2024 15:46:55 +0800 Subject: [PATCH 1/2] fix(cli): enable setNextRequest for CLI --- packages/insomnia-inso/src/cli.test.ts | 2 + packages/insomnia-inso/src/cli.ts | 37 +++++- .../src/examples/set-next-request.yml | 113 ++++++++++++++++++ packages/insomnia/src/common/send-request.ts | 13 +- packages/insomnia/src/scriptExecutor.ts | 1 + 5 files changed, 163 insertions(+), 3 deletions(-) create mode 100644 packages/insomnia-inso/src/examples/set-next-request.yml diff --git a/packages/insomnia-inso/src/cli.test.ts b/packages/insomnia-inso/src/cli.test.ts index 0ec77994edf..a61befd6fb0 100644 --- a/packages/insomnia-inso/src/cli.test.ts +++ b/packages/insomnia-inso/src/cli.test.ts @@ -43,6 +43,8 @@ const shouldReturnSuccessCode = [ '$PWD/packages/insomnia-inso/bin/inso run collection -w packages/insomnia-inso/src/examples/after-response.yml wrk_616795 --verbose', // select request by id '$PWD/packages/insomnia-inso/bin/inso run collection -w packages/insomnia-inso/src/examples/three-requests.yml -i req_3fd28aabbb18447abab1f45e6ee4bdc1 -i req_6063adcdab5b409e9b4f00f47322df4a', + // setNextRequest runs the next request then ends + '$PWD/packages/insomnia-inso/bin/inso run collection -w packages/insomnia-inso/src/examples/set-next-request.yml wrk_cbc89e', // multiple --env-var overrides '$PWD/packages/insomnia-inso/bin/inso run collection -w packages/insomnia-inso/src/examples/with-missing-env-vars.yml -i req_3fd28aabbb18447abab1f45e6ee4bdc1 --env-var firstkey=first --env-var secondkey=second', // globals file path env overrides diff --git a/packages/insomnia-inso/src/cli.ts b/packages/insomnia-inso/src/cli.ts index cf4df8bb022..ce3ae526343 100644 --- a/packages/insomnia-inso/src/cli.ts +++ b/packages/insomnia-inso/src/cli.ts @@ -23,6 +23,7 @@ import { Database, isFile, loadDb } from './db'; import { insomniaExportAdapter } from './db/adapters/insomnia-adapter'; import { loadApiSpec, promptApiSpec } from './db/models/api-spec'; import { loadEnvironment, promptEnvironment } from './db/models/environment'; +import { BaseModel } from './db/models/types'; import { loadTestSuites, promptTestSuites } from './db/models/unit-test-suite'; import { matchIdIsh } from './db/models/util'; import { loadWorkspace, promptWorkspace } from './db/models/workspace'; @@ -530,6 +531,23 @@ export const go = (args?: string[]) => { return process.exit(1); } + const getNextRequestOffset = ( + leftRequestsToRun: BaseModel[], + nextRequestIdOrName: string + ) => { + const idMatchOffset = leftRequestsToRun.findIndex(req => req._id.trim() === nextRequestIdOrName.trim()); + if (idMatchOffset >= 0) { + return idMatchOffset; + } + + const nameMatchOffset = leftRequestsToRun.reverse().findIndex(req => req.name.trim() === nextRequestIdOrName.trim()); + if (nameMatchOffset >= 0) { + return leftRequestsToRun.length - 1 - nameMatchOffset; + } + + return leftRequestsToRun.length; + }; + try { const iterationCount = parseInt(options.iterationCount, 10); @@ -537,7 +555,10 @@ export const go = (args?: string[]) => { const sendRequest = await getSendRequestCallbackMemDb(environment._id, db, { validateSSL: !options.disableCertValidation }, iterationData, iterationCount); let success = true; for (let i = 0; i < iterationCount; i++) { - for (const req of requestsToRun) { + let reqIndex = 0; + while (reqIndex < requestsToRun.length) { + const req = requestsToRun[reqIndex]; + if (options.bail && !success) { return; } @@ -548,7 +569,7 @@ export const go = (args?: string[]) => { success = false; continue; } - // logger.debug(res); + const timelineString = await readFile(res.timelinePath, 'utf8'); const appendNewLineIfNeeded = (str: string) => str.endsWith('\n') ? str : str + '\n'; const timeline = deserializeNDJSON(timelineString).map(e => appendNewLineIfNeeded(e.value)).join(''); @@ -564,6 +585,18 @@ Test results:`); } await new Promise(r => setTimeout(r, parseInt(options.delayRequest, 10))); + + if (res.nextRequestIdOrName) { + const offset = getNextRequestOffset(requestsToRun.slice(reqIndex), res.nextRequestIdOrName); + reqIndex += offset; + if (reqIndex < requestsToRun.length) { + console.log(`The next request has been pointed to "${requestsToRun[reqIndex].name}"`); + } else { + console.log(`No request has been found for "${res.nextRequestIdOrName}", ending the iteration`); + } + } else { + reqIndex++; + } } } return process.exit(success ? 0 : 1); diff --git a/packages/insomnia-inso/src/examples/set-next-request.yml b/packages/insomnia-inso/src/examples/set-next-request.yml new file mode 100644 index 00000000000..06d82757705 --- /dev/null +++ b/packages/insomnia-inso/src/examples/set-next-request.yml @@ -0,0 +1,113 @@ +_type: export +__export_format: 4 +__export_date: 2024-10-26T22:34:07.758Z +__export_source: insomnia.desktop.app:v10.1.1 +resources: + - _id: req_5b004a6d43ef4e62a9117b9e08daa61e + parentId: wrk_cbc89ea8669648b8970ae684f9ff08b8 + modified: 1729982030396 + created: 1729981763331 + url: localhost:4010/echo + name: setNextRequest + description: "" + method: GET + body: {} + parameters: [] + headers: + - name: User-Agent + value: insomnia/10.1.1 + authentication: {} + metaSortKey: -1729981822482 + isPrivate: false + pathParameters: [] + afterResponseScript: |+ + insomnia.execution.setNextRequest("Passing Request"); + settingStoreCookies: true + settingSendCookies: true + settingDisableRenderRequestBody: false + settingEncodeUrl: true + settingRebuildPath: true + settingFollowRedirects: global + _type: request + - _id: wrk_cbc89ea8669648b8970ae684f9ff08b8 + parentId: null + modified: 1729981758905 + created: 1729981758905 + name: test next request + description: "" + scope: collection + _type: workspace + - _id: req_6a0343d51ca74de7a2c73e34211354ab + parentId: wrk_cbc89ea8669648b8970ae684f9ff08b8 + modified: 1729981999436 + created: 1729981846012 + url: localhost:4010/echo + name: Failing Request + description: "" + method: GET + body: {} + parameters: [] + headers: + - name: User-Agent + value: insomnia/10.1.1 + authentication: {} + preRequestScript: |- + insomnia.test('Failing test', () => { + insomnia.expect(true).to.eql(false); + }); + metaSortKey: -1729981763231 + isPrivate: false + pathParameters: [] + settingStoreCookies: true + settingSendCookies: true + settingDisableRenderRequestBody: false + settingEncodeUrl: true + settingRebuildPath: true + settingFollowRedirects: global + _type: request + - _id: req_704fcb5bf8e047cbaee4f8ca23a97249 + parentId: wrk_cbc89ea8669648b8970ae684f9ff08b8 + modified: 1729982010136 + created: 1729981822432 + url: localhost:4010/echo + name: Passing Request + description: "" + method: GET + body: {} + parameters: [] + headers: + - name: User-Agent + value: insomnia/10.1.1 + authentication: {} + preRequestScript: |- + insomnia.test('Passing test', () => { + insomnia.expect(true).to.eql(true); + }); + metaSortKey: -1729981763131 + isPrivate: false + pathParameters: [] + settingStoreCookies: true + settingSendCookies: true + settingDisableRenderRequestBody: false + settingEncodeUrl: true + settingRebuildPath: true + settingFollowRedirects: global + _type: request + - _id: env_6d416edc2e4fd8b59c75eae67c16f3b21e1e2de2 + parentId: wrk_cbc89ea8669648b8970ae684f9ff08b8 + modified: 1729982036362 + created: 1729981758906 + name: Base Environment + data: {} + dataPropertyOrder: {} + color: null + isPrivate: false + metaSortKey: 1729981758906 + _type: environment + - _id: jar_6d416edc2e4fd8b59c75eae67c16f3b21e1e2de2 + parentId: wrk_cbc89ea8669648b8970ae684f9ff08b8 + modified: 1729982036362 + created: 1729981758906 + name: Default Jar + cookies: [] + _type: cookie_jar diff --git a/packages/insomnia/src/common/send-request.ts b/packages/insomnia/src/common/send-request.ts index 74c0b0326dc..da0bcf7de88 100644 --- a/packages/insomnia/src/common/send-request.ts +++ b/packages/insomnia/src/common/send-request.ts @@ -33,6 +33,7 @@ const wrapAroundIterationOverIterationData = (list?: UserUploadEnvironment[], cu }; return list[(currentIteration + 1) % list.length]; }; + export async function getSendRequestCallbackMemDb(environmentId: string, memDB: any, settingsOverrides?: SettingsOverride, iterationData?: UserUploadEnvironment[], iterationCount?: number) { // Initialize the DB in-memory and fill it with data if we're given one await database.init( @@ -168,6 +169,16 @@ export async function getSendRequestCallbackMemDb(environmentId: string, memDB: const bodyBuffer = await getBodyBuffer(res) as Buffer; const data = bodyBuffer ? bodyBuffer.toString('utf8') : undefined; - return { status, statusMessage, data, headers, responseTime, timelinePath: requestData.timelinePath, testResults: postMutatedContext.requestTestResults }; + const testResults = [...(mutatedContext.requestTestResults || []), ...(postMutatedContext.requestTestResults || [])]; + return { + status, + statusMessage, + data, + headers, + responseTime, + timelinePath: requestData.timelinePath, + testResults, + nextRequestIdOrName: postMutatedContext?.execution?.nextRequestIdOrName, + }; }; } diff --git a/packages/insomnia/src/scriptExecutor.ts b/packages/insomnia/src/scriptExecutor.ts index b5264c7b682..2fe195b1dc2 100644 --- a/packages/insomnia/src/scriptExecutor.ts +++ b/packages/insomnia/src/scriptExecutor.ts @@ -82,6 +82,7 @@ export const runScript = async ( cookieJar: updatedCookieJar, globals: mutatedContextObject.globals, requestTestResults: mutatedContextObject.requestTestResults, + execution: mutatedContextObject.execution, }; }; From 140905f53e2f88d869b9b39f527f3505eaa71d53 Mon Sep 17 00:00:00 2001 From: George He Date: Thu, 31 Oct 2024 15:55:56 +0800 Subject: [PATCH 2/2] chore: move function out of the command --- packages/insomnia-inso/src/cli.ts | 34 +++++++++++++++---------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/packages/insomnia-inso/src/cli.ts b/packages/insomnia-inso/src/cli.ts index ce3ae526343..0c442cdff5f 100644 --- a/packages/insomnia-inso/src/cli.ts +++ b/packages/insomnia-inso/src/cli.ts @@ -531,23 +531,6 @@ export const go = (args?: string[]) => { return process.exit(1); } - const getNextRequestOffset = ( - leftRequestsToRun: BaseModel[], - nextRequestIdOrName: string - ) => { - const idMatchOffset = leftRequestsToRun.findIndex(req => req._id.trim() === nextRequestIdOrName.trim()); - if (idMatchOffset >= 0) { - return idMatchOffset; - } - - const nameMatchOffset = leftRequestsToRun.reverse().findIndex(req => req.name.trim() === nextRequestIdOrName.trim()); - if (nameMatchOffset >= 0) { - return leftRequestsToRun.length - 1 - nameMatchOffset; - } - - return leftRequestsToRun.length; - }; - try { const iterationCount = parseInt(options.iterationCount, 10); @@ -742,3 +725,20 @@ Test results:`); program.parseAsync(args || process.argv).catch(logErrorAndExit); }; + +const getNextRequestOffset = ( + leftRequestsToRun: BaseModel[], + nextRequestIdOrName: string +) => { + const idMatchOffset = leftRequestsToRun.findIndex(req => req._id.trim() === nextRequestIdOrName.trim()); + if (idMatchOffset >= 0) { + return idMatchOffset; + } + + const nameMatchOffset = leftRequestsToRun.reverse().findIndex(req => req.name.trim() === nextRequestIdOrName.trim()); + if (nameMatchOffset >= 0) { + return leftRequestsToRun.length - 1 - nameMatchOffset; + } + + return leftRequestsToRun.length; +};