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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
28 changes: 25 additions & 3 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,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 { kTestRunOptions, TestModel, TestModelCollection, TestProject } from './testModel';
import { 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 { PlaywrightTestRunOptions, RunHooks, TestConfig, ErrorContext } from './playwrightTestTypes';
import { ansi2html } from './ansi2html';
import { LocatorsView } from './locatorsView';

Expand Down Expand Up @@ -103,7 +103,7 @@ export class Extension implements RunHooks {
});

this._settingsModel = new SettingsModel(vscode, context);
this._reusedBrowser = new ReusedBrowser(this._vscode, this._settingsModel, this._envProvider.bind(this));
this._reusedBrowser = new ReusedBrowser(this._vscode, this._settingsModel, this._envProvider.bind(this), this._showBrowserForRecording.bind(this));
this._debugHighlight = new DebugHighlight(vscode, this._reusedBrowser);
this._models = new TestModelCollection(vscode, {
context,
Expand Down Expand Up @@ -648,6 +648,28 @@ export class Extension implements RunHooks {
await this._queueWatchRun(new this._vscode.TestRunRequest(testItems), 'items');
}

private async _showBrowserForRecording(file: string, project: TestProject, connectWsEndpoint: string) {
const fileItem = this._testTree.testItemForFile(file);
if (!fileItem)
throw new Error(`File item not found for ${file}`);
if (fileItem.children.size !== 1)
throw new Error('expected single test in file');

const testItems = this._testTree.collectTestsInside(fileItem);
const testForProject = testItems.length === 1 ? testItems[0] : testItems.find(t => t.label === project.name);
if (!testForProject)
throw new Error(`Test item not found for ${project.name}`);

const request = new this._vscode.TestRunRequest([testForProject], undefined, undefined, false, true);
(request as any)[kTestRunOptions] = {
connectWsEndpoint,
headed: true,
reuseContext: true,
} satisfies PlaywrightTestRunOptions;

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
23 changes: 15 additions & 8 deletions src/reusedBrowser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
*/

import type { TestConfig } from './playwrightTestTypes';
import type { TestModel, TestModelCollection } from './testModel';
import type { TestModel, TestModelCollection, TestProject } from './testModel';
import { createGuid } from './utils';
import * as vscodeTypes from './vscodeTypes';
import path from 'path';
Expand Down Expand Up @@ -44,8 +44,9 @@ export class ReusedBrowser implements vscodeTypes.Disposable {
private _editOperations = Promise.resolve();
private _pausedOnPagePause = false;
private _settingsModel: SettingsModel;
private _showBrowserForRecording: (file: string, project: TestProject, wsEndpoint: string) => Promise<void>;

constructor(vscode: vscodeTypes.VSCode, settingsModel: SettingsModel, envProvider: () => NodeJS.ProcessEnv) {
constructor(vscode: vscodeTypes.VSCode, settingsModel: SettingsModel, envProvider: () => NodeJS.ProcessEnv, _showBrowserForRecording: (file: string, project: TestProject, wsEndpoint: string) => Promise<void>) {
this._vscode = vscode;
this._envProvider = envProvider;
this._onPageCountChangedEvent = new vscode.EventEmitter();
Expand All @@ -56,6 +57,7 @@ export class ReusedBrowser implements vscodeTypes.Disposable {
this.onHighlightRequestedForTest = this._onHighlightRequestedForTestEvent.event;
this._onInspectRequestedEvent = new vscode.EventEmitter();
this.onInspectRequested = this._onInspectRequestedEvent.event;
this._showBrowserForRecording = _showBrowserForRecording;

this._settingsModel = settingsModel;

Expand Down Expand Up @@ -298,17 +300,21 @@ export class ReusedBrowser implements vscodeTypes.Disposable {
}

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;
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' });
const file = await this._createFileForNewTest(model);
if (!file)
return;
await model.handleWorkspaceChange({ created: new Set([file]), changed: new Set(), deleted: new Set() });
await model.ensureTests([file]);
const project = model.enabledProjects()[0];
if (!project)
return;
await this._showBrowserForRecording(file, project, this._backend!.wsEndpoint);
}

// Register early to have this._cancelRecording assigned during re-entry.
Expand Down Expand Up @@ -368,6 +374,7 @@ test('test', async ({ page }) => {
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;
}

async onWillRunTests(config: TestConfig, debug: boolean) {
Expand Down
5 changes: 4 additions & 1 deletion src/testModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ import { collectTestIds } from './upstream/testTree';
import { TraceViewer } from './traceViewer';
import { SpawnTraceViewer } from './spawnTraceViewer';

export const kTestRunOptions = Symbol('kTestRunOptions');

export type TestEntry = reporterTypes.TestCase | reporterTypes.Suite;

export type TestProject = {
Expand Down Expand Up @@ -344,7 +346,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 Expand Up @@ -551,6 +553,7 @@ export class TestModel extends DisposableBase {
connectWsEndpoint: showBrowser ? externalOptions.connectWsEndpoint : undefined,
updateSnapshots: noOverrideToUndefined(this._embedder.settingsModel.updateSnapshots.get()),
updateSourceMethod: noOverrideToUndefined(this._embedder.settingsModel.updateSourceMethod.get()),
...(request as any)[kTestRunOptions],
};

try {
Expand Down
19 changes: 17 additions & 2 deletions tests/codegen.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,31 @@ import { connectToSharedBrowser, expect, test, waitForPage } from './utils';

test('should generate code', async ({ activate }) => {
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.getByText('Record new').click();
await webView.getByRole('checkbox', { name: 'default' }).setChecked(false);
await webView.getByRole('checkbox', { name: 'germany' }).setChecked(true);
await expect.poll(() => vscode.lastWithProgressData).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