Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

devops: remove redundant scripts (#36408)

Max Schmitta5b68a5c0e87
diff --git a/utils/check_chromium_cdn.js b/utils/check_chromium_cdn.js
deleted file mode 100755
index c509624152..0000000000
--- a/utils/check_chromium_cdn.js
+++ /dev/null
@@ -1,196 +0,0 @@
-#!/usr/bin/env node
-/**
- * Copyright 2017 Google Inc. All rights reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-const assert = require('assert');
-const https = require('https');
-const util = require('util');
-const URL = require('url');
-const SUPPORTER_PLATFORMS = ['linux', 'mac', 'win64'];
-
-const colors = {
- reset: '\x1b[0m',
- red: '\x1b[31m',
- green: '\x1b[32m',
- yellow: '\x1b[33m'
-};
-
-class Table {
- /**
- * @param {!Array<number>} columnWidths
- */
- constructor(columnWidths) {
- this.widths = columnWidths;
- }
-
- /**
- * @param {!Array<string>} values
- */
- drawRow(values) {
- assert(values.length === this.widths.length);
- let row = '';
- for (let i = 0; i < values.length; ++i)
- row += padCenter(values[i], this.widths[i]);
- console.log(row);
- }
-}
-
-if (process.argv.length === 2) {
- checkOmahaProxyAvailability();
- return;
-}
-if (process.argv.length !== 4) {
- console.log(`
- Usage: node check_revisions.js [fromRevision] [toRevision]
-
-This script checks availability of different prebuild chromium revisions.
-Running command without arguments will check against omahaproxy revisions.`);
- return;
-}
-
-const fromRevision = parseInt(process.argv[2], 10);
-const toRevision = parseInt(process.argv[3], 10);
-checkRangeAvailability(fromRevision, toRevision, false /* stopWhenAllAvailable */);
-
-async function checkOmahaProxyAvailability() {
- const lastchanged = (await Promise.all([
- fetch('https://storage.googleapis.com/chromium-browser-snapshots/Mac/LAST_CHANGE'),
- fetch('https://storage.googleapis.com/chromium-browser-snapshots/Linux_x64/LAST_CHANGE'),
- fetch('https://storage.googleapis.com/chromium-browser-snapshots/Win/LAST_CHANGE'),
- fetch('https://storage.googleapis.com/chromium-browser-snapshots/Win_x64/LAST_CHANGE'),
- ])).map(s => parseInt(s, 10));
- const from = Math.max(...lastchanged);
- checkRangeAvailability(from, 0, true /* stopWhenAllAvailable */);
-}
-
-/**
- * @param {number} fromRevision
- * @param {number} toRevision
- * @param {boolean} stopWhenAllAvailable
- */
-async function checkRangeAvailability(fromRevision, toRevision, stopWhenAllAvailable) {
- const table = new Table([15, 7, 7, 7]);
- table.drawRow([''].concat(SUPPORTER_PLATFORMS));
- const inc = fromRevision < toRevision ? 1 : -1;
- for (let revision = fromRevision; revision !== toRevision; revision += inc) {
- const allAvailable = await checkAndDrawRevisionAvailability(table, 'chromium', revision);
- if (allAvailable && stopWhenAllAvailable)
- break;
- }
-}
-
-async function canDownload(revision, platform) {
- const serverHost = 'https://storage.googleapis.com';
- const urlTemplate = new Map([
- ['linux', '%s/chromium-browser-snapshots/Linux_x64/%d/chrome-linux.zip'],
- ['mac', '%s/chromium-browser-snapshots/Mac/%d/chrome-mac.zip'],
- ['win64', '%s/chromium-browser-snapshots/Win_x64/%d/chrome-win.zip'],
- ]).get(platform);
- assert(urlTemplate, `ERROR: Playwright does not support ${platform}`);
- const url = util.format(urlTemplate, serverHost, revision);
- return await headRequest(url);
-}
-
-/**
- * @param {!Table} table
- * @param {string} name
- * @param {number} revision
- * @return {boolean}
- */
-async function checkAndDrawRevisionAvailability(table, name, revision) {
- const promises = SUPPORTER_PLATFORMS.map(platform => canDownload(revision, platform));
- const availability = await Promise.all(promises);
- const allAvailable = availability.every(e => !!e);
- const values = [name + ' ' + (allAvailable ? colors.green + revision + colors.reset : revision)];
- for (let i = 0; i < availability.length; ++i) {
- const decoration = availability[i] ? '+' : '-';
- const color = availability[i] ? colors.green : colors.red;
- values.push(color + decoration + colors.reset);
- }
- table.drawRow(values);
- return allAvailable;
-}
-
-/**
- * @param {string} url
- * @return {!Promise<?string>}
- */
-function fetch(url) {
- let resolve;
- const promise = new Promise(x => resolve = x);
- https.get(url, response => {
- if (response.statusCode !== 200) {
- resolve(null);
- return;
- }
- let body = '';
- response.on('data', function(chunk){
- body += chunk;
- });
- response.on('end', function(){
- resolve(body);
- });
- }).on('error', function(e){
- console.error('Error fetching json: ' + e);
- resolve(null);
- });
- return promise;
-}
-
-/**
- * @param {number} size
- * @return {string}
- */
-function spaceString(size) {
- return new Array(size).fill(' ').join('');
-}
-
-/**
- * @param {string} text
- * @return {string}
- */
-function filterOutColors(text) {
- for (const colorName in colors) {
- const color = colors[colorName];
- text = text.replace(color, '');
- }
- return text;
-}
-
-/**
- * @param {string} text
- * @param {number} length
- * @return {string}
- */
-function padCenter(text, length) {
- const printableCharacters = filterOutColors(text);
- if (printableCharacters.length >= length)
- return text;
- const left = Math.floor((length - printableCharacters.length) / 2);
- const right = Math.ceil((length - printableCharacters.length) / 2);
- return spaceString(left) + text + spaceString(right);
-}
-
-async function headRequest(url) {
- return new Promise(resolve => {
- let options = URL.parse(url);
- options.method = 'HEAD';
- const request = https.request(options, res => resolve(res.statusCode === 200));
- request.on('error', error => resolve(false));
- request.end();
- });
-}
-
diff --git a/utils/doclint/generateJavaSnippets.js b/utils/doclint/generateJavaSnippets.js
deleted file mode 100644
index 0973811317..0000000000
--- a/utils/doclint/generateJavaSnippets.js
+++ /dev/null
@@ -1,154 +0,0 @@
-// @ts-check
-
-const fs = require("fs");
-const md = require("../markdown");
-
-
-/**
- * @param {string[]} input
- */
-function transformValue(input) {
- const out = [];
- const suffix = [];
- for (let line of input) {
- let match = line.match(/const { (\w+) } = require\('playwright'\);/);
- if (match) {
- out.push('import com.microsoft.playwright.*;');
- out.push('');
- out.push('public class Example {');
- out.push(' public static void main(String[] args) {');
- out.push(' try (Playwright playwright = Playwright.create()) {');
- out.push(` BrowserType ${match[1]} = playwright.${match[1]}();`);
- suffix.push(' }');
- suffix.push(' }');
- suffix.push('}');
- continue;
- }
- if (line.trim() === '(async () => {' || line.trim() === '})();')
- continue;
- if (!line)
- continue;
- if (line.trim() === '}')
- continue;
-
- // Remove await/Promise.all
- line = line.replace(/const \[(.+)\] = await Promise.all\(\[/g, '$1 =');
- line = line.replace(/Promise\.all\(\[/g, '');
- line = line.replace(/await /g, '');
-
- // Rename some methods
- line = line.replace(/\.goto\(/g, '.navigate(');
- line = line.replace(/\.continue\(/g, '.resume(');
- line = line.replace(/\.\$eval\(/g, '.evalOnSelector(');
- line = line.replace(/\.\$\$eval\(/g, '.evalOnSelectorAll(');
- line = line.replace(/\.\$\(/g, '.querySelector(');
- line = line.replace(/\.\$\$\(/g, '.querySelectorAll(');
-
- line = line.replace(/console.log/g, 'System.out.println');
-
- line = line.replace(/page.evaluate\((\(\) => [^\)]+)\)/g, 'page.evaluate("$1")');
-
- // Convert properties to methods
- line = line.replace(/\.keyboard\./g, '.keyboard().');
- line = line.replace(/\.mouse\./g, '.mouse().');
- line = line.replace(/\.coverage\./g, '.coverage().');
- line = line.replace(/\.accessibility\./g, '.accessibility().');
- line = line.replace(/\.chromium\./g, '.chromium().');
- line = line.replace(/\.webkit\./g, '.webkit().');
- line = line.replace(/\.firefox\./g, '.firefox().');
- line = line.replace(/\.length/g, '.size()');
-
- // JUnit asserts
- line = line.replace(/expect\((.+)\).toBeTruthy\(\);/g, 'assertNotNull($1);');
- line = line.replace(/expect\(error.message\)\.toContain\((.+)\);/g, 'assertTrue(e.getMessage().contains($1));');
- line = line.replace(/expect\((.+)\)\.toContain\((.+)\);/g, 'assertTrue($1.contains($2));');
- line = line.replace(/expect\((.+)\)\.toBe\(null\);/g, 'assertNull($1);');
- line = line.replace(/expect\((.+)\)\.not.toBe\(null\);/g, 'assertNotNull($1);');
- line = line.replace(/expect\((.+)\)\.toBe\(true\);/g, 'assertTrue($1);');
- line = line.replace(/expect\((.+)\)\.toBe\((.+)\);/g, 'assertEquals($2, $1);');
- line = line.replace(/expect\((.+)\)\.toEqual\(\[(.+)\]\);/g, 'assertEquals(Arrays.asList($2), $1);');
- line = line.replace(/expect\((.+)\)\.toEqual\((.+)\);/g, 'assertEquals($2, $1);');
-
- line = line.replace(/\[('[^']+')\]/g, '.get("$1")');
- line = line.replace(/.push\(/g, '.add(');
-
- // Define common types
- line = line.replace(/const browser = /g, 'Browser browser = ');
- line = line.replace(/const context = /g, 'BrowserContext context = ');
- line = line.replace(/const page = /g, 'Page page = ');
- line = line.replace(/const newPage = /g, 'Page newPage = ');
- line = line.replace(/const button/g, 'ElementHandle button');
- line = line.replace(/const result = /g, 'Object result = ');
- line = line.replace(/const response = /g, 'Response response = ');
- line = line.replace(/const request = /g, 'Request request = ');
- line = line.replace(/const requests = \[\];/g, 'List<Request> requests = new ArrayList<>();');
- line = line.replace(/const snapshot = page.accessibility/g, 'String snapshot = page.accessibility');
- line = line.replace(/snapshot\.children\./g, 'snapshot.children().');
- line = line.replace(/const (.+) = \[\];/g, 'List<> $1 = new ArrayList<>();');
- line = line.replace(/const (\w+ = .+evalOnSelector)/g, 'Object $1');
- line = line.replace(/const (\w+ = .+querySelector)/g, 'ElementHandle $1');
- line = line.replace(/const (.+= page.waitForNavigation)/g, 'Response $1');
- line = line.replace(/const messages = \[\]/g, 'List<String> messages = new ArrayList<>()');
- line = line.replace(/const frame = /g, 'Frame frame = ');
- line = line.replace(/const elementHandle = (.+)/g, 'JSHandle jsHandle = $1\n ElementHandle elementHandle = jsHandle.asElement();\n');
- line = line.replace(/const (\w+ = \w+\.boundingBox)/g, 'BoundingBox $1');
- line = line.replace(/setViewportSize\({ width: (\d+), height: (\d+) }\)/g, 'setViewportSize($1, $2)');
- line = line.replace(/\.on\('([^']+)'/g, (match, p1, offset, string) => `.on${toTitleCase(p1)}(`);
- line = line.replace(/\.waitForEvent\('([^']+)'/g, (match, p1, offset, string) => `page.waitFor${toTitleCase(p1)}(() -> {})`);
-
- line = line.replace(/[`']/g, '"');
-
- out.push(line)
- }
- return [...out, ...suffix].join("\n");
-}
-
-/**
- * @param {string} name
- */
-function toTitleCase(name) {
- return name[0].toUpperCase() + name.substring(1);
-}
-
-/**
- * @param {md.MarkdownNode} node
- */
-function generateComment(node) {
- const commentNode = md.clone(node)
- commentNode.codeLang = 'java';
- commentNode.lines = ['// FIXME', ...transformValue(node.lines).split("\n")];
- return commentNode;
-}
-
-/**
- *
- * @param {md.MarkdownNode[]} spec
- */
-function multiplyComment(spec) {
- const children = []
- for (const node of (spec || [])) {
- if (node.codeLang === "js")
- children.push(node, generateComment(node));
- else
- children.push(node);
- }
- return children;
-}
-
-for (const name of fs.readdirSync("docs/src")) {
- if (!name.endsWith(".md"))
- continue;
- if (name.includes('android'))
- continue;
- const inputFile = `docs/src/${name}`;
- const fileline = fs.readFileSync(inputFile).toString();
- const nodes = md.parse(fileline);
-
- md.visitAll(nodes, node => {
- if (node.children)
- node.children = multiplyComment(node.children);
- });
-
- const out = md.render(nodes, 120);
- fs.writeFileSync(inputFile, out);
-}
diff --git a/utils/doclint/generatePythonSnippets.js b/utils/doclint/generatePythonSnippets.js
deleted file mode 100644
index 98275966cc..0000000000
--- a/utils/doclint/generatePythonSnippets.js
+++ /dev/null
@@ -1,120 +0,0 @@
-// @ts-check
-
-const fs = require("fs");
-const md = require("../markdown");
-
-
-/**
- * @param {string[]} input
- * @param {boolean} isSync
- */
-function transformValue(input, isSync) {
- const out = [];
- const suffix = [];
- for (let line of input) {
- let match = line.match(/const { (\w+) } = require\('playwright'\);/);
- if (match) {
- if (isSync) {
- out.push('from playwright.sync_api import sync_playwright, Playwright');
- out.push('');
- out.push('def run(playwright: Playwright):');
- out.push(` ${match[1]} = playwright.${match[1]}`);
- suffix.push(``);
- suffix.push(`with sync_playwright() as playwright:`);
- suffix.push(` run(playwright)`);
- } else {
- out.push('import asyncio');
- out.push('from playwright.async_api import async_playwright, Playwright');
- out.push('');
- out.push('async def run(playwright: Playwright):');
- out.push(` ${match[1]} = playwright.${match[1]}`);
- suffix.push(``);
- suffix.push(`async def main():`);
- suffix.push(` async with async_playwright() as playwright:`);
- suffix.push(` await run(playwright)`);
- suffix.push(`asyncio.run(main())`);
- }
- continue;
- }
- if (line.trim() === '(async () => {' || line.trim() === '})();')
- continue;
- if (!line)
- continue;
- if (line.trim() === '}')
- continue;
- line = line.replace(/\$\$eval/g, 'eval_on_selector_all');
- line = line.replace(/\$eval/g, 'eval_on_selector');
- line = line.replace(/\$\$/g, 'query_selector_all');
- line = line.replace(/\$/g, 'query_selector');
- line = line.replace(/([a-zA-Z$]+)/g, (match, p1) => toSnakeCase(p1));
- line = line.replace(/try {/, 'try:');
- line = line.replace(/async \(([^)]+)\) => {/, 'lambda $1:');
- line = line.replace(/} catch \(e\) {/, 'except Error as e:');
- line = line.replace(/;$/, '');
- line = line.replace(/ /g, ' ');
- line = line.replace(/'/g, '"');
- line = line.replace(/const /g, '');
- line = line.replace(/{\s*(\w+):\s*([^} ]+)\s*}/, "$1=$2");
- line = line.replace(/\/\/ /, "# ");
- line = line.replace(/\(\) => /, 'lambda: ');
- line = line.replace(/console.log/, 'print');
- line = line.replace(/function /, 'def ');
- line = line.replace(/{$/, '');
- if (isSync)
- line = line.replace(/await /g, "")
- out.push(line)
- }
- return [...out, ...suffix].join("\n");
-}
-
-/**
- *
- * @param {md.MarkdownNode} node
- * @param {boolean} isSync
- */
-function generateComment(node, isSync) {
- const commentNode = md.clone(node)
- commentNode.codeLang = isSync ? "python sync" : "python async";
- commentNode.lines = ['# FIXME', ...transformValue(node.lines, isSync).split("\n")];
- return commentNode;
-}
-
-/**
- *
- * @param {md.MarkdownNode[]} spec
- */
-function multiplyComment(spec) {
- const children = []
- for (const node of (spec || [])) {
- if (node.codeLang === "js")
- children.push(node, generateComment(node, false), generateComment(node, true));
- else
- children.push(node);
- }
- return children;
-}
-
-/**
- * @param {string} name
- */
-function toSnakeCase(name) {
- const toSnakeCaseRegex = /((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))/g;
- return name.replace(toSnakeCaseRegex, `_$1`).toLowerCase();
-}
-
-for (const name of fs.readdirSync("docs/src")) {
- if (!name.endsWith(".md"))
- continue;
- const inputFile = `docs/src/${name}`;
- const fileContent = fs.readFileSync(inputFile).toString();
- const nodes = md.parse(fileContent);
-
- md.visitAll(nodes, node => {
- if (node.children)
- node.children = multiplyComment(node.children);
- });
-
-
- const out = md.render(nodes, 120);
- fs.writeFileSync(inputFile, out);
-}
diff --git a/utils/doclint/since.js b/utils/doclint/since.js
deleted file mode 100644
index 5f97ec5630..0000000000
--- a/utils/doclint/since.js
+++ /dev/null
@@ -1,81 +0,0 @@
-const fs = require('fs');
-const path = require('path');
-const { ZipFile } = require('../../packages/playwright-core/lib/utils');
-
-(async () => {
- // Extract API.json
- if (!process.env.DRIVERS_DIR) {
- console.log('DRIVERS_DIR env should contain downloaded drivers');
- process.exit(1);
- }
-
- for (const name of fs.readdirSync(process.env.DRIVERS_DIR)) {
- const match = name.match(/playwright-(.*).0-linux.zip/);
- if (!match)
- continue;
- const apiName = path.join(process.env.DRIVERS_DIR, `api-${match[1]}.json`);
- if (!fs.existsSync(apiName)) {
- const zipFile = new ZipFile(path.join(process.env.DRIVERS_DIR, name));
- const buffer = await zipFile.read('package/api.json');
- fs.writeFileSync(path.join(process.env.DRIVERS_DIR, `api-${match[1]}.json`), buffer);
- zipFile.close();
- }
- }
-
- // Build Since map.
- const since = new Map();
- for (const name of fs.readdirSync(process.env.DRIVERS_DIR)) {
- const match = name.match(/api-(.*).json/);
- if (!match)
- continue;
- const version = match[1];
- const json = JSON.parse(fs.readFileSync(path.join(process.env.DRIVERS_DIR, `api-${match[1]}.json`), 'utf-8'));
- for (const clazz of json) {
- add(since, `# class: ${clazz.name}`, version);
- for (const member of clazz.members) {
- add(since, `## ${member.async ? 'async ' : ''}${member.kind}: ${clazz.name}.${member.name}`, version);
- for (const arg of member.args) {
- if (arg.name === 'options') {
- for (const option of arg.type.properties)
- add(since, `### option: ${clazz.name}.${member.name}.${option.name}`, version);
- } else {
- add(since, `### param: ${clazz.name}.${member.name}.${arg.name}`, version);
- }
- }
- }
- }
- }
-
- // Patch docs
- for (const name of fs.readdirSync('docs/src/api')) {
- const lines = fs.readFileSync(path.join('docs/src/api', name), 'utf-8');
- const toPatch = new Map();
- for (const line of lines.split('\n')) {
- if (!line.startsWith('# class:') && !line.startsWith('## method:') && !line.startsWith('## async method:') && !line.startsWith('## property:') && !line.startsWith('## event:') && !line.startsWith('### param:') && !line.startsWith('### option:'))
- continue;
- const key = line.includes('=') ? line.substring(0, line.indexOf('=')).trim() : line;
- const version = since.get(key);
- console.log(key);
-
- if (!version) {
- console.log('Not yet released: ' + line);
- continue;
- }
-
- toPatch.set(line +'\n', line + `\n* since: v${version}\n`);
- }
- if (toPatch.size) {
- let newContent = lines;
- for (const [from, to] of toPatch)
- newContent = newContent.replace(new RegExp(from, 'g'), to);
- fs.writeFileSync(path.join('docs/src/api', name), newContent);
- }
- }
-
-})();
-
-function add(since, name, version) {
- let v = since.get(name);
- if (!v || (+v.split('.')[1]) > (+version.split('.')[1]))
- since.set(name, version);
-}
diff --git a/utils/draft_release_notes.sh b/utils/draft_release_notes.sh
deleted file mode 100755
index c27df96a4a..0000000000
--- a/utils/draft_release_notes.sh
+++ /dev/null
@@ -1,39 +0,0 @@
-#!/usr/bin/env bash
-set -e
-set +x
-
-trap "cd $(pwd -P)" EXIT
-cd "$(dirname $0)"
-
-git fetch --tags [email protected]:microsoft/playwright.git >/dev/null 2>/dev/null
-LAST_RELEASE=$(git describe --tags $(git rev-list --tags --max-count=1))
-
-echo "## Highlights"
-echo
-echo "TODO: asked teammates for the highlights"
-echo
-echo "## Browser Versions"
-echo
-node ./print_versions.js
-echo
-echo "## New APIs"
-echo
-echo "TODO: \`git diff -w ${LAST_RELEASE}..HEAD src/client\`"
-echo
-CLOSED_ISSUES=$(./list_closed_issues.sh "${LAST_RELEASE}")
-ISSUES_COUNT=$(echo "${CLOSED_ISSUES}" | wc -l | xargs)
-echo "<details>"
-echo " <summary><b>Issues Closed (${ISSUES_COUNT})</b></summary>"
-echo
-echo "${CLOSED_ISSUES}"
-echo
-echo "</details>"
-
-COMMITS=$(git log --pretty="%h - %s" "${LAST_RELEASE}"..HEAD)
-COMMITS_COUNT=$(echo "${COMMITS}" | wc -l | xargs)
-echo "<details>"
-echo " <summary><b>Commits (${COMMITS_COUNT})</b></summary>"
-echo
-echo "${COMMITS}"
-echo
-echo "</details>"
diff --git a/utils/limits.sh b/utils/limits.sh
deleted file mode 100755
index 71baec19a4..0000000000
--- a/utils/limits.sh
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-sudo sysctl -w fs.inotify.max_user_instances=1024
diff --git a/utils/list_closed_issues.sh b/utils/list_closed_issues.sh
deleted file mode 100755
index 512da44283..0000000000
--- a/utils/list_closed_issues.sh
+++ /dev/null
@@ -1,25 +0,0 @@
-#!/usr/bin/env bash
-set -e
-set +x
-
-if [[ ($1 == '--help') || ($1 == '-h') ]]; then
- echo "usage: $(basename $0) <GIT_SHA>"
- echo
- echo "List Playwright closed issues since the given commit was landed"
- echo
- echo "Example: $(basename $0) HEAD~100"
- exit 0
-fi
-
-if [[ $# == 0 ]]; then
- echo "missing git SHA"
- echo "try './$(basename $0) --help' for more information"
- exit 1
-fi
-
-COMMIT_DATE_WEIRD_ISO=$(git show -s --format=%cd --date=iso $1)
-COMMIT_DATE=$(node -e "console.log(new Date('${COMMIT_DATE_WEIRD_ISO}').toISOString())")
-
-curl -s "https://api.github.com/repos/microsoft/playwright/issues?state=closed&since=${COMMIT_DATE}&direction=asc&per_page=100" | \
- node -e "console.log(JSON.parse(require('fs').readFileSync(0, 'utf8')).filter(issue => !issue.pull_request && new Date(issue.closed_at) > new Date('${COMMIT_DATE}')).map(issue => '#' + issue.number + ' - ' + issue.title).join('\n'))"
-
diff --git a/utils/ts_to_java.js b/utils/ts_to_java.js
deleted file mode 100644
index d071945a9f..0000000000
--- a/utils/ts_to_java.js
+++ /dev/null
@@ -1,165 +0,0 @@
-/**
- * Copyright (c) Microsoft Corporation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// The script does basic transformation of .spec.ts code to .java unit tests.
-
-const path = require('path');
-const fs = require('fs');
-const os = require('os');
-const util = require('util');
-const { argv } = require('process');
-
-(async () => {
- if (process.argv.length < 3) throw new Error("Usage: node to_java.js <test>.spec.js");
- const file = argv[2];
- if (!file.endsWith('.spec.ts')) throw new Error("Unexpected input: " + file);
- console.log('Reading: ' + file);
- let content = await util.promisify(fs.readFile)(file);
- content = content.toString();
-
- function toCamelCase(match, p1, offset, string) {
- return p1.toUpperCase();
- }
-
- function itReplacer(match, p1, p2, p3, offset, string) {
- // let name = p1.replace(/[ :'\-=\[\]\<\>]/g, '_');
- let name = p1.replace(/\W+(.)/g, toCamelCase);
- // Remove special chars from the end.
- name = name.replace(/\W+$/, '');
- // console.log(name);
- return `@Test
-void ${name}() {`;
- }
- content = content.replace(/playwrightTest\('(.+)',.*{/g, itReplacer);
- content = content.replace(/browserTest\('(.+)',.*{/g, itReplacer);
- content = content.replace(/pageTest\('(.+)',.*{/g, itReplacer);
- content = content.replace(/test\('(.+)',.*{/g, itReplacer);
- content = content.replace(/it\('(.+)',.*{/g, itReplacer);
- content = content.replace(/it\(`(.+)`,.*{/g, itReplacer);
-
- // Test's closing bracket: });
- content = content.replace(/\n\}\);/g, '\n}');
-
- content = content.replace(/ async route => {/g, ' (route, request) -> {');
- content = content.replace(/ route => {/g, ' (route, request) -> {');
- content = content.replace(/ async \(route, request\) => {/g, ' (route, request) -> {');
- content = content.replace(/ \(route, request\) => {/g, ' (route, request) -> {');
- content = content.replace(/(server.setRoute.+)\(req, res\) => \{/g, '$1exchange -> {');
-
- content = content.replace(/([^\\])"/g, '$1SINGLE_QUOTE');
- // content = content.replace(/(\) \=\>.*)'/g, '$1 XXX');
-
- // Replace single quotes with double quotes
- content = content.replace(/''/g, '""');
- content = content.replace(/(?<!\) \=\>.*)([^\\])'/g, '$1"');
- // Replace double quotes with single quotes
- content = content.replace(/SINGLE_QUOTE/g, "'");
- content = content.replace(/`/g, '"');
-
- // quote lambdas
- content = content.replace(/request => requests.push\(request\)/g, 'request -> requests.add(request)');
- // content = content.replace(/, ([^,\(]+ \=\> [^\)]+)\)/g, ', "$1")');
- content = content.replace(/page.evaluate\((\(\) => [^\)]+)\)/g, 'page.evaluate("$1")');
-
- // Remove await/Promise.all
- // Match all [^;] inside Promise.all([...]); to overcome greedy match and not include next foo([...]) calls.
- content = content.replace(/const \[(.+)\] = await Promise.all\(\[([^;]+|)\]\);/g, '$1 = $2');
- content = content.replace(/await Promise.all\(\[([^;]+|)\]\);/g, '$1');
- content = content.replace(/Promise\.all\(\[/g, '');
- content = content.replace(/await /g, '');
-
- // Rename some methods
- content = content.replace(/context\.tracing/g, 'context.tracing()');
- content = content.replace(/\.goto\(/g, '.navigate(');
- content = content.replace(/\.continue\(/g, '.resume(');
- content = content.replace(/\.\$eval\(/g, '.evalOnSelector(');
- content = content.replace(/\.\$\$eval\(/g, '.evalOnSelectorAll(');
- content = content.replace(/\.\$\(/g, '.querySelector(');
- content = content.replace(/\.\$\$\(/g, '.querySelectorAll(');
-
- content = content.replace(/\.keyboard\./g, '.keyboard().');
- content = content.replace(/\.mouse\./g, '.mouse().');
- content = content.replace(/\.coverage\./g, '.coverage().');
- content = content.replace(/\.accessibility\./g, '.accessibility().');
- content = content.replace(/\.length/g, '.size()');
-
- content = content.replace(/expect\((.+)\).toBeTruthy\(\);/g, 'assertNotNull($1);');
- content = content.replace(/expect\(error.message\)\.toContain\((.+)\);/g, 'assertTrue(e.getMessage().contains($1), e.getMessage());');
- content = content.replace(/expect\((.+)\)\.toContain\((.+)\);/g, 'assertTrue($1.contains($2));');
- content = content.replace(/expect\((.+)\)\.toBe\(null\);/g, 'assertNull($1);');
- content = content.replace(/expect\((.+)\)\.not.toBe\(null\);/g, 'assertNotNull($1);');
- content = content.replace(/expect\((.+\.evaluate.+)\)\.toBe\(true\);/g, 'assertEquals(true, $1);');
- content = content.replace(/expect\((.+)\)\.toBe\(true\);/g, 'assertTrue($1);');
- content = content.replace(/expect\((.+)\)\.toBe\((.+)\);/g, 'assertEquals($2, $1);');
- // Match all [^;] inside .toEqual([...]); to overcome greedy match and not include next foo([...]) calls.
- content = content.replace(/expect\((.+)\)\.toEqual\(\[([^;]+|)\]\);/g, 'assertEquals(asList($2), $1);');
- for (let before = null; before !== content;) {
- before = content;
- content = content.replace(/(asList\([^\)\']*)'/g, '$1"');
- }
- content = content.replace(/expect\((.+)\)\.toEqual\((.+)\);/g, 'assertEquals($2, $1);');
-
- content = content.replace(/(?<!.files)\[(\d+)\]/g, '.get($1)');
- content = content.replace(/\[("[^"]+")\]/g, '.get($1)');
- content = content.replace(/.push\(/g, '.add(');
-
- // Define common types
- content = content.replace(/const request = playwright.request.newContext/g, 'APIRequestContext request = playwright.request.newContext');
- content = content.replace(/const (browser[^\s=]*) = /g, 'Browser $1 = ');
- content = content.replace(/const sizes = /g, 'Sizes sizes = ');
- content = content.replace(/const remote = /g, 'Browser remote = ');
- content = content.replace(/const context = /g, 'BrowserContext context = ');
- content = content.replace(/const (page[^\s=]*) = /g, 'Page $1 = ');
- content = content.replace(/const newPage = /g, 'Page newPage = ');
- content = content.replace(/const button/g, 'ElementHandle button');
- content = content.replace(/const result = /g, 'Object result = ');
- content = content.replace(/const response = /g, 'Response response = ');
- content = content.replace(/const request = /g, 'Request request = ');
- content = content.replace(/const requests = \[\];/g, 'List<Request> requests = new ArrayList<>();');
- content = content.replace(/const snapshot = page.accessibility/g, 'AccessibilityNode snapshot = page.accessibility');
- content = content.replace(/snapshot\.children\./g, 'snapshot.children().');
- content = content.replace(/const (.+) = \[\];/g, 'List<> $1 = new ArrayList<>();');
- content = content.replace(/const (\w+ = .+evalOnSelector)/g, 'Object $1');
- content = content.replace(/const (\w+ = .+querySelector)/g, 'ElementHandle $1');
- content = content.replace(/const messages = \[\]/g, 'List<String> messages = new ArrayList<>()');
- content = content.replace(/const frame = /g, 'Frame frame = ');
- content = content.replace(/const elementHandle = (.+)/g, 'JSHandle jsHandle = $1\n ElementHandle elementHandle = jsHandle.asElement();\n assertNotNull(elementHandle);');
- content = content.replace(/const (\w+ = \w+\.boundingBox)/g, 'ElementHandle.BoundingBox $1');
- content = content.replace(/assertEquals\({ x: (\d+), y: (\d+), width: (\d+), height: (\d+) }, box\);/g, `assertEquals(box.x, $1);
- assertEquals(box.y, $2);
- assertEquals(box.width, $3);
- assertEquals(box.height, $4);`);
- content = content.replace(/setViewportSize\({ width: (\d+), height: (\d+) }\)/g, 'setViewportSize($1, $2)');
- content = content.replace(/\.on\("([^"]+)", /g, (match, p1, offset, string) => `\.on${toTitleCase(p1)}(`);
- content = content.replace(/page.waitForEvent\("([^"]+)"/g, (match, p1, offset, string) => `page.waitFor${toTitleCase(p1)}(`);
- content = content.replace(/server.waitForRequest/g, 'server.futureRequest');
- content = content.replace(/context.request/g, 'context.request()');
- content = content.replace(/page.request/g, 'page.request()');
- content = content.replace(/playwright.request/g, 'playwright.request()');
-
- // try/catch
- content = content.replace(/const error = /g, 'try {\n');
- content = content.replace(/\.catch\(e => e\)[;,]/g, ';\nfail("did not throw");\n} catch (PlaywrightException e) {}\n');
- content = content.replace(/(.+)\.catch\(e => error = e\);/g, ' try {\n $1;\n fail("did not throw");\n } catch (PlaywrightException e) {\n }\n');
-
- const output = file.replace(/\.spec\.ts$/, ".java")
- console.log('Writing: ' + output);
- await util.promisify(fs.writeFile)(output, content)
-})();
-
-function toTitleCase(s) {
- return s[0].toUpperCase() + s.substr(1);
-}
\ No newline at end of file