Skip to content

Commit

Permalink
fix(cli): enable setNextRequest for CLI
Browse files Browse the repository at this point in the history
  • Loading branch information
ihexxa committed Oct 31, 2024
1 parent 4c759b0 commit ccbcf38
Show file tree
Hide file tree
Showing 5 changed files with 163 additions and 3 deletions.
2 changes: 2 additions & 0 deletions packages/insomnia-inso/src/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
37 changes: 35 additions & 2 deletions packages/insomnia-inso/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -530,14 +531,34 @@ 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);

const iterationData = await pathToIterationData(options.iterationData, options.envVar);
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;
}
Expand All @@ -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('');
Expand All @@ -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);
Expand Down
113 changes: 113 additions & 0 deletions packages/insomnia-inso/src/examples/set-next-request.yml
Original file line number Diff line number Diff line change
@@ -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
13 changes: 12 additions & 1 deletion packages/insomnia/src/common/send-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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,
};
};
}
1 change: 1 addition & 0 deletions packages/insomnia/src/scriptExecutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export const runScript = async (
cookieJar: updatedCookieJar,
globals: mutatedContextObject.globals,
requestTestResults: mutatedContextObject.requestTestResults,
execution: mutatedContextObject.execution,
};
};

Expand Down

0 comments on commit ccbcf38

Please sign in to comment.