Skip to content

chore: pick right launch options for codegen #624

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

Merged
merged 11 commits into from
Apr 29, 2025
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
80 changes: 70 additions & 10 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
* limitations under the License.
*/

import fs from 'fs';
import path from 'path';
import StackUtils from 'stack-utils';
import { DebugHighlight } from './debugHighlight';
Expand All @@ -22,13 +23,13 @@ import * as reporterTypes from './upstream/reporter';
import { ReusedBrowser } from './reusedBrowser';
import { SettingsModel } from './settingsModel';
import { SettingsView } from './settingsView';
import { TestModel, TestModelCollection } from './testModel';
import { TestModel, TestModelCollection, TestProject } from './testModel';
import { configError, disabledProjectName as disabledProject, TestTree } from './testTree';
import { NodeJSNotFoundError, getPlaywrightInfo, stripAnsi, stripBabelFrame, uriToPath } from './utils';
import * as vscodeTypes from './vscodeTypes';
import { WorkspaceChange, WorkspaceObserver } from './workspaceObserver';
import { registerTerminalLinkProvider } from './terminalLinkProvider';
import { ErrorContext, RunHooks, TestConfig } from './playwrightTestTypes';
import { RunHooks, TestConfig, ErrorContext } from './playwrightTestTypes';
import { ansi2html } from './ansi2html';
import { LocatorsView } from './locatorsView';

