Revert "chore: update eslint config (#6840)" partly (#7268)

This reverts commit ec7d37d92f.
This commit is contained in:
Max Schmitt 2021-06-23 11:08:35 +02:00 committed by GitHub
parent 7b6e9b9be9
commit 103f8ddd06
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
28 changed files with 55 additions and 49 deletions

View File

@ -1,16 +1,17 @@
# Ignore everything by default test/assets/modernizr.js
**/* lib/
*.js
# Check ts files in src/
!src
!src/**/*.ts
src/**/*.d.ts
src/generated/* src/generated/*
src/server/chromium/protocol.ts src/server/chromium/protocol.ts
src/server/firefox/protocol.ts src/server/firefox/protocol.ts
src/server/webkit/protocol.ts src/server/webkit/protocol.ts
src/third_party/
# Check ts files in tests/ /types/*
!tests /index.d.ts
!tests/**/*.ts utils/generate_types/overrides.d.ts
tests/**/*.d.ts utils/generate_types/test/test.ts
node_modules/
browser_patches/*/checkout/
browser_patches/chromium/output/
**/*.d.ts
output/

View File

@ -26,7 +26,6 @@ import { Events } from './events';
import { Page } from './page'; import { Page } from './page';
import { Waiter } from './waiter'; import { Waiter } from './waiter';
import * as api from '../../types/types'; import * as api from '../../types/types';
import { Serializable } from '../../types/structs';
export type NetworkCookie = { export type NetworkCookie = {
name: string, name: string,
@ -303,7 +302,7 @@ export class Route extends ChannelOwner<channels.RouteChannel, channels.RouteIni
}); });
} }
async intercept(options: { url?: string, method?: string, headers?: Headers, postData?: string | Buffer, interceptResponse?: boolean } = {}) : Promise<api.Response> { async intercept(options: { url?: string, method?: string, headers?: Headers, postData?: string | Buffer, interceptResponse?: boolean } = {}): Promise<api.Response> {
return await this._continue('route.intercept', options, true); return await this._continue('route.intercept', options, true);
} }
@ -311,9 +310,9 @@ export class Route extends ChannelOwner<channels.RouteChannel, channels.RouteIni
await this._continue('route.continue', options, false); await this._continue('route.continue', options, false);
} }
async _continue(apiName: string, options: { url?: string, method?: string, headers?: Headers, postData?: string | Buffer }, interceptResponse: NotInterceptResponse) : Promise<null>; async _continue(apiName: string, options: { url?: string, method?: string, headers?: Headers, postData?: string | Buffer }, interceptResponse: NotInterceptResponse): Promise<null>;
async _continue(apiName: string, options: { url?: string, method?: string, headers?: Headers, postData?: string | Buffer }, interceptResponse: InterceptResponse) : Promise<api.Response>; async _continue(apiName: string, options: { url?: string, method?: string, headers?: Headers, postData?: string | Buffer }, interceptResponse: InterceptResponse): Promise<api.Response>;
async _continue(apiName: string, options: { url?: string, method?: string, headers?: Headers, postData?: string | Buffer }, interceptResponse: boolean) : Promise<null|api.Response> { async _continue(apiName: string, options: { url?: string, method?: string, headers?: Headers, postData?: string | Buffer }, interceptResponse: boolean): Promise<null|api.Response> {
return await this._wrapApiCall(apiName, async (channel: channels.RouteChannel) => { return await this._wrapApiCall(apiName, async (channel: channels.RouteChannel) => {
const postDataBuffer = isString(options.postData) ? Buffer.from(options.postData, 'utf8') : options.postData; const postDataBuffer = isString(options.postData) ? Buffer.from(options.postData, 'utf8') : options.postData;
const result = await channel.continue({ const result = await channel.continue({

View File

@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { InterceptedResponse, Request, Response, Route, WebSocket } from '../server/network'; import { Request, Response, Route, WebSocket } from '../server/network';
import * as channels from '../protocol/channels'; import * as channels from '../protocol/channels';
import { Dispatcher, DispatcherScope, lookupNullableDispatcher, existingDispatcher } from './dispatcher'; import { Dispatcher, DispatcherScope, lookupNullableDispatcher, existingDispatcher } from './dispatcher';
import { FrameDispatcher } from './frameDispatcher'; import { FrameDispatcher } from './frameDispatcher';

View File

@ -144,7 +144,7 @@ export abstract class BrowserType extends SdkObject {
await fs.promises.mkdir(options.tracesDir, { recursive: true }); await fs.promises.mkdir(options.tracesDir, { recursive: true });
const artifactsDir = await fs.promises.mkdtemp(ARTIFACTS_FOLDER); const artifactsDir = await fs.promises.mkdtemp(ARTIFACTS_FOLDER);
tempDirectories.push(artifactsDir); tempDirectories.push(artifactsDir);
if (!userDataDir) { if (!userDataDir) {
userDataDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), `playwright_${this._name}dev_profile-`)); userDataDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), `playwright_${this._name}dev_profile-`));

View File

@ -72,7 +72,7 @@ export class Chromium extends BrowserType {
headersMap = headersArrayToObject(options.headers, false); headersMap = headersArrayToObject(options.headers, false);
const artifactsDir = await fs.promises.mkdtemp(ARTIFACTS_FOLDER); const artifactsDir = await fs.promises.mkdtemp(ARTIFACTS_FOLDER);
const chromeTransport = await WebSocketTransport.connect(progress, await urlToWSEndpoint(endpointURL), headersMap); const chromeTransport = await WebSocketTransport.connect(progress, await urlToWSEndpoint(endpointURL), headersMap);
const browserProcess: BrowserProcess = { const browserProcess: BrowserProcess = {
close: async () => { close: async () => {
@ -229,9 +229,10 @@ async function urlToWSEndpoint(endpointURL: string) {
const httpURL = endpointURL.endsWith('/') ? `${endpointURL}json/version/` : `${endpointURL}/json/version/`; const httpURL = endpointURL.endsWith('/') ? `${endpointURL}json/version/` : `${endpointURL}/json/version/`;
const json = await new Promise<string>((resolve, reject) => { const json = await new Promise<string>((resolve, reject) => {
http.get(httpURL, resp => { http.get(httpURL, resp => {
if (resp.statusCode! < 200 || resp.statusCode! >= 400) if (resp.statusCode! < 200 || resp.statusCode! >= 400) {
reject(new Error(`Unexpected status ${resp.statusCode} when connecting to ${httpURL}.\n` + reject(new Error(`Unexpected status ${resp.statusCode} when connecting to ${httpURL}.\n` +
`This does not look like a DevTools server, try connecting via ws://.`)); `This does not look like a DevTools server, try connecting via ws://.`));
}
let data = ''; let data = '';
resp.on('data', chunk => data += chunk); resp.on('data', chunk => data += chunk);
resp.on('end', () => resolve(data)); resp.on('end', () => resolve(data));

View File

@ -187,7 +187,7 @@ export class CRNetworkManager {
return; return;
} }
request._onInterceptedResponse!(event); request._onInterceptedResponse!(event);
return return;
} }
const requestId = event.networkId; const requestId = event.networkId;
@ -310,13 +310,14 @@ export class CRNetworkManager {
}; };
} }
const response = new network.Response(request.request, responsePayload.status, responsePayload.statusText, headersObjectToArray(responsePayload.headers), timing, getResponseBody); const response = new network.Response(request.request, responsePayload.status, responsePayload.statusText, headersObjectToArray(responsePayload.headers), timing, getResponseBody);
if (responsePayload?.remoteIPAddress && typeof responsePayload?.remotePort === 'number') if (responsePayload?.remoteIPAddress && typeof responsePayload?.remotePort === 'number') {
response._serverAddrFinished({ response._serverAddrFinished({
ipAddress: responsePayload.remoteIPAddress, ipAddress: responsePayload.remoteIPAddress,
port: responsePayload.remotePort, port: responsePayload.remotePort,
}); });
else } else {
response._serverAddrFinished(); response._serverAddrFinished();
}
response._securityDetailsFinished({ response._securityDetailsFinished({
protocol: responsePayload?.securityDetails?.protocol, protocol: responsePayload?.securityDetails?.protocol,
subjectName: responsePayload?.securityDetails?.subjectName, subjectName: responsePayload?.securityDetails?.subjectName,

View File

@ -124,7 +124,7 @@ export class Electron extends SdkObject {
} }
const artifactsDir = await fs.promises.mkdtemp(ARTIFACTS_FOLDER); const artifactsDir = await fs.promises.mkdtemp(ARTIFACTS_FOLDER);
const browserLogsCollector = new RecentLogsCollector(); const browserLogsCollector = new RecentLogsCollector();
const { launchedProcess, gracefullyClose, kill } = await launchProcess({ const { launchedProcess, gracefullyClose, kill } = await launchProcess({
executablePath: options.executablePath || require('electron/index.js'), executablePath: options.executablePath || require('electron/index.js'),

View File

@ -89,13 +89,12 @@ export class FFNetworkManager {
responseStart: this._relativeTiming(event.timing.responseStart), responseStart: this._relativeTiming(event.timing.responseStart),
}; };
const response = new network.Response(request.request, event.status, event.statusText, event.headers, timing, getResponseBody); const response = new network.Response(request.request, event.status, event.statusText, event.headers, timing, getResponseBody);
if (event?.remoteIPAddress && typeof event?.remotePort === 'number') if (event?.remoteIPAddress && typeof event?.remotePort === 'number') {
response._serverAddrFinished({ response._serverAddrFinished({
ipAddress: event.remoteIPAddress, ipAddress: event.remoteIPAddress,
port: event.remotePort, port: event.remotePort,
}); });
else } else {response._serverAddrFinished();}
response._serverAddrFinished()
response._securityDetailsFinished({ response._securityDetailsFinished({
protocol: event?.securityDetails?.protocol, protocol: event?.securityDetails?.protocol,
subjectName: event?.securityDetails?.subjectName, subjectName: event?.securityDetails?.subjectName,

View File

@ -258,7 +258,7 @@ export class Route extends SdkObject {
throw new Error('New URL must have same protocol as overridden URL'); throw new Error('New URL must have same protocol as overridden URL');
} }
this._response = await this._delegate.continue(overrides); this._response = await this._delegate.continue(overrides);
return this._response return this._response;
} }
async responseBody(): Promise<Buffer> { async responseBody(): Promise<Buffer> {
@ -285,7 +285,7 @@ export type ResourceTiming = {
export type RemoteAddr = { export type RemoteAddr = {
ipAddress: string; ipAddress: string;
port: number; port: number;
} };
export type SecurityDetails = { export type SecurityDetails = {
protocol?: string; protocol?: string;

View File

@ -162,7 +162,7 @@ function snapshotScript() {
adoptedSheets.push(sheet); adoptedSheets.push(sheet);
} }
(root as any).adoptedStyleSheets = adoptedSheets; (root as any).adoptedStyleSheets = adoptedSheets;
} }
}; };
visit(document); visit(document);

View File

@ -91,9 +91,9 @@ export class JavaScriptLanguageGenerator implements LanguageGenerator {
const suffix = (signals.waitForNavigation || emitPromiseAll) ? '' : ';'; const suffix = (signals.waitForNavigation || emitPromiseAll) ? '' : ';';
formatter.add(`${prefix}${subject}.${actionCall}${suffix}`); formatter.add(`${prefix}${subject}.${actionCall}${suffix}`);
if (emitPromiseAll) if (emitPromiseAll) {
formatter.add(`]);`); formatter.add(`]);`);
else if (signals.assertNavigation) { } else if (signals.assertNavigation) {
if (this._isTest) if (this._isTest)
formatter.add(` expect(${pageAlias}.url()).toBe(${quote(signals.assertNavigation.url)});`); formatter.add(` expect(${pageAlias}.url()).toBe(${quote(signals.assertNavigation.url)});`);
else else

View File

@ -23,8 +23,6 @@ import { BrowserType } from '../browserType';
import { ConnectionTransport } from '../transport'; import { ConnectionTransport } from '../transport';
import { BrowserOptions, PlaywrightOptions } from '../browser'; import { BrowserOptions, PlaywrightOptions } from '../browser';
import * as types from '../types'; import * as types from '../types';
import * as fs from 'fs';
import { assert } from '../../utils/utils';
export class WebKit extends BrowserType { export class WebKit extends BrowserType {
constructor(playwrightOptions: PlaywrightOptions) { constructor(playwrightOptions: PlaywrightOptions) {

View File

@ -100,7 +100,7 @@ export class WKInterceptableRequest implements network.RouteDelegate {
mimeType = contentType.split(';')[0].trim(); mimeType = contentType.split(';')[0].trim();
const isResponseIntercepted = await this._responseInterceptedPromise; const isResponseIntercepted = await this._responseInterceptedPromise;
await this._session.sendMayFail(isResponseIntercepted ? 'Network.interceptWithResponse' :'Network.interceptRequestWithResponse', { await this._session.sendMayFail(isResponseIntercepted ? 'Network.interceptWithResponse' : 'Network.interceptRequestWithResponse', {
requestId: this._requestId, requestId: this._requestId,
status: response.status, status: response.status,
statusText: network.STATUS_TEXTS[String(response.status)], statusText: network.STATUS_TEXTS[String(response.status)],

View File

@ -673,7 +673,7 @@ export class WKPage implements PageDelegate {
this._updateState('Network.addInterception', { url: '.*', stage: 'request', isRegex: true }), this._updateState('Network.addInterception', { url: '.*', stage: 'request', isRegex: true }),
]; ];
if (this._needsResponseInterception) if (this._needsResponseInterception)
this._updateState('Network.addInterception', { url: '.*', stage: 'response', isRegex: true }) this._updateState('Network.addInterception', { url: '.*', stage: 'response', isRegex: true });
await Promise.all(promises); await Promise.all(promises);
} }

View File

@ -15,6 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
/* eslint-disable no-console */
import colors from 'colors/safe'; import colors from 'colors/safe';
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';

View File

@ -17,7 +17,7 @@
import * as fs from 'fs'; import * as fs from 'fs';
import * as path from 'path'; import * as path from 'path';
import * as os from 'os'; import * as os from 'os';
import type { LaunchOptions, BrowserContextOptions, Page, BrowserContext } from '../../types/types'; import type { LaunchOptions, BrowserContextOptions, Page } from '../../types/types';
import type { TestType, PlaywrightTestArgs, PlaywrightTestOptions, PlaywrightWorkerArgs, PlaywrightWorkerOptions, FullConfig, TestInfo } from '../../types/test'; import type { TestType, PlaywrightTestArgs, PlaywrightTestOptions, PlaywrightWorkerArgs, PlaywrightWorkerOptions, FullConfig, TestInfo } from '../../types/test';
import { rootTestType } from './testType'; import { rootTestType } from './testType';
import { createGuid, removeFolders } from '../utils/utils'; import { createGuid, removeFolders } from '../utils/utils';

View File

@ -190,7 +190,7 @@ export class Loader {
let testDir = takeFirst(projectConfig.testDir, rootDir); let testDir = takeFirst(projectConfig.testDir, rootDir);
if (!path.isAbsolute(testDir)) if (!path.isAbsolute(testDir))
testDir = path.resolve(rootDir, testDir); testDir = path.resolve(rootDir, testDir);
let outputDir = takeFirst(this._configOverrides.outputDir, projectConfig.outputDir, this._config.outputDir, path.resolve(process.cwd(), 'test-results')) let outputDir = takeFirst(this._configOverrides.outputDir, projectConfig.outputDir, this._config.outputDir, path.resolve(process.cwd(), 'test-results'));
if (!path.isAbsolute(outputDir)) if (!path.isAbsolute(outputDir))
outputDir = path.resolve(rootDir, outputDir); outputDir = path.resolve(rootDir, outputDir);
const fullProject: FullProject = { const fullProject: FullProject = {

View File

@ -0,0 +1,5 @@
{
"rules": {
"no-console": "off"
}
}

View File

@ -14,6 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
/* eslint-disable no-console */
import colors from 'colors/safe'; import colors from 'colors/safe';
// @ts-ignore // @ts-ignore
import milliseconds from 'ms'; import milliseconds from 'ms';

View File

@ -15,6 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
/* eslint-disable no-console */
import rimraf from 'rimraf'; import rimraf from 'rimraf';
import * as fs from 'fs'; import * as fs from 'fs';
import * as path from 'path'; import * as path from 'path';

View File

@ -87,7 +87,7 @@ export function fetchData(url: string): Promise<string> {
type OnProgressCallback = (downloadedBytes: number, totalBytes: number) => void; type OnProgressCallback = (downloadedBytes: number, totalBytes: number) => void;
type DownloadFileLogger = (message: string) => void; type DownloadFileLogger = (message: string) => void;
export function downloadFile(url: string, destinationPath: string, options : {progressCallback?: OnProgressCallback, log?: DownloadFileLogger} = {}): Promise<{error: any}> { export function downloadFile(url: string, destinationPath: string, options: {progressCallback?: OnProgressCallback, log?: DownloadFileLogger} = {}): Promise<{error: any}> {
const { const {
progressCallback, progressCallback,
log = () => {}, log = () => {},

View File

@ -318,7 +318,7 @@ test('should report an expected error when the endpointURL returns a non-expecte
}); });
await expect(browserType.connectOverCDP({ await expect(browserType.connectOverCDP({
endpointURL: server.PREFIX, endpointURL: server.PREFIX,
})).rejects.toThrowError(`browserType.connectOverCDP: Unexpected status 404 when connecting to ${server.PREFIX}/json/version/`) })).rejects.toThrowError(`browserType.connectOverCDP: Unexpected status 404 when connecting to ${server.PREFIX}/json/version/`);
}); });
test('should report an expected error when the endpoint URL JSON webSocketDebuggerUrl is undefined', async ({ browserType, server }) => { test('should report an expected error when the endpoint URL JSON webSocketDebuggerUrl is undefined', async ({ browserType, server }) => {

View File

@ -78,7 +78,6 @@ test('test', async ({ page }) => {`;
test('should print load storageState', async ({ browserName, channel, runCLI }, testInfo) => { test('should print load storageState', async ({ browserName, channel, runCLI }, testInfo) => {
const loadFileName = testInfo.outputPath('load.json'); const loadFileName = testInfo.outputPath('load.json');
const saveFileName = testInfo.outputPath('save.json');
await fs.promises.writeFile(loadFileName, JSON.stringify({ cookies: [], origins: [] }), 'utf8'); await fs.promises.writeFile(loadFileName, JSON.stringify({ cookies: [], origins: [] }), 'utf8');
const cli = runCLI([`--load-storage=${loadFileName}`, emptyHTML]); const cli = runCLI([`--load-storage=${loadFileName}`, emptyHTML]);
const expectedResult = `const { test, expect } = require('@playwright/test'); const expectedResult = `const { test, expect } = require('@playwright/test');

View File

@ -226,7 +226,7 @@ it.describe('Drag and drop', () => {
await page.mouse.up(); await page.mouse.up();
route.abort(); route.abort();
expect(await page.$eval('#target', target => target.contains(document.querySelector('#source')))).toBe(true); // could not find source in target expect(await page.$eval('#target', target => target.contains(document.querySelector('#source')))).toBe(true); // could not find source in target
}) });
async function trackEvents(target: ElementHandle) { async function trackEvents(target: ElementHandle) {
const eventsHandle = await target.evaluateHandle(target => { const eventsHandle = await target.evaluateHandle(target => {

View File

@ -558,7 +558,7 @@ it('should not use Array.prototype.toJSON when evaluating', async ({ page }) =>
it('should not add a toJSON property to newly created Arrays after evaluation', async ({ page, browserName }) => { it('should not add a toJSON property to newly created Arrays after evaluation', async ({ page, browserName }) => {
await page.evaluate(() => []); await page.evaluate(() => []);
const hasToJSONProperty = await page.evaluate(() => "toJSON" in []); const hasToJSONProperty = await page.evaluate(() => 'toJSON' in []);
expect(hasToJSONProperty).toEqual(false); expect(hasToJSONProperty).toEqual(false);
}); });

View File

@ -15,9 +15,9 @@
* limitations under the License. * limitations under the License.
*/ */
import { fail } from 'assert'; import { fail } from 'assert';
import type { Route } from '../../index'; import type { Route } from '../../index';
import { test as it, expect } from './pageTest'; import { test as it, expect } from './pageTest';
it('should fulfill intercepted response', async ({page, server, browserName}) => { it('should fulfill intercepted response', async ({page, server, browserName}) => {
it.fixme(browserName === 'firefox'); it.fixme(browserName === 'firefox');
@ -53,7 +53,7 @@ it('should throw on continue after intercept', async ({page, server, browserName
await route.continue(); await route.continue();
fail('did not throw'); fail('did not throw');
} catch (e) { } catch (e) {
expect(e.message).toContain('Cannot call continue after response interception!') expect(e.message).toContain('Cannot call continue after response interception!');
} }
}); });

View File

@ -126,7 +126,7 @@ async function runPlaywrightTest(baseDir: string, params: any, env: Env): Promis
const reportFile = path.join(outputDir, 'report.json'); const reportFile = path.join(outputDir, 'report.json');
const args = [path.join(__dirname, '..', '..', 'lib', 'cli', 'cli.js'), 'test']; const args = [path.join(__dirname, '..', '..', 'lib', 'cli', 'cli.js'), 'test'];
if (!params.usesCustomOutputDir) if (!params.usesCustomOutputDir)
args.push('--output=' + outputDir) args.push('--output=' + outputDir);
args.push( args.push(
'--reporter=dot,json', '--reporter=dot,json',
'--workers=2', '--workers=2',

View File

@ -28,7 +28,7 @@ export class VideoPlayer {
videoHeight: number; videoHeight: number;
constructor(fileName: string) { constructor(fileName: string) {
var output = spawnSync(ffmpeg, ['-i', fileName, '-r', '25', `${fileName}-%03d.png`]).stderr.toString(); const output = spawnSync(ffmpeg, ['-i', fileName, '-r', '25', `${fileName}-%03d.png`]).stderr.toString();
const lines = output.split('\n'); const lines = output.split('\n');
const streamLine = lines.find(l => l.trim().startsWith('Stream #0:0')); const streamLine = lines.find(l => l.trim().startsWith('Stream #0:0'));
const resolutionMatch = streamLine.match(/, (\d+)x(\d+),/); const resolutionMatch = streamLine.match(/, (\d+)x(\d+),/);