Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
chore: adopt more modern new() csharp syntax in codegen (#37391)
Max Schmitt14d2c4a2bb26
diff --git a/packages/playwright-core/src/server/codegen/csharp.ts b/packages/playwright-core/src/server/codegen/csharp.tsindex 0929f06d03..32fb598cff 100644--- a/packages/playwright-core/src/server/codegen/csharp.ts+++ b/packages/playwright-core/src/server/codegen/csharp.ts@@ -126,11 +126,11 @@ export class CSharpLanguageGenerator implements LanguageGenerator {const options = toClickOptionsForSourceCode(action);if (!Object.entries(options).length)return `await ${subject}.${this._asLocator(action.selector)}.${method}Async();`;- const optionsString = formatObject(options, ' ', 'Locator' + method + 'Options');+ const optionsString = formatObject(options, ' ');return `await ${subject}.${this._asLocator(action.selector)}.${method}Async(${optionsString});`;}case 'hover': {- const optionsString = action.position ? formatObject({ position: action.position }, ' ', 'LocatorHoverOptions') : '';+ const optionsString = action.position ? formatObject({ position: action.position }, ' ') : '';return `await ${subject}.${this._asLocator(action.selector)}.HoverAsync(${optionsString});`;}case 'check':@@ -183,11 +183,11 @@ export class CSharpLanguageGenerator implements LanguageGenerator {using System.Threading.Tasks;using var playwright = await Playwright.CreateAsync();- await using var browser = await playwright.${toPascal(options.browserName)}.LaunchAsync(${formatObject(options.launchOptions, ' ', 'BrowserTypeLaunchOptions')});+ await using var browser = await playwright.${toPascal(options.browserName)}.LaunchAsync(${formatObject(options.launchOptions, ' ')});var context = await browser.NewContextAsync(${formatContextOptions(options.contextOptions, options.deviceName)});`);if (options.contextOptions.recordHar) {const url = options.contextOptions.recordHar.urlFilter;- formatter.add(` await context.RouteFromHARAsync(${quote(options.contextOptions.recordHar.path)}${url ? `, ${formatObject({ url }, ' ', 'BrowserContextRouteFromHAROptions')}` : ''});`);+ formatter.add(` await context.RouteFromHARAsync(${quote(options.contextOptions.recordHar.path)}${url ? `, ${formatObject({ url }, ' ')}` : ''});`);}formatter.newLine();return formatter.format();@@ -216,14 +216,14 @@ export class CSharpLanguageGenerator implements LanguageGenerator {{`);if (options.contextOptions.recordHar) {const url = options.contextOptions.recordHar.urlFilter;- formatter.add(` await Context.RouteFromHARAsync(${quote(options.contextOptions.recordHar.path)}${url ? `, ${formatObject({ url }, ' ', 'BrowserContextRouteFromHAROptions')}` : ''});`);+ formatter.add(` await Context.RouteFromHARAsync(${quote(options.contextOptions.recordHar.path)}${url ? `, ${formatObject({ url }, ' ')}` : ''});`);}return formatter.format();}generateFooter(saveStorage: string | undefined): string {const offset = this._mode === 'library' ? '' : ' ';- let storageStateLine = saveStorage ? `\n${offset}await context.StorageStateAsync(new BrowserContextStorageStateOptions\n${offset}{\n${offset} Path = ${quote(saveStorage)}\n${offset}});\n` : '';+ let storageStateLine = saveStorage ? `\n${offset}await context.StorageStateAsync(new()\n${offset}{\n${offset} Path = ${quote(saveStorage)}\n${offset}});\n` : '';if (this._mode !== 'library')storageStateLine += ` }\n}\n`;return storageStateLine;@@ -232,8 +232,8 @@ export class CSharpLanguageGenerator implements LanguageGenerator {function formatObject(value: any, indent = ' ', name = ''): string {if (typeof value === 'string') {- if (['permissions', 'colorScheme', 'modifiers', 'button', 'recordHarContent', 'recordHarMode', 'serviceWorkers'].includes(name))- return `${getClassName(name)}.${toPascal(value)}`;+ if (['colorScheme', 'modifiers', 'button', 'recordHarContent', 'recordHarMode', 'serviceWorkers'].includes(name))+ return `${getEnumName(name)}.${toPascal(value)}`;return quote(value);}if (Array.isArray(value))@@ -241,15 +241,13 @@ function formatObject(value: any, indent = ' ', name = ''): string {if (typeof value === 'object') {const keys = Object.keys(value).filter(key => value[key] !== undefined).sort();if (!keys.length)- return name ? `new ${getClassName(name)}` : '';+ return `new()`;const tokens: string[] = [];for (const key of keys) {const property = getPropertyName(key);tokens.push(`${property} = ${formatObject(value[key], indent, key)},`);}- if (name)- return `new ${getClassName(name)}\n{\n${indent}${tokens.join(`\n${indent}`)}\n${indent}}`;- return `{\n${indent}${tokens.join(`\n${indent}`)}\n${indent}}`;+ return `new()\n{\n${indent}${tokens.join(`\n${indent}`)}\n${indent}}`;}if (name === 'latitude' || name === 'longitude')return String(value) + 'm';@@ -257,11 +255,8 @@ function formatObject(value: any, indent = ' ', name = ''): string {return String(value);}-function getClassName(value: string): string {+function getEnumName(value: string): string {switch (value) {- case 'viewport': return 'ViewportSize';- case 'proxy': return 'ProxySettings';- case 'permissions': return 'ContextPermission';case 'modifiers': return 'KeyboardModifier';case 'button': return 'MouseButton';case 'recordHarMode': return 'HarMode';@@ -284,21 +279,22 @@ function toPascal(value: string): string {}function formatContextOptions(contextOptions: BrowserContextOptions, deviceName: string | undefined): string {- let options = { ...contextOptions };+ const 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(options, ' ', 'BrowserNewContextOptions');+ return formatObject(options, ' ');}- options = sanitizeDeviceOptions(device, options);- if (!Object.entries(options).length)+ // NOTE: If options are the same as in the device, we just use the device.+ if (!Object.entries(sanitizeDeviceOptions(device, options)).length)return `playwright.Devices[${quote(deviceName!)}]`;-- return formatObject(options, ' ', `BrowserNewContextOptions(playwright.Devices[${quote(deviceName!)}])`);+ // NOTE: In csharp there is no easy way to merge options, so we just expand everything.+ delete (options as any)['defaultBrowserType'];+ return formatObject(options, ' ');}class CSharpFormatter {diff --git a/tests/library/inspector/cli-codegen-1.spec.ts b/tests/library/inspector/cli-codegen-1.spec.tsindex 92d65851a8..b693a08401 100644--- a/tests/library/inspector/cli-codegen-1.spec.ts+++ b/tests/library/inspector/cli-codegen-1.spec.ts@@ -238,9 +238,9 @@ await page.GetByRole(AriaRole.Button, new() { Name = "Submit" }).DblClickAsync().setPosition(250, 250));`);expect(sources.get('C#')!.text).toContain(`-await page.Locator("canvas").ClickAsync(new LocatorClickOptions+await page.Locator("canvas").ClickAsync(new(){- Position = new Position+ Position = new(){X = 250,Y = 250,@@ -975,7 +975,7 @@ await page.GetByRole(AriaRole.Textbox).FillAsync("h");`);.setButton(MouseButton.MIDDLE));`);expect(sources.get('C#')!.text).toContain(`-await page.GetByText("Click me").ClickAsync(new LocatorClickOptions+await page.GetByText("Click me").ClickAsync(new(){Button = MouseButton.Middle,});`);diff --git a/tests/library/inspector/cli-codegen-csharp.spec.ts b/tests/library/inspector/cli-codegen-csharp.spec.tsindex 3bf45f3f5f..c38488f68a 100644--- a/tests/library/inspector/cli-codegen-csharp.spec.ts+++ b/tests/library/inspector/cli-codegen-csharp.spec.ts@@ -32,7 +32,7 @@ using System;using System.Threading.Tasks;using var playwright = await Playwright.CreateAsync();-await using var browser = await playwright.${capitalize(browserName)}.LaunchAsync(new BrowserTypeLaunchOptions+await using var browser = await playwright.${capitalize(browserName)}.LaunchAsync(new(){${launchOptions(channel)}});@@ -54,27 +54,27 @@ test('should print the correct context options for custom settings', async ({ brserver.EMPTY_PAGE]);const expectedResult = `using var playwright = await Playwright.CreateAsync();-await using var browser = await playwright.${capitalize(browserName)}.LaunchAsync(new BrowserTypeLaunchOptions+await using var browser = await playwright.${capitalize(browserName)}.LaunchAsync(new(){${launchOptions(channel)}- Proxy = new ProxySettings+ Proxy = new(){Server = "${proxyServer.HOST}",},});-var context = await browser.NewContextAsync(new BrowserNewContextOptions+var context = await browser.NewContextAsync(new(){ColorScheme = ColorScheme.Dark,- Geolocation = new Geolocation+ Geolocation = new(){Latitude = 37.819722m,Longitude = -122.478611m,},Locale = "es",- Permissions = new[] { ContextPermission.Geolocation },+ Permissions = new[] { "geolocation" },TimezoneId = "Europe/Rome",UserAgent = "hardkodemium",- ViewportSize = new ViewportSize+ ViewportSize = new(){Height = 720,Width = 1280,@@ -89,7 +89,7 @@ test('should print the correct context options when using a device', async ({ brconst cli = runCLI(['--device=Pixel 2', '--target=csharp', server.EMPTY_PAGE]);const expectedResult = `using var playwright = await Playwright.CreateAsync();-await using var browser = await playwright.${capitalize(browserName)}.LaunchAsync(new BrowserTypeLaunchOptions+await using var browser = await playwright.${capitalize(browserName)}.LaunchAsync(new(){${launchOptions(channel)}});@@ -114,27 +114,34 @@ test('should print the correct context options when using a device and additionaserver.EMPTY_PAGE]);const expectedResult = `using var playwright = await Playwright.CreateAsync();-await using var browser = await playwright.${capitalize(browserName)}.LaunchAsync(new BrowserTypeLaunchOptions+await using var browser = await playwright.${capitalize(browserName)}.LaunchAsync(new(){${launchOptions(channel)}- Proxy = new ProxySettings+ Proxy = new(){Server = "${proxyServer.HOST}",},});-var context = await browser.NewContextAsync(new BrowserNewContextOptions(playwright.Devices["iPhone 11"])+var context = await browser.NewContextAsync(new(){ColorScheme = ColorScheme.Dark,- Geolocation = new Geolocation+ Geolocation = new(){Latitude = 37.819722m,Longitude = -122.478611m,- },+ },${process.platform === 'linux' && browserName === 'webkit' ? '' : `+ HasTouch = true,+ IsMobile = true,`}Locale = "es",- Permissions = new[] { ContextPermission.Geolocation },+ Permissions = new[] { "geolocation" },+ Screen = new()+ {+ Height = 896,+ Width = 414,+ },TimezoneId = "Europe/Rome",UserAgent = "hardkodemium",- ViewportSize = new ViewportSize+ ViewportSize = new(){Height = 720,Width = 1280,@@ -150,17 +157,17 @@ test('should print load/save storageState', async ({ browserName, channel, runCLconst cli = runCLI([`--load-storage=${loadFileName}`, `--save-storage=${saveFileName}`, '--target=csharp', server.EMPTY_PAGE]);const expectedResult1 = `using var playwright = await Playwright.CreateAsync();-await using var browser = await playwright.${capitalize(browserName)}.LaunchAsync(new BrowserTypeLaunchOptions+await using var browser = await playwright.${capitalize(browserName)}.LaunchAsync(new(){${launchOptions(channel)}});-var context = await browser.NewContextAsync(new BrowserNewContextOptions+var context = await browser.NewContextAsync(new(){StorageStatePath = "${loadFileName.replace(/\\/g, '\\\\')}",});`;await cli.waitFor(expectedResult1);const expectedResult2 = `-await context.StorageStateAsync(new BrowserContextStorageStateOptions+await context.StorageStateAsync(new(){Path = "${saveFileName.replace(/\\/g, '\\\\')}"});@@ -180,7 +187,7 @@ test('should work with --save-har', async ({ runCLI }, testInfo) => {test('should work with --save-har and --save-har-glob', async ({ runCLI }, testInfo) => {const harFileName = testInfo.outputPath('har.har');- const expectedResult = `await context.RouteFromHARAsync(${JSON.stringify(harFileName)}, new BrowserContextRouteFromHAROptions+ const expectedResult = `await context.RouteFromHARAsync(${JSON.stringify(harFileName)}, new(){Url = "**/*.js",});`;@@ -203,7 +210,7 @@ for (const testFramework of ['nunit', 'mstest'] as const) {await cli.waitFor(`Page.GotoAsync("${server.EMPTY_PAGE}")`);expect(await cli.text()).toContain(` public override BrowserNewContextOptions ContextOptions(){- return new BrowserNewContextOptions+ return new(){ColorScheme = ColorScheme.Dark,};@@ -223,7 +230,7 @@ for (const testFramework of ['nunit', 'mstest'] as const) {test(`should work with --save-har and --save-har-glob in ${testFramework}`, async ({ runCLI }, testInfo) => {const harFileName = testInfo.outputPath('har.har');- const expectedResult = `await Context.RouteFromHARAsync(${JSON.stringify(harFileName)}, new BrowserContextRouteFromHAROptions+ const expectedResult = `await Context.RouteFromHARAsync(${JSON.stringify(harFileName)}, new(){Url = "**/*.js",});`;@@ -246,7 +253,7 @@ public class Tests : PageTest{public override BrowserNewContextOptions ContextOptions(){- return new BrowserNewContextOptions+ return new(){ColorScheme = ColorScheme.Dark,};@@ -273,7 +280,7 @@ public class Tests : PageTest{public override BrowserNewContextOptions ContextOptions(){- return new BrowserNewContextOptions+ return new(){ColorScheme = ColorScheme.Dark,};