Expand Down Expand Up @@ -185,18 +186,34 @@ export class Extension implements RunHooks {
this._reusedBrowser.closeAllBrowsers();
}),
vscode.commands.registerCommand('pw.extension.command.recordNew', async () => {
if (!this._models.hasEnabledModels()) {
await vscode.window.showWarningMessage(messageNoPlaywrightTestsFound);
const model = this._models.selectedModel();
if (!model)
return vscode.window.showWarningMessage(messageNoPlaywrightTestsFound);

const project = model.enabledProjects()[0];
if (!project)
return vscode.window.showWarningMessage(this._vscode.l10n.t(`Project is disabled in the Playwright sidebar.`));

const file = await this._createFileForNewTest(model, project);
if (!file)
return;


const showBrowser = this._settingsModel.showBrowser.get() ?? false;
try {
await this._settingsModel.showBrowser.set(true);
await this._showBrowserForRecording(file, project);
await this._reusedBrowser.record(model);
} finally {
await this._settingsModel.showBrowser.set(showBrowser);
}
await this._reusedBrowser.record(this._models, true);
}),
vscode.commands.registerCommand('pw.extension.command.recordAtCursor', async () => {
if (!this._models.hasEnabledModels()) {
await vscode.window.showWarningMessage(messageNoPlaywrightTestsFound);
return;
}
await this._reusedBrowser.record(this._models, false);
const model = this._models.selectedModel();
if (!model)
return vscode.window.showWarningMessage(messageNoPlaywrightTestsFound);

await this._reusedBrowser.record(model);
}),
vscode.commands.registerCommand('pw.extension.command.toggleModels', async () => {
this._settingsView.toggleModels();
Expand Down Expand Up @@ -662,6 +679,49 @@ export class Extension implements RunHooks {
await this._queueWatchRun(new this._vscode.TestRunRequest(testItems), 'items');
}

private async _createFileForNewTest(model: TestModel, project: TestProject) {
let file;
for (let i = 1; i < 100; ++i) {
file = path.join(project.project.testDir, `test-${i}.spec.ts`);
if (fs.existsSync(file))
continue;
break;
}
if (!file)
return;

await fs.promises.writeFile(file, `import { test, expect } from '@playwright/test';

test('test', async ({ page }) => {
// Recording...
});`);

await model.handleWorkspaceChange({ created: new Set([file]), changed: new Set(), deleted: new Set() });
await model.ensureTests([file]);

const document = await this._vscode.workspace.openTextDocument(file);
const editor = await this._vscode.window.showTextDocument(document);
editor.selection = new this._vscode.Selection(new this._vscode.Position(3, 2), new this._vscode.Position(3, 2 + '// Recording...'.length));

return file;
}

private async _showBrowserForRecording(file: string, project: TestProject) {
const fileItem = this._testTree.testItemForFile(file);
if (!fileItem)
return;
if (fileItem.children.size !== 1)
return;

const testItems = this._testTree.collectTestsInside(fileItem);
const testForProject = testItems.length === 1 ? testItems[0] : testItems.find(t => t.label === project.name);
if (!testForProject)
return;

const request = new this._vscode.TestRunRequest([testForProject], undefined, undefined, false, true);
await this._queueTestRun(request, 'run');
}

private async _updateVisibleEditorItems() {
const files = this._vscode.window.visibleTextEditors.map(e => uriToPath(e.document.uri));
await this._ensureTestsInAllModels(files);
Expand Down
46 changes: 5 additions & 41 deletions src/reusedBrowser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ import type { TestConfig } from './playwrightTestTypes';
import type { TestModel, TestModelCollection } from './testModel';
import { createGuid } from './utils';
import * as vscodeTypes from './vscodeTypes';
import path from 'path';
import fs from 'fs';
import { installBrowsers } from './installer';
import { SettingsModel } from './settingsModel';
import { BackendServer, BackendClient } from './backend';
Expand Down Expand Up @@ -244,9 +242,8 @@ export class ReusedBrowser implements vscodeTypes.Disposable {
return !this._isRunningTests && !!this._pageCount;
}

async record(models: TestModelCollection, recordNew: boolean) {
const selectedModel = models.selectedModel();
if (!selectedModel || !this._checkVersion(selectedModel.config))
async record(model: TestModel) {
if (!model || !this._checkVersion(model.config))
return;
if (!this.canRecord()) {
void this._vscode.window.showWarningMessage(
Expand All @@ -258,7 +255,7 @@ export class ReusedBrowser implements vscodeTypes.Disposable {
location: this._vscode.ProgressLocation.Notification,
title: 'Playwright codegen',
cancellable: true
}, async (progress, token) => this._doRecord(progress, selectedModel, recordNew, token));
}, async (progress, token) => this._doRecord(progress, model, token));
}

async highlight(selector: string) {
Expand Down Expand Up @@ -297,20 +294,12 @@ export class ReusedBrowser implements vscodeTypes.Disposable {
return true;
}

private async _doRecord(progress: vscodeTypes.Progress<{ message?: string; increment?: number }>, model: TestModel, recordNew: boolean, token: vscodeTypes.CancellationToken) {
const startBackend = this._startBackendIfNeeded(model.config);
if (recordNew)
await this._createFileForNewTest(model);
await startBackend;
private async _doRecord(progress: vscodeTypes.Progress<{ message?: string; increment?: number }>, model: TestModel, token: vscodeTypes.CancellationToken) {
await this._startBackendIfNeeded(model.config);
this._insertedEditActionCount = 0;

progress.report({ message: 'starting\u2026' });

if (recordNew) {
await this._backend?.resetForReuse();
await this._backend?.navigate({ url: 'about:blank' });
}

// Register early to have this._cancelRecording assigned during re-entry.
const canceledPromise = Promise.race([
new Promise<void>(f => token.onCancellationRequested(f)),
Expand Down Expand Up @@ -345,31 +334,6 @@ export class ReusedBrowser implements vscodeTypes.Disposable {
});
}

private async _createFileForNewTest(model: TestModel) {
const project = model.enabledProjects()[0];
if (!project)
return;
let file;
for (let i = 1; i < 100; ++i) {
file = path.join(project.project.testDir, `test-${i}.spec.ts`);
if (fs.existsSync(file))
continue;
break;
}
if (!file)
return;

await fs.promises.writeFile(file, `import { test, expect } from '@playwright/test';

test('test', async ({ page }) => {
// Recording...
});`);

const document = await this._vscode.workspace.openTextDocument(file);
const editor = await this._vscode.window.showTextDocument(document);
editor.selection = new this._vscode.Selection(new this._vscode.Position(3, 2), new this._vscode.Position(3, 2 + '// Recording...'.length));
}

async onWillRunTests(config: TestConfig, debug: boolean) {
if (!this._settingsModel.showBrowser.get() && !debug)
return;
Expand Down
2 changes: 1 addition & 1 deletion src/testModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,7 @@ export class TestModel extends DisposableBase {
const enabledFiles = this.enabledFiles();
const filesToListTests = inputFiles.filter(f => enabledFiles.has(f) && !this._filesWithListedTests.has(f));
if (!filesToListTests.length)
return;
return this._filesPendingListTests?.promise;

for (const file of filesToListTests)
this._filesWithListedTests.add(file);
Expand Down
22 changes: 19 additions & 3 deletions tests/codegen.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,33 @@
import { connectToSharedBrowser, expect, test, waitForPage } from './utils';

test('should generate code', async ({ activate }) => {
test.slow();
const { vscode } = await activate({
'playwright.config.js': `module.exports = {}`,
'playwright.config.js': `module.exports = {
projects: [
{
name: 'default',
},
{
name: 'germany',
use: {
locale: 'de-DE',
},
},
]
}`,
});

const webView = vscode.webViews.get('pw.extension.settingsView')!;
await webView.getByRole('checkbox', { name: 'default' }).setChecked(false);
await webView.getByRole('checkbox', { name: 'germany' }).setChecked(true);
await webView.getByText('Record new').click();
await expect.poll(() => vscode.lastWithProgressData).toEqual({ message: 'recording\u2026' });
await expect.poll(() => vscode.lastWithProgressData, { timeout: 0 }).toEqual({ message: 'recording\u2026' });

const browser = await connectToSharedBrowser(vscode);
const page = await waitForPage(browser);
const page = await waitForPage(browser, { locale: 'de-DE' });
await page.locator('body').click();
expect(await page.evaluate(() => navigator.language)).toBe('de-DE');
await expect.poll(() => {
return vscode.window.visibleTextEditors[0]?.edits;
}).toEqual([{
Expand Down
6 changes: 3 additions & 3 deletions tests/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/

import { expect as baseExpect, test as baseTest, Browser, chromium, Page } from '@playwright/test';
import { expect as baseExpect, test as baseTest, Browser, BrowserContextOptions, chromium, Page } from '@playwright/test';
// @ts-ignore
import { Extension } from '../out/extension';
import { TestController, VSCode, WorkspaceFolder, TestRun, TestItem } from './mock/vscode';
Expand Down Expand Up @@ -197,10 +197,10 @@ export async function connectToSharedBrowser(vscode: VSCode) {
return await chromium.connect(wsEndpoint);
}

export async function waitForPage(browser: Browser) {
export async function waitForPage(browser: Browser, params?: BrowserContextOptions) {
let pages: Page[] = [];
await expect.poll(async () => {
const context = await (browser as any)._newContextForReuse();
const context = await (browser as any)._newContextForReuse(params);
pages = context.pages();
return pages.length;
}).toBeTruthy();
Expand Down
Loading