Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: enable manipulation on insomnia.request - INS-3379 #7145

Merged
merged 8 commits into from
Mar 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 37 additions & 5 deletions packages/insomnia-smoke-test/fixtures/pre-request-collection.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ resources:
parentId: wrk_6b9b8455fd784462ae19cd51d7156f86
modified: 1707809218855
created: 1707808697304
url: ""
url: http://127.0.0.1:4010/echo
name: Long running task
description: ""
method: GET
Expand Down Expand Up @@ -78,7 +78,7 @@ resources:
parentId: wrk_6b9b8455fd784462ae19cd51d7156f86
modified: 1707809035895
created: 1707809028449
url: ""
url: http://127.0.0.1:4010/echo
name: Range error
description: ""
method: GET
Expand All @@ -103,7 +103,7 @@ resources:
parentId: wrk_6b9b8455fd784462ae19cd51d7156f86
modified: 1707808953866
created: 1707808727077
url: ""
url: http://127.0.0.1:4010/echo
name: Syntax error
description: ""
method: GET
Expand All @@ -128,7 +128,7 @@ resources:
parentId: wrk_6b9b8455fd784462ae19cd51d7156f86
modified: 1707808979424
created: 1707808961112
url: ""
url: http://127.0.0.1:4010/echo
name: Type error
description: ""
method: GET
Expand All @@ -155,7 +155,7 @@ resources:
parentId: wrk_6b9b8455fd784462ae19cd51d7156f86
modified: 1707809017110
created: 1707809000715
url: ""
url: http://127.0.0.1:4010/echo
name: Reference error
description: ""
method: GET
Expand Down Expand Up @@ -194,3 +194,35 @@ resources:
name: Default Jar
cookies: []
_type: cookie_jar
- _id: fld_01de564274824ecaad272330339ea6b2
parentId: wrk_6b9b8455fd784462ae19cd51d7156f86
modified: 1668533312225
created: 1668533312225
name: FolderWithEnv
description: ""
environment:
customValue: "fromFolder"
environmentPropertyOrder: null
metaSortKey: -1668533312225
_type: request_group
- _id: req_89dade2ee9ee42fbb22d588783a9df3c
parentId: fld_01de564274824ecaad272330339ea6b2
modified: 1636707449231
created: 1636141014552
url: http://127.0.0.1:4010/echo
name: echo pre-request script result
description: ""
method: POST
body: {}
parameters: []
headers: []
authentication: {}
metaSortKey: -1636141014553
isPrivate: false
settingStoreCookies: true
settingSendCookies: true
settingDisableRenderRequestBody: false
settingEncodeUrl: true
settingRebuildPath: true
settingFollowRedirects: global
_type: request
22 changes: 0 additions & 22 deletions packages/insomnia-smoke-test/fixtures/smoke-test-collection.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -176,27 +176,6 @@ resources:
settingRebuildPath: true
settingFollowRedirects: global
_type: request
- _id: req_89dade2ee9ee42fbb22d588783a9df3c
parentId: fld_01de564274824ecaad272330339ea6b2
modified: 1636707449231
created: 1636141014552
url: http://127.0.0.1:4010/echo
name: echo pre-request script result
description: ""
method: POST
body: {}
parameters: []
headers: []
authentication: {}
metaSortKey: -1636141014553
isPrivate: false
settingStoreCookies: true
settingSendCookies: true
settingDisableRenderRequestBody: false
settingEncodeUrl: true
settingRebuildPath: true
settingFollowRedirects: global
_type: request
- _id: env_afc214be117853a024cce22f194c500e68dac13f
parentId: wrk_5b5ab67830944ffcbec47528366ef403
modified: 1636140994432
Expand Down Expand Up @@ -298,4 +277,3 @@ resources:
settingRebuildPath: true
settingFollowRedirects: global
_type: request

11 changes: 7 additions & 4 deletions packages/insomnia-smoke-test/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ app.use(cookieParser.default());
const port = 4010;
const httpsPort = 4011;
const grpcPort = 50051;
const jsonParser = bodyParser.json();
const rawParser = bodyParser.raw({
inflate: true,
type: '*/*',
});

