Skip to content

Commit

Permalink
fix: support generating values with faker.js in scripting (#7454)
Browse files Browse the repository at this point in the history
* fix: support generating values with faker.js in scripting

* fix: relax timeout for one case and remove a duplicated case

* fix: test is flaky because of timeout

* fix: incorrect test selector

* fix: waiting before checking

* fix: replace clicking with assertion

* fix: relax the external timeout a bit
  • Loading branch information
ihexxa authored May 28, 2024
1 parent 9f0bd8b commit 5d08381
Show file tree
Hide file tree
Showing 4 changed files with 77 additions and 41 deletions.
24 changes: 24 additions & 0 deletions packages/insomnia-sdk/src/objects/__tests__/environments.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { describe, expect, it } from '@jest/globals';
import { validate } from 'uuid';

import { Environment, Variables } from '../environments';

describe('test Variables object', () => {
it('test basic operations', () => {
const variables = new Variables({
globals: new Environment('globals', { value: '777' }),
environment: new Environment('environments', {}),
collection: new Environment('baseEnvironment', {}),
data: new Environment('iterationData', {}),
});

const uuidAnd777 = variables.replaceIn('{{ $randomUUID }}{{value }}');
expect(validate(uuidAnd777.replace('777', ''))).toBeTruthy();

const uuidAndBrackets1 = variables.replaceIn('{{ $randomUUID }}}}');
expect(validate(uuidAndBrackets1.replace('}}', ''))).toBeTruthy();

const uuidAndBrackets2 = variables.replaceIn('}}{{ $randomUUID }}');
expect(validate(uuidAndBrackets2.replace('}}', ''))).toBeTruthy();
});
});
38 changes: 37 additions & 1 deletion packages/insomnia-sdk/src/objects/interpolator.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { fakerFunctions } from 'insomnia/src/ui/components/templating/faker-functions';
import { configure, type ConfigureOptions, type Environment as NunjuncksEnv } from 'nunjucks';

class Intepolator {
Expand All @@ -10,7 +11,42 @@ class Intepolator {
render = (template: string, context: object) => {
// TODO: handle timeout
// TODO: support plugin?
return this.engine.renderString(template, context);
return this.engine.renderString(
this.renderWithFaker(template),
context
);
};

renderWithFaker = (template: string) => {
const segments = template.split('}}');
if (segments.length === 1) {
return template;
}

const translatedSegments = segments.map(segment => {
const tagStart = segment.lastIndexOf('{{');
if ((tagStart) < 0) {
return segment;
}

const tagName = segment
.slice(tagStart + 2)
.trim();
if (!tagName.startsWith('$')) {
// it is a tag probably for interpolating, at least not for generating
return segment + '}}';
}
const funcName = tagName.slice(1) as keyof typeof fakerFunctions; // remove prefix '$'

if (!fakerFunctions[funcName]) {
throw Error(`replaceIn: no faker function is found: ${funcName}`);
};

const generated = fakerFunctions[funcName]();
return segment.slice(0, tagStart) + generated;
});

return translatedSegments.join('');
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,15 +51,25 @@ test.describe('test hidden window handling', async () => {
await page.getByLabel('Request Collection').getByTestId('Long running task').press('Enter');
await page.getByTestId('request-pane').getByRole('button', { name: 'Send', exact: true }).click();

await page.getByText('Timeout: Running script took too long').click();
await page.waitForSelector('[data-testid="response-status-tag"]:visible');

expect(await page.locator('.pane-two pre').innerText()).toEqual('Timeout: Running script took too long');
await page.getByRole('tab', { name: 'Timeline' }).click();
await page.getByRole('tab', { name: 'Preview ' }).click();
const windows = await app.windows();
const hiddenWindow = windows[1];
hiddenWindow.close();
await page.getByRole('button', { name: 'Send', exact: true }).click();
// as the hidden window is restarted, it should not show "Timeout: Hidden browser window is not responding"
await page.getByText('Timeout: Running script took too long').click();

await page.getByTestId('settings-button').click();
await page.getByLabel('Request timeout (ms)').fill('6000');
await page.getByRole('button', { name: '' }).click();

await page.getByTestId('request-pane').getByRole('button', { name: 'Send' }).click();

// it should still work
const statusTag = page.locator('[data-testid="response-status-tag"]:visible');
await page.waitForSelector('[data-testid="response-status-tag"]:visible');
await expect(statusTag).toContainText('200 OK');
});

test('window should be restarted if it hangs', async ({ app, page }) => {
Expand All @@ -77,7 +87,7 @@ test.describe('test hidden window handling', async () => {

// update timeout
await page.getByTestId('settings-button').click();
await page.getByLabel('Request timeout (ms)').fill('100');
await page.getByLabel('Request timeout (ms)').fill('1000');
await page.getByRole('button', { name: '' }).click();

// send the request with infinite loop script
Expand All @@ -96,37 +106,3 @@ test.describe('test hidden window handling', async () => {
await expect(statusTag).toContainText('200 OK');
});
});

test('window should be restarted if it hangs', async ({ app, page }) => {
test.slow(process.platform === 'darwin' || process.platform === 'win32', 'Slow app start on these platforms');

// load collection
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();
await page.getByRole('menuitemradio', { name: 'Import' }).click();
await page.locator('[data-test-id="import-from-clipboard"]').click();
await page.getByRole('button', { name: 'Scan' }).click();
await page.getByRole('dialog').getByRole('button', { name: 'Import' }).click();

// update timeout
await page.getByTestId('settings-button').click();
await page.getByLabel('Request timeout (ms)').fill('100');
await page.getByRole('button', { name: '' }).click();

// send the request with infinite loop script
await page.getByText('Pre-request Scripts').click();
await page.getByLabel('Request Collection').getByTestId('infinite loop').press('Enter');
await page.getByTestId('request-pane').getByRole('button', { name: 'Send', exact: true }).click();
await page.getByText('Timeout: Hidden browser window is not responding').click();

// send the another script with normal script
await page.getByLabel('Request Collection').getByTestId('simple log').press('Enter');
await page.getByTestId('request-pane').getByRole('button', { name: 'Send', exact: true }).click();

// it should still work
const statusTag = page.locator('[data-testid="response-status-tag"]:visible');
await page.waitForSelector('[data-testid="response-status-tag"]:visible');
await expect(statusTag).toContainText('200 OK');
});
2 changes: 1 addition & 1 deletion packages/insomnia/src/network/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ export const tryToExecuteScript = async (context: RequestAndContextAndOptionalRe
reject(new Error('Timeout: Hidden browser window is not responding'));
// Add one extra second to ensure the hidden browser window has had a chance to return its timeout
// TODO: restart the hidden browser window
}, timeout + 1000);
}, timeout + 2000);
});
// const isBaseEnvironmentSelected = environment._id === baseEnvironment._id;
// if (isBaseEnvironmentSelected) {
Expand Down

0 comments on commit 5d08381

Please sign in to comment.