@xylentis/testgen 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,235 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { asLocators } from './locatorGenerators.js';
17
+ import { encodeTestIdAttributeName } from './locatorUtils.js';
18
+ import { parseSelector } from './selectorParser.js';
19
+ import { escapeForAttributeSelector, escapeForTextSelector } from './stringUtils.js';
20
+ function parseLocator(locator, testIdAttributeName) {
21
+ locator = locator
22
+ .replace(/AriaRole\s*\.\s*([\w]+)/g, (_, group) => group.toLowerCase())
23
+ .replace(/(get_by_role|getByRole)\s*\(\s*(?:["'`])([^'"`]+)['"`]/g, (_, group1, group2) => `${group1}(${group2.toLowerCase()}`);
24
+ const params = [];
25
+ let template = '';
26
+ for (let i = 0; i < locator.length; ++i) {
27
+ const quote = locator[i];
28
+ if (quote !== '"' && quote !== '\'' && quote !== '`' && quote !== '/') {
29
+ template += quote;
30
+ continue;
31
+ }
32
+ const isRegexEscaping = locator[i - 1] === 'r' || locator[i] === '/';
33
+ ++i;
34
+ let text = '';
35
+ while (i < locator.length) {
36
+ if (locator[i] === '\\') {
37
+ if (isRegexEscaping) {
38
+ if (locator[i + 1] !== quote)
39
+ text += locator[i];
40
+ ++i;
41
+ text += locator[i];
42
+ }
43
+ else {
44
+ ++i;
45
+ if (locator[i] === 'n')
46
+ text += '\n';
47
+ else if (locator[i] === 'r')
48
+ text += '\r';
49
+ else if (locator[i] === 't')
50
+ text += '\t';
51
+ else
52
+ text += locator[i];
53
+ }
54
+ ++i;
55
+ continue;
56
+ }
57
+ if (locator[i] !== quote) {
58
+ text += locator[i++];
59
+ continue;
60
+ }
61
+ break;
62
+ }
63
+ params.push({ quote, text });
64
+ template += (quote === '/' ? 'r' : '') + '$' + params.length;
65
+ }
66
+ // Equalize languages.
67
+ template = template.toLowerCase()
68
+ .replace(/get_by_alt_text/g, 'getbyalttext')
69
+ .replace(/get_by_test_id/g, 'getbytestid')
70
+ .replace(/get_by_([\w]+)/g, 'getby$1')
71
+ .replace(/has_not_text/g, 'hasnottext')
72
+ .replace(/has_text/g, 'hastext')
73
+ .replace(/has_not/g, 'hasnot')
74
+ .replace(/frame_locator/g, 'framelocator')
75
+ .replace(/content_frame/g, 'contentframe')
76
+ .replace(/[{}\s]/g, '')
77
+ .replace(/new\(\)/g, '')
78
+ .replace(/new[\w]+\.[\w]+options\(\)/g, '')
79
+ .replace(/\.set/g, ',set')
80
+ .replace(/\.or_\(/g, 'or(') // Python has "or_" instead of "or".
81
+ .replace(/\.and_\(/g, 'and(') // Python has "and_" instead of "and".
82
+ .replace(/:/g, '=')
83
+ .replace(/,re\.ignorecase/g, 'i')
84
+ .replace(/,pattern.case_insensitive/g, 'i')
85
+ .replace(/,regexoptions.ignorecase/g, 'i')
86
+ .replace(/re.compile\(([^)]+)\)/g, '$1') // Python has regex strings as r"foo"
87
+ .replace(/pattern.compile\(([^)]+)\)/g, 'r$1')
88
+ .replace(/newregex\(([^)]+)\)/g, 'r$1')
89
+ .replace(/string=/g, '=')
90
+ .replace(/regex=/g, '=')
91
+ .replace(/,,/g, ',')
92
+ .replace(/,\)/g, ')');
93
+ const preferredQuote = params.map(p => p.quote).filter(quote => '\'"`'.includes(quote))[0];
94
+ return { selector: transform(template, params, testIdAttributeName), preferredQuote };
95
+ }
96
+ function countParams(template) {
97
+ return [...template.matchAll(/\$\d+/g)].length;
98
+ }
99
+ function shiftParams(template, sub) {
100
+ return template.replace(/\$(\d+)/g, (_, ordinal) => `$${ordinal - sub}`);
101
+ }
102
+ function transform(template, params, testIdAttributeName) {
103
+ // Recursively handle filter(has=, hasnot=, sethas(), sethasnot()).
104
+ // TODO: handle and(locator), or(locator), locator(locator), locator(has=, hasnot=, sethas(), sethasnot()).
105
+ while (true) {
106
+ const hasMatch = template.match(/filter\(,?(has=|hasnot=|sethas\(|sethasnot\()/);
107
+ if (!hasMatch)
108
+ break;
109
+ // Extract inner locator based on balanced parens.
110
+ const start = hasMatch.index + hasMatch[0].length;
111
+ let balance = 0;
112
+ let end = start;
113
+ for (; end < template.length; end++) {
114
+ if (template[end] === '(')
115
+ balance++;
116
+ else if (template[end] === ')')
117
+ balance--;
118
+ if (balance < 0)
119
+ break;
120
+ }
121
+ // Replace Java sethas(...) and sethasnot(...) with has=... and hasnot=...
122
+ let prefix = template.substring(0, start);
123
+ let extraSymbol = 0;
124
+ if (['sethas(', 'sethasnot('].includes(hasMatch[1])) {
125
+ // Eat extra ) symbol at the end of sethas(...)
126
+ extraSymbol = 1;
127
+ prefix = prefix.replace(/sethas\($/, 'has=').replace(/sethasnot\($/, 'hasnot=');
128
+ }
129
+ const paramsCountBeforeHas = countParams(template.substring(0, start));
130
+ const hasTemplate = shiftParams(template.substring(start, end), paramsCountBeforeHas);
131
+ const paramsCountInHas = countParams(hasTemplate);
132
+ const hasParams = params.slice(paramsCountBeforeHas, paramsCountBeforeHas + paramsCountInHas);
133
+ const hasSelector = JSON.stringify(transform(hasTemplate, hasParams, testIdAttributeName));
134
+ // Replace filter(has=...) with filter(has2=$5). Use has2 to avoid matching the same filter again.
135
+ // Replace filter(hasnot=...) with filter(hasnot2=$5). Use hasnot2 to avoid matching the same filter again.
136
+ template = prefix.replace(/=$/, '2=') + `$${paramsCountBeforeHas + 1}` + shiftParams(template.substring(end + extraSymbol), paramsCountInHas - 1);
137
+ // Replace inner params with $5 value.
138
+ const paramsBeforeHas = params.slice(0, paramsCountBeforeHas);
139
+ const paramsAfterHas = params.slice(paramsCountBeforeHas + paramsCountInHas);
140
+ params = paramsBeforeHas.concat([{ quote: '"', text: hasSelector }]).concat(paramsAfterHas);
141
+ }
142
+ // Transform to selector engines.
143
+ template = template
144
+ .replace(/\,set([\w]+)\(([^)]+)\)/g, (_, group1, group2) => ',' + group1.toLowerCase() + '=' + group2.toLowerCase())
145
+ .replace(/framelocator\(\)/g, 'internal:control=any-frame')
146
+ .replace(/framelocator\(([^)]+)\)/g, '$1.internal:control=enter-frame')
147
+ .replace(/contentframe(\(\))?/g, 'internal:control=enter-frame')
148
+ .replace(/locator\(([^)]+),hastext=([^),]+)\)/g, 'locator($1).internal:has-text=$2')
149
+ .replace(/locator\(([^)]+),hasnottext=([^),]+)\)/g, 'locator($1).internal:has-not-text=$2')
150
+ .replace(/locator\(([^)]+),hastext=([^),]+)\)/g, 'locator($1).internal:has-text=$2')
151
+ .replace(/locator\(([^)]+)\)/g, '$1')
152
+ .replace(/getbyrole\(([^)]+)\)/g, 'internal:role=$1')
153
+ .replace(/getbytext\(([^)]+)\)/g, 'internal:text=$1')
154
+ .replace(/getbylabel\(([^)]+)\)/g, 'internal:label=$1')
155
+ .replace(/getbytestid\(([^)]+)\)/g, `internal:testid=[${encodeTestIdAttributeName(testIdAttributeName)}=$1]`)
156
+ .replace(/getby(placeholder|alt|title)(?:text)?\(([^)]+)\)/g, 'internal:attr=[$1=$2]')
157
+ .replace(/first(\(\))?/g, 'nth=0')
158
+ .replace(/last(\(\))?/g, 'nth=-1')
159
+ .replace(/nth\(([^)]+)\)/g, 'nth=$1')
160
+ .replace(/filter\(,?visible=true\)/g, 'visible=true')
161
+ .replace(/filter\(,?visible=false\)/g, 'visible=false')
162
+ .replace(/\.visible(\(\))?(?!=)/g, '.visible=true')
163
+ .replace(/filter\(,?hastext=([^)]+)\)/g, 'internal:has-text=$1')
164
+ .replace(/filter\(,?hasnottext=([^)]+)\)/g, 'internal:has-not-text=$1')
165
+ .replace(/filter\(,?has2=([^)]+)\)/g, 'internal:has=$1')
166
+ .replace(/filter\(,?hasnot2=([^)]+)\)/g, 'internal:has-not=$1')
167
+ .replace(/,exact=false/g, '')
168
+ .replace(/(,name=\$\d+)(,description=\$\d+),exact=true/g, '$1s$2s') // exact=true is shared between name and description, so we need a special case for applying it to both.
169
+ .replace(/,exact=true/g, 's')
170
+ .replace(/,includehidden=/g, ',include-hidden=')
171
+ .replace(/\,/g, '][');
172
+ const parts = template.split('.');
173
+ // Turn "internal:control=enter-frame >> nth=0" into "nth=0 >> internal:control=enter-frame"
174
+ // because these are swapped in locators vs selectors.
175
+ for (let index = 0; index < parts.length - 1; index++) {
176
+ if (parts[index] === 'internal:control=enter-frame' && parts[index + 1].startsWith('nth=')) {
177
+ // Swap nth and enter-frame.
178
+ const [nth] = parts.splice(index, 1);
179
+ parts.splice(index + 1, 0, nth);
180
+ }
181
+ }
182
+ // Substitute params.
183
+ return parts.map(t => {
184
+ if (!t.startsWith('internal:') || t === 'internal:control')
185
+ return t.replace(/\$(\d+)/g, (_, ordinal) => { const param = params[+ordinal - 1]; return param.text; });
186
+ t = t.includes('[') ? t.replace(/\]/, '') + ']' : t;
187
+ t = t
188
+ .replace(/(?:r)\$(\d+)(i)?/g, (_, ordinal, suffix) => {
189
+ const param = params[+ordinal - 1];
190
+ if (t.startsWith('internal:attr') || t.startsWith('internal:testid') || t.startsWith('internal:role'))
191
+ return escapeForAttributeSelector(new RegExp(param.text), false) + (suffix || '');
192
+ return escapeForTextSelector(new RegExp(param.text, suffix), false);
193
+ })
194
+ .replace(/\$(\d+)(i|s)?/g, (_, ordinal, suffix) => {
195
+ const param = params[+ordinal - 1];
196
+ if (t.startsWith('internal:has=') || t.startsWith('internal:has-not='))
197
+ return param.text;
198
+ if (t.startsWith('internal:testid'))
199
+ return escapeForAttributeSelector(param.text, true);
200
+ if (t.startsWith('internal:attr') || t.startsWith('internal:role'))
201
+ return escapeForAttributeSelector(param.text, suffix === 's');
202
+ return escapeForTextSelector(param.text, suffix === 's');
203
+ });
204
+ return t;
205
+ }).join(' >> ');
206
+ }
207
+ export function locatorOrSelectorAsSelector(language, locator, testIdAttributeName = 'data-testid') {
208
+ try {
209
+ return unsafeLocatorOrSelectorAsSelector(language, locator, testIdAttributeName);
210
+ }
211
+ catch (e) {
212
+ return '';
213
+ }
214
+ }
215
+ export function unsafeLocatorOrSelectorAsSelector(language, locator, testIdAttributeName = 'data-testid') {
216
+ try {
217
+ parseSelector(locator);
218
+ return locator;
219
+ }
220
+ catch (e) {
221
+ }
222
+ const { selector, preferredQuote } = parseLocator(locator, testIdAttributeName);
223
+ const locators = asLocators(language, selector, undefined, undefined, preferredQuote);
224
+ const digest = digestForComparison(language, locator);
225
+ if (locators.some(candidate => digestForComparison(language, candidate) === digest))
226
+ return selector;
227
+ return '';
228
+ }
229
+ function digestForComparison(language, locator) {
230
+ locator = locator.replace(/\s/g, '');
231
+ if (language === 'javascript')
232
+ locator = locator.replace(/\\?["`]/g, '\'').replace(/,{}/g, '');
233
+ return locator;
234
+ }
235
+ //# sourceMappingURL=locatorParser.js.map
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { escapeForAttributeSelector, escapeForTextSelector } from './stringUtils.js';
17
+ function getByAttributeTextSelector(attrName, text, options) {
18
+ return `internal:attr=[${attrName}=${escapeForAttributeSelector(text, options?.exact || false)}]`;
19
+ }
20
+ // Multiple test id attribute names can be joined with a comma. Attribute names cannot contain commas.
21
+ export function splitTestIdAttributeNames(testIdAttributeName) {
22
+ return testIdAttributeName.split(',');
23
+ }
24
+ export function encodeTestIdAttributeName(testIdAttributeName) {
25
+ return testIdAttributeName.includes(',') ? JSON.stringify(testIdAttributeName) : testIdAttributeName;
26
+ }
27
+ export function getByTestIdSelector(testIdAttributeName, testId) {
28
+ return `internal:testid=[${encodeTestIdAttributeName(testIdAttributeName)}=${escapeForAttributeSelector(testId, true)}]`;
29
+ }
30
+ export function getByLabelSelector(text, options) {
31
+ return 'internal:label=' + escapeForTextSelector(text, !!options?.exact);
32
+ }
33
+ export function getByAltTextSelector(text, options) {
34
+ return getByAttributeTextSelector('alt', text, options);
35
+ }
36
+ export function getByTitleSelector(text, options) {
37
+ return getByAttributeTextSelector('title', text, options);
38
+ }
39
+ export function getByPlaceholderSelector(text, options) {
40
+ return getByAttributeTextSelector('placeholder', text, options);
41
+ }
42
+ export function getByTextSelector(text, options) {
43
+ return 'internal:text=' + escapeForTextSelector(text, !!options?.exact);
44
+ }
45
+ export function getByRoleSelector(role, options = {}) {
46
+ const props = [];
47
+ if (options.checked !== undefined)
48
+ props.push(['checked', String(options.checked)]);
49
+ if (options.disabled !== undefined)
50
+ props.push(['disabled', String(options.disabled)]);
51
+ if (options.selected !== undefined)
52
+ props.push(['selected', String(options.selected)]);
53
+ if (options.expanded !== undefined)
54
+ props.push(['expanded', String(options.expanded)]);
55
+ if (options.includeHidden !== undefined)
56
+ props.push(['include-hidden', String(options.includeHidden)]);
57
+ if (options.level !== undefined)
58
+ props.push(['level', String(options.level)]);
59
+ if (options.name !== undefined)
60
+ props.push(['name', escapeForAttributeSelector(options.name, !!options.exact)]);
61
+ if (options.description !== undefined)
62
+ props.push(['description', escapeForAttributeSelector(options.description, !!options.exact)]);
63
+ if (options.pressed !== undefined)
64
+ props.push(['pressed', String(options.pressed)]);
65
+ return `internal:role=${role}${props.map(([n, v]) => `[${n}=${v}]`).join('')}`;
66
+ }
67
+ //# sourceMappingURL=locatorUtils.js.map
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xylentis/testgen",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Record a UI test once with the Playwright recorder, then generate it for Playwright (TypeScript, Go) and Selenium (Java, JavaScript).",
5
5
  "keywords": [
6
6
  "playwright",
@@ -11,6 +11,7 @@
11
11
  "e2e",
12
12
  "playwright-go",
13
13
  "junit",
14
+ "testng",
14
15
  "mocha"
15
16
  ],
16
17
  "author": "Xylentis (https://portal.xylentis.com)",
@@ -39,7 +40,8 @@
39
40
  "prepare": "npm run build",
40
41
  "typecheck": "tsc -p tsconfig.json --noEmit",
41
42
  "test": "vitest run",
42
- "e2e": "bash e2e/run.sh"
43
+ "e2e": "bash e2e/run.sh",
44
+ "release": "node scripts/release.mjs"
43
45
  },
44
46
  "dependencies": {
45
47
  "playwright-core": "1.63.0"
@@ -0,0 +1,64 @@
1
+ // Generated by testgen: rewritten every time tests are generated, do not edit.
2
+ // testgen (@xylentis/testgen), Copyright (C) 2026 Xylentis. Licensed under AGPL-3.0-only with an additional
3
+ // permission: as part of tests generated by testgen, this file may be used, modified and distributed under
4
+ // terms of your choice (see NOTICE in @xylentis/testgen).
5
+
6
+ package e2e
7
+
8
+ import (
9
+ "bytes"
10
+ "encoding/csv"
11
+ "os"
12
+ "strings"
13
+ "testing"
14
+ )
15
+
16
+ // readTestgenCSV returns the rows of the CSV data file of a data-driven test, with the given columns.
17
+ // The file is UTF-8, with or without a BOM, separated by commas or semicolons (as Excel saves it in
18
+ // some languages), and its first line names the columns; other columns are ignored, blank lines skipped.
19
+ func readTestgenCSV(t *testing.T, file string, columns ...string) []map[string]string {
20
+ t.Helper()
21
+ data, err := os.ReadFile(file)
22
+ if err != nil {
23
+ t.Fatalf("testgen: %v", err)
24
+ }
25
+ data = bytes.TrimPrefix(data, []byte("\uFEFF"))
26
+ reader := csv.NewReader(bytes.NewReader(data))
27
+ reader.FieldsPerRecord = -1
28
+ if firstLine, _, _ := strings.Cut(string(data), "\n"); !strings.Contains(firstLine, ",") && strings.Contains(firstLine, ";") {
29
+ reader.Comma = ';'
30
+ }
31
+ records, err := reader.ReadAll()
32
+ if err != nil {
33
+ t.Fatalf("testgen: data file %s: %v", file, err)
34
+ }
35
+ if len(records) == 0 {
36
+ t.Fatalf("testgen: data file %s is empty", file)
37
+ }
38
+ header := map[string]int{}
39
+ for i, name := range records[0] {
40
+ header[strings.TrimSpace(name)] = i
41
+ }
42
+ for _, column := range columns {
43
+ if _, ok := header[column]; !ok {
44
+ t.Fatalf("testgen: data file %s has no column %q (it has %s)", file, column, strings.Join(records[0], ", "))
45
+ }
46
+ }
47
+ var rows []map[string]string
48
+ for _, record := range records[1:] {
49
+ if strings.TrimSpace(strings.Join(record, "")) == "" {
50
+ continue
51
+ }
52
+ row := map[string]string{}
53
+ for _, column := range columns {
54
+ if i := header[column]; i < len(record) {
55
+ row[column] = record[i]
56
+ }
57
+ }
58
+ rows = append(rows, row)
59
+ }
60
+ if len(rows) == 0 {
61
+ t.Fatalf("testgen: data file %s has no data rows", file)
62
+ }
63
+ return rows
64
+ }
@@ -0,0 +1,70 @@
1
+ // Generated by testgen: rewritten every time tests are generated, do not edit.
2
+ // testgen (@xylentis/testgen), Copyright (C) 2026 Xylentis. Licensed under AGPL-3.0-only with an additional
3
+ // permission: as part of tests generated by testgen, this file may be used, modified and distributed under
4
+ // terms of your choice (see NOTICE in @xylentis/testgen).
5
+ import fs from 'node:fs';
6
+
7
+ /**
8
+ * Rows of the CSV data file of a data-driven test, as objects with the given columns. The file is UTF-8,
9
+ * with or without a BOM, separated by commas or semicolons (as Excel saves it in some languages), and its
10
+ * first line names the columns; other columns are ignored, blank lines skipped.
11
+ */
12
+ export function readCsv<Column extends string>(file: string, columns: Column[]): Record<Column, string>[] {
13
+ const text = fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '');
14
+ const firstLine = text.split(/\r?\n/, 1)[0];
15
+ const separator = !firstLine.includes(',') && firstLine.includes(';') ? ';' : ',';
16
+ const [header, ...records] = parseCsv(text, separator);
17
+ if (!header)
18
+ throw new Error(`testgen: data file ${file} is empty`);
19
+ const names = header.map(name => name.trim());
20
+ for (const column of columns) {
21
+ if (!names.includes(column))
22
+ throw new Error(`testgen: data file ${file} has no column "${column}" (it has ${names.join(', ')})`);
23
+ }
24
+ const rows = records
25
+ .filter(record => record.some(cell => cell.trim()))
26
+ .map(record => Object.fromEntries(columns.map(column => [column, record[names.indexOf(column)] ?? ''])) as Record<Column, string>);
27
+ if (!rows.length)
28
+ throw new Error(`testgen: data file ${file} has no data rows`);
29
+ return rows;
30
+ }
31
+
32
+ // RFC 4180: quoted fields may contain separators, line breaks and doubled quotes.
33
+ function parseCsv(text: string, separator: string): string[][] {
34
+ const rows: string[][] = [];
35
+ let row: string[] = [];
36
+ let field = '';
37
+ let quoted = false;
38
+ for (let i = 0; i < text.length; i++) {
39
+ const c = text[i];
40
+ if (quoted) {
41
+ if (c === '"' && text[i + 1] === '"') {
42
+ field += '"';
43
+ i++;
44
+ } else if (c === '"') {
45
+ quoted = false;
46
+ } else {
47
+ field += c;
48
+ }
49
+ } else if (c === '"') {
50
+ quoted = true;
51
+ } else if (c === separator) {
52
+ row.push(field);
53
+ field = '';
54
+ } else if (c === '\n' || c === '\r') {
55
+ if (c === '\r' && text[i + 1] === '\n')
56
+ i++;
57
+ row.push(field);
58
+ rows.push(row);
59
+ row = [];
60
+ field = '';
61
+ } else {
62
+ field += c;
63
+ }
64
+ }
65
+ if (field || row.length) {
66
+ row.push(field);
67
+ rows.push(row);
68
+ }
69
+ return rows;
70
+ }