app.get('/pets/:id', (req, res) => {
res.status(200).send({ id: req.params.id });
Expand All @@ -39,13 +42,13 @@ async function echoHandler(req: any, res: any) {
res.status(200).send({
method: req.method,
headers: req.headers,
data: req.body,
data: req.body.toString(),
cookies: req.cookies,
});
};

app.get('/echo', jsonParser, echoHandler);
app.post('/echo', jsonParser, echoHandler);
app.get('/echo', rawParser, echoHandler);
app.post('/echo', rawParser, echoHandler);

app.get('/sleep', (_req, res) => {
res.status(200).send({ sleep: true });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import { expect } from '@playwright/test';
import { loadFixture } from '../../playwright/paths';
import { test } from '../../playwright/test';;

test.describe('pre-request UI tests', async () => {
test.describe('pre-request features tests', async () => {
test.slow(process.platform === 'darwin' || process.platform === 'win32', 'Slow app start on these platforms');

test.beforeEach(async ({ app, page }) => {
const text = await loadFixture('smoke-test-collection.yaml');
const text = await loadFixture('pre-request-collection.yaml');
await app.evaluate(async ({ clipboard }, text) => clipboard.writeText(text), text);

await page.getByRole('button', { name: 'Create in project' }).click();
Expand All @@ -16,7 +16,7 @@ test.describe('pre-request UI tests', async () => {
await page.getByRole('button', { name: 'Scan' }).click();
await page.getByRole('dialog').getByRole('button', { name: 'Import' }).click();

await page.getByLabel('Smoke tests').click();
await page.getByLabel('Pre-request Scripts').click();
});

const testCases = [
Expand All @@ -34,10 +34,10 @@ test.describe('pre-request UI tests', async () => {
insomnia.baseEnvironment.set('customValue', 'fromScript');
`,
body: `{
"fromBaseEnv": "{{ _.fromBaseEnv }}",
"scriptValue": "{{ _.scriptValue }}",
"preDefinedValue": "{{ _.preDefinedValue }}",
"customValue": "{{ _.customValue }}"
"fromBaseEnv": "{{ _.fromBaseEnv }}",
"scriptValue": "{{ _.scriptValue }}",
"preDefinedValue": "{{ _.preDefinedValue }}",
"customValue": "{{ _.customValue }}"
}`,
expectedBody: {
fromBaseEnv: 'baseEnv',
Expand All @@ -59,9 +59,9 @@ test.describe('pre-request UI tests', async () => {
pm.environment.set('varBool', pm.variables.get('varBool'));
`,
body: `{
"varStr": "{{ _.varStr }}",
"varNum": {{ _.varNum }},
"varBool": {{ _.varBool }}
"varStr": "{{ _.varStr }}",
"varNum": {{ _.varNum }},
"varBool": {{ _.varBool }}
}`,
expectedBody: {
varStr: 'varStr',
Expand Down Expand Up @@ -160,8 +160,8 @@ test.describe('pre-request UI tests', async () => {
insomnia.environment.set('headerJson', JSON.stringify(header.toJSON()));
`,
body: `{
"propJson": {{ _.propJson }},
"headerJson": {{ _.headerJson }}
"propJson": {{ _.propJson }},
"headerJson": {{ _.headerJson }}
}`,
expectedBody: {
propJson: {
Expand All @@ -180,6 +180,43 @@ test.describe('pre-request UI tests', async () => {
},
},
},
{
name: 'insomnia.request manipulation',
preReqScript: `
const { Header } = require('insomnia-collection');
insomnia.request.method = 'GET';
insomnia.request.url.addQueryParams('k1=v1');
insomnia.request.headers.add(new Header({
key: 'Content-Type',
value: 'text/plain'
}));
insomnia.request.headers.add(new Header({
key: 'X-Hello',
value: 'hello'
}));
insomnia.request.body.update({
mode: 'raw',
raw: 'rawContent',
});
insomnia.request.auth.update(
{
type: 'bearer',
bearer: [
{key: 'token', value: 'tokenValue'},
],
},
'bearer'
);
// insomnia.request.proxy.update({}); // TODO: enable proxy and test it
// insomnia.request.certificate.update({});
`,
body: '{}',
customVerify: (bodyJson: any) => {
expect(bodyJson.method).toEqual('GET');
expect(bodyJson.headers['x-hello']).toEqual('hello');
expect(bodyJson.data).toEqual('rawContent');
},
},
];

for (let i = 0; i < testCases.length; i++) {
Expand Down Expand Up @@ -220,8 +257,14 @@ test.describe('pre-request UI tests', async () => {
const rows = await responseBody.allInnerTexts();
expect(rows.length).toBeGreaterThan(0);

const bodyJson = JSON.parse(rows.join('\n'));
expect(bodyJson.data).toEqual(tc.expectedBody);
const bodyJson = JSON.parse(rows.join(' '));

if (tc.expectedBody) {
expect(JSON.parse(bodyJson.data)).toEqual(tc.expectedBody);
}
if (tc.customVerify) {
tc.customVerify(bodyJson);
}
});
}
});
2 changes: 1 addition & 1 deletion packages/insomnia/src/hidden-window-preload.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { contextBridge, ipcRenderer, IpcRendererEvent } from 'electron';

import * as CollectionModule from './sdk/objects';
import { RequestContext } from './sdk/objects/insomnia';
import { RequestContext } from './sdk/objects/interfaces';

const bridge: Window['bridge'] = {
onmessage: listener => {
Expand Down
6 changes: 5 additions & 1 deletion packages/insomnia/src/hidden-window.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { initInsomniaObject, RequestContext } from './sdk/objects/insomnia';
import { initInsomniaObject } from './sdk/objects/insomnia';
import { RequestContext } from './sdk/objects/interfaces';
import { mergeRequests } from './sdk/objects/request';

export interface HiddenBrowserWindowBridgeAPI {
runPreRequestScript: (options: { script: string; context: RequestContext }) => Promise<RequestContext>;
Expand Down Expand Up @@ -50,6 +52,7 @@ const runPreRequestScript = async (
consoleInterceptor
);
const mutatedContextObject = mutatedInsomniaObject.toObject();
const updatedRequest = mergeRequests(context.request, mutatedContextObject.request);

await window.bridge.requireInterceptor('fs').promises.writeFile(context.timelinePath, log.join('\n'));

Expand All @@ -60,5 +63,6 @@ const runPreRequestScript = async (
...context,
environment: mutatedContextObject.environment,
baseEnvironment: mutatedContextObject.baseEnvironment,
request: updatedRequest,
};
};
2 changes: 1 addition & 1 deletion packages/insomnia/src/network/cancellation.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { CurlRequestOptions, CurlRequestOutput } from '../main/network/libcurl-promise';
import { Request } from '../models/request';
import { RequestContext } from '../sdk/objects/insomnia';
import { RequestContext } from '../sdk/objects/interfaces';

const cancelRequestFunctionMap = new Map<string, () => void>();
export async function cancelRequestById(requestId: string) {
Expand Down
Loading
Loading