Skip to content

Commit

Permalink
fix(codegen): generate routeFromHAR for --save-har option (#33480)
Browse files Browse the repository at this point in the history
  • Loading branch information
yury-s authored Nov 11, 2024
1 parent e3ed9fa commit e691ca7
Show file tree
Hide file tree
Showing 8 changed files with 55 additions and 59 deletions.
26 changes: 10 additions & 16 deletions packages/playwright-core/src/server/codegen/csharp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,8 @@ export class CSharpLanguageGenerator implements LanguageGenerator {
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.${toPascal(options.browserName)}.LaunchAsync(${formatObject(options.launchOptions, ' ', 'BrowserTypeLaunchOptions')});
var context = await browser.NewContextAsync(${formatContextOptions(options.contextOptions, options.deviceName)});`);
if (options.contextOptions.recordHar)
formatter.add(` await context.RouteFromHARAsync(${quote(options.contextOptions.recordHar.path)});`);
formatter.newLine();
return formatter.format();
}
Expand All @@ -196,6 +198,8 @@ export class CSharpLanguageGenerator implements LanguageGenerator {
formatter.add(` [${this._mode === 'nunit' ? 'Test' : 'TestMethod'}]
public async Task MyTest()
{`);
if (options.contextOptions.recordHar)
formatter.add(` await context.RouteFromHARAsync(${quote(options.contextOptions.recordHar.path)});`);
return formatter.format();
}

Expand Down Expand Up @@ -261,32 +265,22 @@ function toPascal(value: string): string {
return value[0].toUpperCase() + value.slice(1);
}

function convertContextOptions(options: BrowserContextOptions): any {
const result: any = { ...options };
if (options.recordHar) {
result['recordHarPath'] = options.recordHar.path;
result['recordHarContent'] = options.recordHar.content;
result['recordHarMode'] = options.recordHar.mode;
result['recordHarOmitContent'] = options.recordHar.omitContent;
result['recordHarUrlFilter'] = options.recordHar.urlFilter;
delete result.recordHar;
}
return result;
}

function formatContextOptions(options: BrowserContextOptions, deviceName: string | undefined): string {
function formatContextOptions(contextOptions: BrowserContextOptions, deviceName: string | undefined): string {
let options = { ...contextOptions };
// recordHAR is replaced with routeFromHAR in the generated code.
delete options.recordHar;
const device = deviceName && deviceDescriptors[deviceName];
if (!device) {
if (!Object.entries(options).length)
return '';
return formatObject(convertContextOptions(options), ' ', 'BrowserNewContextOptions');
return formatObject(options, ' ', 'BrowserNewContextOptions');
}

options = sanitizeDeviceOptions(device, options);
if (!Object.entries(options).length)
return `playwright.Devices[${quote(deviceName!)}]`;

return formatObject(convertContextOptions(options), ' ', `BrowserNewContextOptions(playwright.Devices[${quote(deviceName!)}])`);
return formatObject(options, ' ', `BrowserNewContextOptions(playwright.Devices[${quote(deviceName!)}])`);
}

class CSharpFormatter {
Expand Down
12 changes: 2 additions & 10 deletions packages/playwright-core/src/server/codegen/java.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,8 @@ export class JavaLanguageGenerator implements LanguageGenerator {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.${options.browserName}().launch(${formatLaunchOptions(options.launchOptions)});
BrowserContext context = browser.newContext(${formatContextOptions(options.contextOptions, options.deviceName)});`);
if (options.contextOptions.recordHar)
formatter.add(` context.routeFromHAR(${quote(options.contextOptions.recordHar.path)});`);
return formatter.format();
}

Expand Down Expand Up @@ -240,16 +242,6 @@ function formatContextOptions(contextOptions: BrowserContextOptions, deviceName:
lines.push(` .setLocale(${quote(options.locale)})`);
if (options.proxy)
lines.push(` .setProxy(new Proxy(${quote(options.proxy.server)}))`);
if (options.recordHar?.content)
lines.push(` .setRecordHarContent(HarContentPolicy.${options.recordHar?.content.toUpperCase()})`);
if (options.recordHar?.mode)
lines.push(` .setRecordHarMode(HarMode.${options.recordHar?.mode.toUpperCase()})`);
if (options.recordHar?.omitContent)
lines.push(` .setRecordHarOmitContent(true)`);
if (options.recordHar?.path)
lines.push(` .setRecordHarPath(Paths.get(${quote(options.recordHar.path)}))`);
if (options.recordHar?.urlFilter)
lines.push(` .setRecordHarUrlFilter(${quote(options.recordHar.urlFilter as string)})`);
if (options.serviceWorkers)
lines.push(` .setServiceWorkers(ServiceWorkerPolicy.${options.serviceWorkers.toUpperCase()})`);
if (options.storageState)
Expand Down
10 changes: 6 additions & 4 deletions packages/playwright-core/src/server/codegen/javascript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,8 @@ export class JavaScriptLanguageGenerator implements LanguageGenerator {
import { test, expect${options.deviceName ? ', devices' : ''} } from '@playwright/test';
${useText ? '\ntest.use(' + useText + ');\n' : ''}
test('test', async ({ page }) => {`);
if (options.contextOptions.recordHar)
formatter.add(` await page.routeFromHAR(${quote(options.contextOptions.recordHar.path)});`);
return formatter.format();
}

Expand All @@ -160,6 +162,8 @@ ${useText ? '\ntest.use(' + useText + ');\n' : ''}
(async () => {
const browser = await ${options.browserName}.launch(${formatObjectOrVoid(options.launchOptions)});
const context = await browser.newContext(${formatContextOptions(options.contextOptions, options.deviceName, false)});`);
if (options.contextOptions.recordHar)
formatter.add(` await context.routeFromHAR(${quote(options.contextOptions.recordHar.path)});`);
return formatter.format();
}

Expand Down Expand Up @@ -203,10 +207,8 @@ function formatObjectOrVoid(value: any, indent = ' '): string {

function formatContextOptions(options: BrowserContextOptions, deviceName: string | undefined, isTest: boolean): string {
const device = deviceName && deviceDescriptors[deviceName];
if (isTest) {
// No recordHAR fixture in test.
options = { ...options, recordHar: undefined };
}
// recordHAR is replaced with routeFromHAR in the generated code.
options = { ...options, recordHar: undefined };
if (!device)
return formatObjectOrVoid(options);
// Filter out all the properties from the device descriptor.
Expand Down
25 changes: 10 additions & 15 deletions packages/playwright-core/src/server/codegen/python.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,8 @@ from playwright.sync_api import Page, expect
${fixture}
def test_example(page: Page) -> None {`);
if (options.contextOptions.recordHar)
formatter.add(` page.route_from_har(${quote(options.contextOptions.recordHar.path)})`);
} else if (this._isAsync) {
formatter.add(`
import asyncio
Expand All @@ -161,6 +163,8 @@ from playwright.async_api import Playwright, async_playwright, expect
async def run(playwright: Playwright) -> None {
browser = await playwright.${options.browserName}.launch(${formatOptions(options.launchOptions, false)})
context = await browser.new_context(${formatContextOptions(options.contextOptions, options.deviceName)})`);
if (options.contextOptions.recordHar)
formatter.add(` await page.route_from_har(${quote(options.contextOptions.recordHar.path)})`);
} else {
formatter.add(`
import re
Expand All @@ -170,6 +174,8 @@ from playwright.sync_api import Playwright, sync_playwright, expect
def run(playwright: Playwright) -> None {
browser = playwright.${options.browserName}.launch(${formatOptions(options.launchOptions, false)})
context = browser.new_context(${formatContextOptions(options.contextOptions, options.deviceName)})`);
if (options.contextOptions.recordHar)
formatter.add(` context.route_from_har(${quote(options.contextOptions.recordHar.path)})`);
}
return formatter.format();
}
Expand Down Expand Up @@ -232,24 +238,13 @@ function formatOptions(value: any, hasArguments: boolean, asDict?: boolean): str
}).join(', ');
}

function convertContextOptions(options: BrowserContextOptions): any {
const result: any = { ...options };
if (options.recordHar) {
result['record_har_path'] = options.recordHar.path;
result['record_har_content'] = options.recordHar.content;
result['record_har_mode'] = options.recordHar.mode;
result['record_har_omit_content'] = options.recordHar.omitContent;
result['record_har_url_filter'] = options.recordHar.urlFilter;
delete result.recordHar;
}
return result;
}

function formatContextOptions(options: BrowserContextOptions, deviceName: string | undefined, asDict?: boolean): string {
// recordHAR is replaced with routeFromHAR in the generated code.
options = { ...options, recordHar: undefined };
const device = deviceName && deviceDescriptors[deviceName];
if (!device)
return formatOptions(convertContextOptions(options), false, asDict);
return `**playwright.devices[${quote(deviceName!)}]` + formatOptions(convertContextOptions(sanitizeDeviceOptions(device, options)), true, asDict);
return formatOptions(options, false, asDict);
return `**playwright.devices[${quote(deviceName!)}]` + formatOptions(sanitizeDeviceOptions(device, options), true, asDict);
}

class PythonFormatter {
Expand Down
19 changes: 12 additions & 7 deletions tests/library/inspector/cli-codegen-csharp.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,13 +170,7 @@ await context.StorageStateAsync(new BrowserContextStorageStateOptions

test('should work with --save-har', async ({ runCLI }, testInfo) => {
const harFileName = testInfo.outputPath('har.har');
const expectedResult = `
var context = await browser.NewContextAsync(new BrowserNewContextOptions
{
RecordHarMode = HarMode.Minimal,
RecordHarPath = ${JSON.stringify(harFileName)},
ServiceWorkers = ServiceWorkerPolicy.Block,
});`;
const expectedResult = `await context.RouteFromHARAsync(${JSON.stringify(harFileName)});`;
const cli = runCLI(['--target=csharp', `--save-har=${harFileName}`], {
autoExitWhen: expectedResult,
});
Expand Down Expand Up @@ -204,6 +198,17 @@ for (const testFramework of ['nunit', 'mstest'] as const) {
}
`);
});

test(`should work with --save-har in ${testFramework}`, async ({ runCLI }, testInfo) => {
const harFileName = testInfo.outputPath('har.har');
const expectedResult = `await context.RouteFromHARAsync("${harFileName}");`;
const cli = runCLI([`--target=csharp-${testFramework}`, `--save-har=${harFileName}`], {
autoExitWhen: expectedResult,
});
await cli.waitForCleanExit();
const json = JSON.parse(fs.readFileSync(harFileName, 'utf-8'));
expect(json.log.creator.name).toBe('Playwright');
});
}

test(`should print a valid basic program in mstest`, async ({ runCLI }) => {
Expand Down
5 changes: 1 addition & 4 deletions tests/library/inspector/cli-codegen-java.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,7 @@ test('should print load/save storage_state', async ({ runCLI, browserName }, tes

test('should work with --save-har', async ({ runCLI }, testInfo) => {
const harFileName = testInfo.outputPath('har.har');
const expectedResult = `BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.setRecordHarMode(HarMode.MINIMAL)
.setRecordHarPath(Paths.get(${JSON.stringify(harFileName)}))
.setServiceWorkers(ServiceWorkerPolicy.BLOCK));`;
const expectedResult = `context.routeFromHAR(${JSON.stringify(harFileName)});`;
const cli = runCLI(['--target=java', `--save-har=${harFileName}`], {
autoExitWhen: expectedResult,
});
Expand Down
2 changes: 1 addition & 1 deletion tests/library/inspector/cli-codegen-python-async.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ asyncio.run(main())

test('should work with --save-har', async ({ runCLI }, testInfo) => {
const harFileName = testInfo.outputPath('har.har');
const expectedResult = `context = await browser.new_context(record_har_mode="minimal", record_har_path=${JSON.stringify(harFileName)}, service_workers="block")`;
const expectedResult = `await page.route_from_har(${JSON.stringify(harFileName)})`;
const cli = runCLI(['--target=python-async', `--save-har=${harFileName}`], {
autoExitWhen: expectedResult,
});
Expand Down
15 changes: 13 additions & 2 deletions tests/library/inspector/cli-codegen-test.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,19 @@ test('test', async ({ page }) => {`;

test('should not generate recordHAR with --save-har', async ({ runCLI }, testInfo) => {
const harFileName = testInfo.outputPath('har.har');
const expectedResult = `test.use({
serviceWorkers: 'block'
const expectedResult = ` await page.routeFromHAR('${harFileName.replace(/\\/g, '\\\\')}');`;
const cli = runCLI(['--target=playwright-test', `--save-har=${harFileName}`], {
autoExitWhen: expectedResult,
});
await cli.waitForCleanExit();
const json = JSON.parse(fs.readFileSync(harFileName, 'utf-8'));
expect(json.log.creator.name).toBe('Playwright');
});

test('should generate routeFromHAR with --save-har', async ({ runCLI }, testInfo) => {
const harFileName = testInfo.outputPath('har.har');
const expectedResult = `test('test', async ({ page }) => {
await page.routeFromHAR('${harFileName.replace(/\\/g, '\\\\')}');
});`;
const cli = runCLI(['--target=playwright-test', `--save-har=${harFileName}`], {
autoExitWhen: expectedResult,
Expand Down

0 comments on commit e691ca7

Please sign in to comment.