@fluxenginejp/sftest 1.2.0 → 1.3.1

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,380 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.messageLines = messageLines;
7
+ exports.formatDuration = formatDuration;
8
+ exports.stepText = stepText;
9
+ /**
10
+ * 実行中の経過を、シナリオとステップごとに1行ずつ標準出力に表示する Playwright のレポーター(20261015-011)。
11
+ *
12
+ * Playwright の既定の表示(line レポーター)は、1行を上書きしながら表示し、失敗の最後にスタックトレースとコードの抜粋を表示する。
13
+ * このレポーターは、どこまで実行されたか、どこで異常があったかを分かるように、次のとおり表示する。
14
+ * - シナリオの開始: 番号・機能・シナリオ名。
15
+ * - ステップ(背景を含む、シナリオに書いたステップ)の終了ごと: 結果(OK・NG・不一致)と所要時間。
16
+ * - 失敗したステップの下: エラーのメッセージだけ(スタックトレース・コードの抜粋・呼び出しの記録は出さない)。
17
+ * - シナリオの終了: 結果と所要時間。ステップの外の失敗(終了時の判定・後片付け)や、制限時間の超過も示す。
18
+ * - 最後: 件数と、詳しい結果(HTML レポート)の開き方。
19
+ * 詳しいエラー(スタックトレースなど)は、HTML レポートで確認する。
20
+ *
21
+ * @author Fluxengine.co.jp
22
+ */
23
+ const node_path_1 = __importDefault(require("node:path"));
24
+ /** エラーのメッセージとして表示する最大の行数。 */
25
+ const MAX_MESSAGE_LINES = 12;
26
+ /**
27
+ * エラーのメッセージから、利用者に示す部分だけを取り出す。
28
+ *
29
+ * 色の制御文字を除き、Playwright の呼び出しの記録(Call log 以降)とスタックトレース(at で始まる行)を除く。
30
+ *
31
+ * @param error - Playwright のエラー。
32
+ * @returns 表示する行(最大 MAX_MESSAGE_LINES 行)。
33
+ */
34
+ function messageLines(error) {
35
+ const text = (error?.message ?? error?.value ?? '').replace(/\u001b\[[0-9;]*m/g, '');
36
+ const lines = [];
37
+ for (const raw of text.split(/\r?\n/)) {
38
+ const line = raw.trimEnd();
39
+ if (/^\s*Call log:/i.test(line))
40
+ break; // expect.poll では「Call Log:」と書かれる。
41
+ if (/^\s+at /.test(line))
42
+ continue;
43
+ if (!line.trim() && (!lines.length || !lines[lines.length - 1].trim()))
44
+ continue;
45
+ lines.push(line.replace(/^Error: /, ''));
46
+ }
47
+ while (lines.length && !lines[lines.length - 1].trim())
48
+ lines.pop();
49
+ if (lines.length > MAX_MESSAGE_LINES)
50
+ return [...lines.slice(0, MAX_MESSAGE_LINES), '…(続きは HTML レポートで確認してください)'];
51
+ return lines;
52
+ }
53
+ /**
54
+ * 所要時間を「1.2秒」「2分3秒」の形にする。
55
+ *
56
+ * @param ms - ミリ秒。
57
+ * @returns 表示用の文字。
58
+ */
59
+ function formatDuration(ms) {
60
+ if (ms < 60_000)
61
+ return `${(ms / 1000).toFixed(1)}秒`;
62
+ const total = Math.round(ms / 1000);
63
+ return `${Math.floor(total / 60)}分${total % 60}秒`;
64
+ }
65
+ /**
66
+ * ステップの題名を、シナリオに書いたとおりの「キーワード ステップの文」の形にする。
67
+ *
68
+ * playwright-bdd の題名は、キーワード(前提・もし・ならば・かつ・しかし)と文が空白なしでつながっているため、間に空白を入れる。
69
+ *
70
+ * @param title - ステップの題名。
71
+ * @returns 表示用の文字。
72
+ */
73
+ function stepText(title) {
74
+ return title.replace(/^(前提|もし|ならば|かつ|しかし|\*)\s*/, '$1 ');
75
+ }
76
+ /**
77
+ * シナリオに書いたステップ(Gherkin のステップ)かを返す。
78
+ *
79
+ * playwright-bdd は、各ステップを test.step(題名はキーワードとステップの文)として実行する。シナリオのステップはテストの直下で、
80
+ * 背景のステップは前処理(test.beforeEach「背景」。hook)の中で実行する(20261016-005)。そのため、祖先に test.step を持たない
81
+ * test.step をシナリオのステップとする(ステップの中で呼ばれる処理の test.step は対象にしない)。
82
+ *
83
+ * @param step - Playwright のステップ。
84
+ * @returns シナリオのステップ(背景を含む)なら true。
85
+ */
86
+ function isScenarioStep(step) {
87
+ if (step.category !== 'test.step')
88
+ return false;
89
+ for (let p = step.parent; p; p = p.parent)
90
+ if (p.category === 'test.step')
91
+ return false;
92
+ return true;
93
+ }
94
+ /**
95
+ * 背景のステップ(前処理の中のシナリオのステップ)かを返す(20261016-005)。
96
+ *
97
+ * @param step - シナリオのステップ。
98
+ * @returns 祖先に前処理(hook)があれば true。
99
+ */
100
+ function isBackgroundStep(step) {
101
+ for (let p = step.parent; p; p = p.parent)
102
+ if (p.category === 'hook')
103
+ return true;
104
+ return false;
105
+ }
106
+ /**
107
+ * ステップの中で、検査の不一致として記録されたもの(support/mismatch.ts の recordMismatch)を集める。
108
+ * ステップの中で受け止めて処理した待機の失敗などは、不一致に数えない。
109
+ *
110
+ * @param step - シナリオのステップ。
111
+ * @returns 不一致のエラー。
112
+ */
113
+ function recordedMismatches(step) {
114
+ const found = [];
115
+ const walk = (s) => {
116
+ if (s.error && /toBeRecordedMismatch/.test(s.title))
117
+ found.push(s.error);
118
+ for (const child of s.steps)
119
+ walk(child);
120
+ };
121
+ for (const child of step.steps)
122
+ walk(child);
123
+ return found;
124
+ }
125
+ /** 実行中の経過を、ステップごとに1行ずつ表示するレポーター。 */
126
+ class ConsoleReporter {
127
+ total = 0;
128
+ started = 0;
129
+ numbers = new Map();
130
+ /** シナリオごとの、ステップの下に表示したエラーのメッセージ(ステップの外の失敗と重ねて表示しないため)。 */
131
+ shown = new Map();
132
+ /** ステップのエラー(記録した不一致を除く)で中断したシナリオ。 */
133
+ stopped = new Set();
134
+ /** シナリオごとの、最後に示した区切り((背景)・(シナリオ))。背景のないシナリオは区切りを示さない(20261016-005)。 */
135
+ parts = new Map();
136
+ counts = { passed: 0, failed: 0, expectedFailed: 0, unexpectedPassed: 0, timedOut: 0, skipped: 0, interrupted: 0 };
137
+ failedTitles = [];
138
+ reportCommand;
139
+ startedAt = Date.now();
140
+ /**
141
+ * 設定を受け取る。
142
+ *
143
+ * @param options - レポーターの設定。
144
+ */
145
+ constructor(options = {}) {
146
+ this.reportCommand = options.reportCommand ?? 'npx sftest report';
147
+ this.listOnly = options._mode === 'list';
148
+ }
149
+ /**
150
+ * --list のとき、シナリオを実行せず一覧だけを表示する(20261016-003)。
151
+ * このレポーターが画面に書くため、Playwright は一覧の表示用のレポーターを加えない。そのため、ここで一覧を表示する。
152
+ */
153
+ listOnly;
154
+ /** 標準出力に書くレポーターであることを Playwright に知らせる(既定の line レポーターを加えさせない)。 */
155
+ printsToStdio() {
156
+ return true;
157
+ }
158
+ /**
159
+ * 実行の開始。シナリオの件数を表示する。
160
+ *
161
+ * @param _config - 設定。
162
+ * @param suite - 実行するシナリオの全体。
163
+ */
164
+ onBegin(config, suite) {
165
+ const tests = suite.allTests();
166
+ this.total = tests.length;
167
+ this.startedAt = Date.now();
168
+ if (this.listOnly) {
169
+ // --list: 番号・機能 › シナリオ・生成したテストの位置を1行ずつ示し、件数とファイルの数で終える(実行はしない)。
170
+ this.write('実行の対象のシナリオ(--list のため、実行はしません):');
171
+ const files = new Set();
172
+ tests.forEach((test, i) => {
173
+ const location = `${node_path_1.default.relative(config.rootDir, test.location.file).replace(/\\/g, '/')}:${test.location.line}`;
174
+ this.write(` [${i + 1}] ${this.titleOf(test)}(${location})`);
175
+ files.add(test.location.file);
176
+ });
177
+ this.write(`合計: ${this.total} 件のシナリオ(${files.size} ファイル)`);
178
+ return;
179
+ }
180
+ this.write(`${this.total} 件のシナリオを実行します。`);
181
+ }
182
+ /**
183
+ * シナリオの開始。番号・機能・シナリオ名を表示する。
184
+ *
185
+ * @param test - シナリオ。
186
+ */
187
+ onTestBegin(test) {
188
+ this.started += 1;
189
+ this.numbers.set(test, this.started);
190
+ this.shown.set(test, new Set());
191
+ this.write('');
192
+ this.write(`[${this.started}/${this.total}] ${this.titleOf(test)}`);
193
+ }
194
+ /**
195
+ * ステップの終了。シナリオのステップだけ、結果と所要時間を1行で表示し、失敗・不一致の場合はメッセージを続けて表示する。
196
+ *
197
+ * @param test - シナリオ。
198
+ * @param _result - シナリオの結果。
199
+ * @param step - 終了したステップ。
200
+ */
201
+ onStepEnd(test, _result, step) {
202
+ if (!isScenarioStep(step))
203
+ return;
204
+ // 背景のステップの前に「(背景)」、背景の後のシナリオのステップの前に「(シナリオ)」を1回ずつ示す(20261016-005)。
205
+ const part = isBackgroundStep(step) ? '(背景)' : this.parts.get(test) ? '(シナリオ)' : undefined;
206
+ if (part && this.parts.get(test) !== part) {
207
+ this.write(` ${part}`);
208
+ this.parts.set(test, part);
209
+ }
210
+ // 記録した不一致は、ステップのエラーにもなる(expect.soft)。ステップのエラーが記録した不一致のどれかと同じなら、
211
+ // 中断ではなく不一致として表示する(後続のステップへ進む)。それ以外のエラーは、そのステップで中断した。
212
+ const mismatches = recordedMismatches(step);
213
+ const key = (error) => messageLines(error).join('\n');
214
+ const mismatchOnly = mismatches.length > 0 && (!step.error || mismatches.some((m) => key(m) === key(step.error)));
215
+ const mark = mismatchOnly ? '不一致' : step.error ? 'NG ' : 'OK ';
216
+ this.write(` ${mark} ${stepText(step.title)}(${formatDuration(step.duration)})`);
217
+ if (mismatchOnly) {
218
+ for (const error of mismatches)
219
+ this.writeError(test, error);
220
+ }
221
+ else if (step.error) {
222
+ this.writeError(test, step.error);
223
+ this.stopped.add(test);
224
+ }
225
+ }
226
+ /**
227
+ * テストの中から標準出力に書かれた内容(開始前の計測など)を、そのまま表示する。
228
+ *
229
+ * @param chunk - 書かれた内容。
230
+ */
231
+ onStdOut(chunk) {
232
+ process.stdout.write(chunk);
233
+ }
234
+ /**
235
+ * テストの中から標準エラーに書かれた内容を、そのまま表示する。
236
+ *
237
+ * @param chunk - 書かれた内容。
238
+ */
239
+ onStdErr(chunk) {
240
+ process.stderr.write(chunk);
241
+ }
242
+ /**
243
+ * シナリオの終了。ステップの外の失敗と、シナリオの結果を表示する。
244
+ *
245
+ * @param test - シナリオ。
246
+ * @param result - シナリオの結果。
247
+ */
248
+ onTestEnd(test, result) {
249
+ const shown = this.shown.get(test) ?? new Set();
250
+ const outside = result.errors.filter((error) => !shown.has(messageLines(error).join('\n')));
251
+ if (this.stopped.has(test) && result.status !== 'timedOut')
252
+ this.write(' (このステップで中断し、以降のステップは実行していません)');
253
+ if (result.status === 'timedOut') {
254
+ this.write(` NG シナリオの制限時間(${formatDuration(test.timeout)})を超えました。実行中のステップを止めました。`);
255
+ }
256
+ for (const error of outside) {
257
+ // 制限時間の超過は上で日本語で示したため、Playwright の英語のメッセージは重ねて表示しない。
258
+ if (result.status === 'timedOut' && /Test timeout of \d+ms exceeded/.test(error.message ?? ''))
259
+ continue;
260
+ this.write(' NG シナリオの終了時');
261
+ this.writeError(test, error);
262
+ }
263
+ const label = this.resultLabel(test, result);
264
+ this.write(` → ${label}(${formatDuration(result.duration)})`);
265
+ }
266
+ /**
267
+ * 実行全体にかかわるエラー(全体の前処理の失敗など)を、メッセージだけ表示する。
268
+ *
269
+ * @param error - エラー。
270
+ */
271
+ onError(error) {
272
+ this.write('');
273
+ this.write('NG 実行の途中でエラーが発生しました');
274
+ for (const line of messageLines(error))
275
+ this.write(` ${line}`);
276
+ }
277
+ /**
278
+ * 実行の終了。件数と、失敗したシナリオ、詳しい結果の開き方を表示する。
279
+ *
280
+ * @param result - 実行全体の結果。
281
+ */
282
+ onEnd(result) {
283
+ if (this.listOnly)
284
+ return; // --list は実行していないため、結果の行を出さない。
285
+ const c = this.counts;
286
+ const parts = [`成功 ${c.passed} 件`];
287
+ if (c.expectedFailed)
288
+ parts.push(`期待どおりの失敗(@fail) ${c.expectedFailed} 件`);
289
+ if (c.failed)
290
+ parts.push(`失敗 ${c.failed} 件`);
291
+ if (c.timedOut)
292
+ parts.push(`制限時間の超過 ${c.timedOut} 件`);
293
+ if (c.unexpectedPassed)
294
+ parts.push(`失敗を期待したのに成功 ${c.unexpectedPassed} 件`);
295
+ if (c.interrupted)
296
+ parts.push(`中止 ${c.interrupted} 件`);
297
+ if (c.skipped)
298
+ parts.push(`実行しなかった ${c.skipped} 件`);
299
+ this.write('');
300
+ this.write(`結果: ${parts.join('、')}(全 ${this.total} 件、${formatDuration(Date.now() - this.startedAt)})${result.status === 'interrupted' ? '。途中で中止しました' : ''}`);
301
+ if (this.failedTitles.length) {
302
+ this.write('期待と異なったシナリオ:');
303
+ for (const title of this.failedTitles)
304
+ this.write(` ${title}`);
305
+ }
306
+ this.write(`詳しい結果(画面キャプチャー・エラーの詳細): ${this.reportCommand}`);
307
+ }
308
+ /**
309
+ * シナリオの結果を数え、表示用の文字を返す。
310
+ *
311
+ * @param test - シナリオ。
312
+ * @param result - シナリオの結果。
313
+ * @returns 表示用の文字。
314
+ */
315
+ resultLabel(test, result) {
316
+ const number = this.numbers.get(test);
317
+ const unexpected = (label) => {
318
+ this.failedTitles.push(`[${number}] ${this.titleOf(test)}(${label})`);
319
+ return label;
320
+ };
321
+ if (result.status === 'skipped') {
322
+ this.counts.skipped += 1;
323
+ return '実行しなかった';
324
+ }
325
+ if (result.status === 'interrupted') {
326
+ this.counts.interrupted += 1;
327
+ return unexpected('中止');
328
+ }
329
+ // 制限時間の超過は、@fail のシナリオでも期待と異なる結果とする(Playwright も失敗として数える)。期待した失敗の分岐より前に判定する。
330
+ if (result.status === 'timedOut') {
331
+ this.counts.timedOut += 1;
332
+ return unexpected('制限時間の超過');
333
+ }
334
+ if (test.expectedStatus === 'failed') {
335
+ if (result.status === 'passed') {
336
+ this.counts.unexpectedPassed += 1;
337
+ return unexpected('失敗を期待したのに成功');
338
+ }
339
+ this.counts.expectedFailed += 1;
340
+ return '期待どおりの失敗(@fail)';
341
+ }
342
+ if (result.status === 'passed') {
343
+ this.counts.passed += 1;
344
+ return '成功';
345
+ }
346
+ this.counts.failed += 1;
347
+ return unexpected('失敗');
348
+ }
349
+ /**
350
+ * シナリオの表示名(機能 › シナリオ)を返す。
351
+ *
352
+ * @param test - シナリオ。
353
+ * @returns 表示名。
354
+ */
355
+ titleOf(test) {
356
+ const feature = test.parent?.title;
357
+ return feature ? `${feature} › ${test.title}` : test.title;
358
+ }
359
+ /**
360
+ * エラーのメッセージを、ステップの下に字下げして表示し、表示済みとして覚える。
361
+ *
362
+ * @param test - シナリオ。
363
+ * @param error - エラー。
364
+ */
365
+ writeError(test, error) {
366
+ const lines = messageLines(error);
367
+ this.shown.get(test)?.add(lines.join('\n'));
368
+ for (const line of lines)
369
+ this.write(` ${line}`);
370
+ }
371
+ /**
372
+ * 1行を標準出力に書く。
373
+ *
374
+ * @param line - 書く行。
375
+ */
376
+ write(line) {
377
+ process.stdout.write(`${line}\n`);
378
+ }
379
+ }
380
+ exports.default = ConsoleReporter;
@@ -50,8 +50,13 @@ exports.test = playwright_bdd_1.test.extend({
50
50
  inAppGuidance: [
51
51
  async ({ page }, use, testInfo) => {
52
52
  // 案内のポップアップは「最小化」「最大化」「閉じる」ボタンを持つダイアログである(入力ダイアログなどには「最小化」がない)。
53
- // 「アプリケーション内ガイダンス」という文字は、読み上げ用の説明文として通常のダイアログにも含まれるため、条件に使わない。
54
- const prompt = page.getByRole('dialog').filter({ has: page.getByRole('button', { name: '最小化', exact: true }) });
53
+ // 「最小化」がなく、「アプリケーション内ガイダンスを一時停止」「閉じる」ボタンを持つ形もある(20261014-018。画面の中に浮かぶ案内)。
54
+ // 「アプリケーション内ガイダンス」という文字は、読み上げ用の説明文として通常のダイアログにも含まれるため、条件に使わない(ボタンの名前は完全一致で比べる)。
55
+ const prompt = page.getByRole('dialog').filter({
56
+ has: page
57
+ .getByRole('button', { name: '最小化', exact: true })
58
+ .or(page.getByRole('button', { name: 'アプリケーション内ガイダンスを一時停止', exact: true })),
59
+ });
55
60
  // 入力ダイアログが開いている間は、画面の覆いに遮られてマウスのクリックが届かないため、ボタンに直接クリックのイベントを送る(dispatchEvent)。
56
61
  // 閉じられなかった場合は、次の操作の前にもう一度試す。
57
62
  // 5秒の固定値は、ガイダンスの見出しの取得と閉じる操作のための短い待ち時間であり、画面の確認の制限時間(expect)とは分けている。
@@ -170,11 +175,12 @@ exports.test = playwright_bdd_1.test.extend({
170
175
  * 現在の画面の画面キャプチャーを取得してレポートに添付し、同じ画像をファイル(evidenceDir/<ID>_<名前>.png)にも保存する関数。
171
176
  *
172
177
  * ID が設定されていれば名前の先頭に付ける。同じシナリオで同じ名前になった場合は、ファイル名の末尾に _2, _3, … を付ける(上書きしない)。
178
+ * 通常はページ全体を撮る。options.fullPage が false の場合は画面の表示範囲だけを撮る(スクロールしながらの撮影。20261015-007)。
173
179
  */
174
180
  evidence: async ({ page, evidenceId, evidenceDir }, use, testInfo) => {
175
- await use(async (label) => {
181
+ await use(async (label, options) => {
176
182
  const name = evidenceId.prefix(label);
177
- const body = await page.screenshot({ fullPage: true });
183
+ const body = await page.screenshot({ fullPage: options?.fullPage ?? true });
178
184
  await testInfo.attach(name, { body, contentType: 'image/png' });
179
185
  (0, node_fs_1.mkdirSync)(evidenceDir, { recursive: true });
180
186
  const base = (0, evidenceId_1.safeFileName)(name, 120);
@@ -188,7 +194,8 @@ exports.test = playwright_bdd_1.test.extend({
188
194
  /**
189
195
  * シナリオの終了時に、未処理の保存エラー・ブラウザのダイアログを判定するかを返す(20261013-002)。
190
196
  *
191
- * 従来どおり、結果が期待どおり(通常は成功、@fail では失敗)の場合に判定する。加えて、検査の不一致を記録して続けた
197
+ * 従来どおり、結果が期待どおり(通常は成功、@fail では失敗)の場合に判定する。加えて、ステップが最後まで通った場合は、
198
+ * @fail のシナリオでも判定する(ほかに失敗がないため。アップロードエラーの判定と同じ。20261015-010)。検査の不一致を記録して続けた
192
199
  * シナリオは、中断していなければ判定する。中断(例外)で終わった場合は、元の失敗の原因を残すため判定しない。
193
200
  *
194
201
  * @param testInfo - シナリオの TestInfo。
@@ -197,7 +204,7 @@ exports.test = playwright_bdd_1.test.extend({
197
204
  function shouldJudgeLeftovers(testInfo) {
198
205
  if ((0, mismatch_1.wasInterrupted)(testInfo))
199
206
  return false;
200
- return testInfo.status === testInfo.expectedStatus || (0, mismatch_1.mismatchCount)(testInfo) > 0;
207
+ return testInfo.status === 'passed' || testInfo.status === testInfo.expectedStatus || (0, mismatch_1.mismatchCount)(testInfo) > 0;
201
208
  }
202
209
  /** sfTest のフィクスチャを使うステップ定義・フックの登録関数。 */
203
210
  const bdd = (0, playwright_bdd_1.createBdd)(exports.test);
@@ -32,6 +32,11 @@ export interface SfTestConfigOptions {
32
32
  * 省略時は作業フォルダ(利用者の既定)。開発元の内部検証が develop/tests/output を指定するための開発用の指定であり、利用者向けの仕様書には載せない(20261012-006)。
33
33
  */
34
34
  outputDir?: string;
35
+ /**
36
+ * 実行の最後に示す、詳しい結果(HTML レポート)を開くコマンド。省略時は npx sftest report。
37
+ * 開発元の内部検証が npm run report:dev を示すための開発用の指定であり、利用者向けの仕様書には載せない(20261015-011)。
38
+ */
39
+ reportCommand?: string;
35
40
  }
36
41
  /**
37
42
  * sfTest の Playwright の設定を作る。
@@ -98,7 +98,12 @@ function sfTestConfig(options) {
98
98
  expect: { timeout: (0, settings_1.timeoutMs)('expect') },
99
99
  workers: 1,
100
100
  outputDir: (0, outputPaths_1.outputPath)('test-results'),
101
- reporter: [['html', { open: 'never', outputFolder: (0, outputPaths_1.outputPath)('playwright-report') }], ['junit', { outputFile: (0, outputPaths_1.outputPath)('results', 'junit.xml') }]],
101
+ // 実行中の経過は、ステップごとに1行ずつ表示する(support/consoleReporter.ts。20261015-011)。詳しい結果は HTML レポートで確認する。
102
+ reporter: [
103
+ [node_path_1.default.join(toolRoot, 'support', `consoleReporter${toolExt}`), { reportCommand: options.reportCommand ?? 'npx sftest report' }],
104
+ ['html', { open: 'never', outputFolder: (0, outputPaths_1.outputPath)('playwright-report') }],
105
+ ['junit', { outputFile: (0, outputPaths_1.outputPath)('results', 'junit.xml') }],
106
+ ],
102
107
  // テスト全体の前にログインしてセッションを保存し、終了後に削除する(support/globalSetup.ts)。
103
108
  globalSetup: node_path_1.default.join(toolRoot, 'support', `globalSetup${toolExt}`),
104
109
  use: {
@@ -106,6 +111,9 @@ function sfTestConfig(options) {
106
111
  storageState: (0, session_1.authFile)(), // 各シナリオは、前後処理で保存したセッションで始まる。
107
112
  locale: 'ja-JP',
108
113
  navigationTimeout: (0, settings_1.timeoutMs)('pageLoad'),
114
+ // 画面の操作(クリック・入力・画面キャプチャーなど)の制限時間。操作の対象が見つからない場合に、シナリオの制限時間まで
115
+ // 待ち続けず、どの対象が見つからないかを示して失敗にする(20261015-010)。個別に制限時間を指定した操作は、その値を使う。
116
+ actionTimeout: (0, settings_1.timeoutMs)('pageLoad'),
109
117
  trace: 'retain-on-failure',
110
118
  screenshot: 'on', // エビデンスとして、成功時もテスト終了時の画面を残す。
111
119
  customPages: options.customPages ?? {},
@@ -4,6 +4,20 @@
4
4
  * @returns 出力の基準フォルダ(support/outputPaths.ts)の .auth/connection.json。
5
5
  */
6
6
  export declare function connectionFile(): string;
7
+ /**
8
+ * Salesforce CLI(sf)のコマンドを、制限時間付きで実行し、標準出力を返す(20261015-010)。
9
+ *
10
+ * 同期実行のため、sf が応答しないとシナリオの制限時間も働かず、処理が終わらなくなる。API の呼び出しと同じ制限時間を過ぎたら、
11
+ * コマンドが起動したプロセスの木(Windows では cmd の先の sf の node も)を停止し、停止を確かめてから失敗にする(SUPERVISOR_SOURCE)。
12
+ * 0 以外の終了コードで終わった場合は、execSync と同じ形の例外(status・stdout・stderr を持つ)を投げる。
13
+ *
14
+ * @param command - 実行するコマンドライン(sf から始まる)。
15
+ * @param limitMs - 制限時間(ミリ秒)。通常は省略する(API の呼び出しと同じ)。確認用に短くできる。
16
+ * @returns コマンドの標準出力。
17
+ * @throws 制限時間を過ぎた場合(何のコマンドかを示す。停止できなかったプロセスがあれば、その PID も示す)、
18
+ * コマンドが 0 以外の終了コードで終わった場合。
19
+ */
20
+ export declare function execSf(command: string, limitMs?: number): string;
7
21
  /**
8
22
  * 対象の組織の別名(.env の SF_ORG_ALIAS)を返す。
9
23
  *
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.connectionFile = connectionFile;
4
+ exports.execSf = execSf;
4
5
  exports.orgAlias = orgAlias;
5
6
  exports.sfEnv = sfEnv;
6
7
  exports.sfJson = sfJson;
@@ -25,7 +26,7 @@ exports.frontDoorUrl = frontDoorUrl;
25
26
  * アクセストークンとログイン用 URL は認証情報のため、ログやエラーのメッセージに出さない。
26
27
  *
27
28
  * Windows では sf の実体が sf.cmd であり、Node.js は .cmd を shell なしで起動できないため、
28
- * コマンドラインの文字列を shell(execSync)で実行する。引数に含める値は、呼び出し元で用途に応じて検証・エスケープする。
29
+ * コマンドラインの文字列を shell で実行する(execSf。制限時間を過ぎたら、起動したプロセスの木ごと止める)。引数に含める値は、呼び出し元で用途に応じて検証・エスケープする。
29
30
  * sf で SOQL を実行する場合、SOQL はシナリオの値を含むため、コマンドラインではなく一時ファイルで渡す。
30
31
  *
31
32
  * @author Fluxengine.co.jp
@@ -55,6 +56,89 @@ function connectionFile() {
55
56
  const CONNECTION_ID_ENV = 'SFTEST_CONNECTION_ID';
56
57
  /** 1回の API の呼び出しの制限時間(ミリ秒)。内部の調整用であり、設定では変えられない。 */
57
58
  const HTTP_TIMEOUT_MS = 120_000;
59
+ /** 見張り役が、制限時間を過ぎてコマンドを止めたことを示す終了コード。 */
60
+ const SUPERVISOR_TIMEOUT_EXIT = 124;
61
+ /**
62
+ * コマンドを起動して見張る node のスクリプト(execSf が同期で実行する。20261015-010)。
63
+ *
64
+ * 引数はコマンドラインと制限時間(ミリ秒)。コマンドの標準出力・標準エラーを、終了後にそのまま書き出し、コマンドの終了コードで終わる。
65
+ * 制限時間を過ぎたら、コマンドが起動したプロセスの木(cmd → sf の node → その子など)を記録してから、木ごと停止し、すべての停止を
66
+ * 確かめてから、終了コード 124 で終わる。停止できなかったプロセスがあれば、標準エラーの最後の行に PID を JSON で書く。
67
+ * Windows では taskkill /T(木ごとの停止)を使い、木の記録には PowerShell の Win32_Process を使う。それ以外では、
68
+ * コマンドを新しいプロセスグループで起動し、グループごと停止する。ほかのプロセスは停止しない。
69
+ */
70
+ const SUPERVISOR_SOURCE = `
71
+ const { spawn, spawnSync } = require('node:child_process');
72
+ const [command, limitText] = process.argv.slice(1);
73
+ const win = process.platform === 'win32';
74
+ const child = spawn(command, { shell: true, detached: !win, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
75
+ const out = [], err = [];
76
+ child.stdout.on('data', (d) => out.push(d));
77
+ child.stderr.on('data', (d) => err.push(d));
78
+ let timedOut = false;
79
+ const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
80
+ const descendants = (root) => {
81
+ const r = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
82
+ 'Get-CimInstance Win32_Process | ForEach-Object { [string]$_.ProcessId + \\' \\' + [string]$_.ParentProcessId }'], { encoding: 'utf8', windowsHide: true, timeout: 20000 });
83
+ const parents = new Map();
84
+ for (const line of String(r.stdout || '').split(/\\r?\\n/)) { const [p, pp] = line.trim().split(' ').map(Number); if (p) parents.set(p, pp); }
85
+ const found = [root];
86
+ for (let added = true; added;) { added = false; for (const [p, pp] of parents) if (found.includes(pp) && !found.includes(p)) { found.push(p); added = true; } }
87
+ return found;
88
+ };
89
+ const timer = setTimeout(async () => {
90
+ timedOut = true;
91
+ let tree = [child.pid];
92
+ if (win) { tree = descendants(child.pid); spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' }); for (const pid of tree) { try { process.kill(pid, 'SIGKILL'); } catch {} } }
93
+ else { try { process.kill(-child.pid, 'SIGKILL'); } catch {} }
94
+ const until = Date.now() + 10000;
95
+ while (Date.now() < until && (win ? tree.some(alive) : alive(child.pid))) await new Promise((r) => setTimeout(r, 100));
96
+ const left = win ? tree.filter(alive) : (alive(child.pid) ? [child.pid] : []);
97
+ process.stderr.write(Buffer.concat(err));
98
+ process.stderr.write('\\nSFTEST_SUPERVISOR_TIMEOUT ' + JSON.stringify({ left }) + '\\n');
99
+ process.exit(${SUPERVISOR_TIMEOUT_EXIT});
100
+ }, Number(limitText));
101
+ child.on('close', (code) => {
102
+ if (timedOut) return;
103
+ clearTimeout(timer);
104
+ process.stdout.write(Buffer.concat(out), () => { process.stderr.write(Buffer.concat(err)); process.exitCode = code ?? 1; });
105
+ });
106
+ child.on('error', (e) => { if (!timedOut) { clearTimeout(timer); process.stderr.write(String(e.message)); process.exitCode = 1; } });
107
+ `;
108
+ /**
109
+ * Salesforce CLI(sf)のコマンドを、制限時間付きで実行し、標準出力を返す(20261015-010)。
110
+ *
111
+ * 同期実行のため、sf が応答しないとシナリオの制限時間も働かず、処理が終わらなくなる。API の呼び出しと同じ制限時間を過ぎたら、
112
+ * コマンドが起動したプロセスの木(Windows では cmd の先の sf の node も)を停止し、停止を確かめてから失敗にする(SUPERVISOR_SOURCE)。
113
+ * 0 以外の終了コードで終わった場合は、execSync と同じ形の例外(status・stdout・stderr を持つ)を投げる。
114
+ *
115
+ * @param command - 実行するコマンドライン(sf から始まる)。
116
+ * @param limitMs - 制限時間(ミリ秒)。通常は省略する(API の呼び出しと同じ)。確認用に短くできる。
117
+ * @returns コマンドの標準出力。
118
+ * @throws 制限時間を過ぎた場合(何のコマンドかを示す。停止できなかったプロセスがあれば、その PID も示す)、
119
+ * コマンドが 0 以外の終了コードで終わった場合。
120
+ */
121
+ function execSf(command, limitMs = HTTP_TIMEOUT_MS) {
122
+ const result = (0, node_child_process_1.spawnSync)(process.execPath, ['-e', SUPERVISOR_SOURCE, command, String(limitMs)], {
123
+ encoding: 'utf-8', env: sfEnv(), maxBuffer: 64 * 1024 * 1024, windowsHide: true,
124
+ timeout: limitMs + 60_000, // 見張り役そのものの上限(木の記録・停止・停止の確認の時間を含める)。通常は届かない。
125
+ });
126
+ const name = `Salesforce CLI(sf ${subcommandOf(command.replace(/^sf /, ''))})`;
127
+ const marker = /SFTEST_SUPERVISOR_TIMEOUT (\{.*\})\s*$/.exec(result.stderr ?? '');
128
+ if (result.status === SUPERVISOR_TIMEOUT_EXIT && marker) {
129
+ const left = JSON.parse(marker[1]).left ?? [];
130
+ throw new Error(`${name}が制限時間(${limitMs / 1000} 秒)内に終わらなかったため、止めました${left.length ? `(停止を確認できなかったプロセス: PID ${left.join(', ')})` : ''}`);
131
+ }
132
+ if (result.error)
133
+ throw new Error(`${name}を実行できませんでした: ${result.error.message}`);
134
+ if (result.status !== 0) {
135
+ const error = Object.assign(new Error(`Command failed: ${name}(終了コード ${result.status})\n${(result.stderr ?? '').slice(0, 2000)}`), {
136
+ status: result.status, stdout: result.stdout, stderr: result.stderr,
137
+ });
138
+ throw error;
139
+ }
140
+ return result.stdout;
141
+ }
58
142
  /** このプロセスで使う接続情報(初回の取得までは undefined)。 */
59
143
  let connection;
60
144
  /** 直接の通信ができず、sf による呼び出しに切り替えたかどうか。 */
@@ -119,7 +203,7 @@ function sfEnv() {
119
203
  * @throws コマンドが 0 以外の終了コードで終わった場合、または出力を JSON として読めない場合。
120
204
  */
121
205
  function sfJson(args) {
122
- const out = (0, startupTiming_1.timeStartup)(`Salesforce CLI の呼び出し(sf ${subcommandOf(args)})`, () => (0, node_child_process_1.execSync)(`sf ${args} --target-org ${orgAlias()} --json`, { encoding: 'utf-8', env: sfEnv(), maxBuffer: 64 * 1024 * 1024 }));
206
+ const out = (0, startupTiming_1.timeStartup)(`Salesforce CLI の呼び出し(sf ${subcommandOf(args)})`, () => execSf(`sf ${args} --target-org ${orgAlias()} --json`));
123
207
  // 前後に余計な出力(更新通知など)が混ざっても JSON 部分だけを取り出す。
124
208
  const json = out.slice(out.indexOf('{'), out.lastIndexOf('}') + 1);
125
209
  return JSON.parse(json).result;
@@ -362,7 +446,7 @@ function sfRest(path) {
362
446
  if (result !== undefined)
363
447
  return result;
364
448
  // オブジェクト一覧などは出力が大きいため、既定(1MB)より大きいバッファを使う。
365
- const out = (0, node_child_process_1.execSync)(`sf api request rest "${path}" --target-org ${orgAlias()}`, { encoding: 'utf-8', env: sfEnv(), maxBuffer: 64 * 1024 * 1024 });
449
+ const out = execSf(`sf api request rest "${path}" --target-org ${orgAlias()}`);
366
450
  const start = Math.min(...['{', '['].map((c) => out.indexOf(c)).filter((i) => i >= 0));
367
451
  return JSON.parse(out.slice(start));
368
452
  }