@capagents/forgeqe 3.0.3 → 3.0.4
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.
- package/HOW_TO_USE.md +190 -189
- package/README.md +12 -12
- package/THIRD_PARTY_NOTICES.md +2 -2
- package/dist/docs-site/architecture-map/index.html +6 -6
- package/dist/docs-site/docs/architecture/index.html +31 -31
- package/dist/docs-site/docs/containers/index.html +9 -10
- package/dist/docs-site/docs/custom-agents-first-run/index.html +5 -5
- package/dist/docs-site/docs/desktop/index.html +8 -10
- package/dist/docs-site/docs/feature-test-prompts/index.html +4 -4
- package/dist/docs-site/docs/graphify/index.html +1 -1
- package/dist/docs-site/docs/index.html +214 -165
- package/dist/docs-site/docs/mobile/index.html +6 -6
- package/dist/docs-site/docs/model-routing/index.html +58 -10
- package/dist/docs-site/docs/product-graph/index.html +3 -3
- package/dist/docs-site/docs/product-views/index.html +1 -1
- package/dist/docs-site/docs/search.js +1 -1
- package/dist/docs-site/docs/web-app/index.html +6 -6
- package/dist/forgeqe.js +1851 -1820
- package/dist/template.html +69 -69
- package/dist/web/assets/Agent-CKlqZ4Eq.js +8 -0
- package/dist/web/assets/ApiTests-MARHrxdT.js +10 -0
- package/dist/web/assets/Browse-B2QYflth.js +2 -0
- package/dist/web/assets/Chat-DRkmiF4r.js +5 -0
- package/dist/web/assets/{CommandPalette-CAAPFMZn.js → CommandPalette-DMpA8mBk.js} +1 -1
- package/dist/web/assets/{Compare-DZfbMjDK.js → Compare-DD1mmRB4.js} +1 -1
- package/dist/web/assets/Cost-B6BCZIxQ.js +1 -0
- package/dist/web/assets/Data-CpKR98gM.js +6 -0
- package/dist/web/assets/{Desktop-sXYXYwRy.js → Desktop-xUqFsJPz.js} +1 -1
- package/dist/web/assets/{DesktopReview-Bz6bfPkM.js → DesktopReview-CnLC9yMR.js} +1 -1
- package/dist/web/assets/{Evidence-CijYL67k.js → Evidence-CWcZvoOu.js} +1 -1
- package/dist/web/assets/{Explore-DZ5PoVZp.js → Explore-DuDQqmEn.js} +2 -2
- package/dist/web/assets/{Features-BvZfZIb7.js → Features-BJTX7utr.js} +1 -1
- package/dist/web/assets/{Flags-B_-HOAeZ.js → Flags-BeG_gA9O.js} +2 -2
- package/dist/web/assets/{Flaky-CWyV0rE3.js → Flaky-DulQuBGi.js} +1 -1
- package/dist/web/assets/Impact-BvGp2rYG.js +3 -0
- package/dist/web/assets/Jobs-BXqBtH8C.js +5 -0
- package/dist/web/assets/KindPage-BGEobnS3.js +6 -0
- package/dist/web/assets/Migration-D1JVUQM0.js +2 -0
- package/dist/web/assets/{Product-BeHmrA7Z.js → Product-Y1dUpFfW.js} +2 -2
- package/dist/web/assets/{Production-Dakb3WS-.js → Production-DY9Gddm8.js} +1 -1
- package/dist/web/assets/{Quality-CcrANX20.js → Quality-B7M1Zna2.js} +1 -1
- package/dist/web/assets/{Readiness-DvYQ17Oh.js → Readiness-BtQ8RbJh.js} +1 -1
- package/dist/web/assets/Record-W7ojjKNu.js +2 -0
- package/dist/web/assets/Regression-eV2N8m2P.js +5 -0
- package/dist/web/assets/{RelationGraph-evMcSFoO.js → RelationGraph-C7K_BfEF.js} +1 -1
- package/dist/web/assets/{Reports--eyV0Gfp.js → Reports-D4v66mJR.js} +2 -2
- package/dist/web/assets/Response-B_2R4FjH.js +4 -0
- package/dist/web/assets/{RunDiff-DwEopDsx.js → RunDiff-Br5uN0Gu.js} +1 -1
- package/dist/web/assets/Runs-DvjM0xfG.js +2 -0
- package/dist/web/assets/{Steps-DxPqrmZK.js → Steps-DULf0k5w.js} +1 -1
- package/dist/web/assets/{TestCases-93xQKkMT.js → TestCases-Dc6bjNO5.js} +1 -1
- package/dist/web/assets/TestData-DWPcmhz4.js +2 -0
- package/dist/web/assets/{TestDebt-CE62ftuJ.js → TestDebt-BpYav19x.js} +1 -1
- package/dist/web/assets/Tosca-Bw-j_W-Q.js +3 -0
- package/dist/web/assets/{WhatsNew-lX-LhWKt.js → WhatsNew-CRaJjaut.js} +1 -1
- package/dist/web/assets/agentLink-Dxy-IYQv.js +1 -0
- package/dist/web/assets/{dataParts-LCnV1x8c.js → dataParts-Bwh_DOs0.js} +1 -1
- package/dist/web/assets/{families-DLmHA4rL.js → families-C47Nrp6j.js} +1 -1
- package/dist/web/assets/filters-Ca7by1u0.js +1 -0
- package/dist/web/assets/{fold-pif2b5qg.js → fold-Bd5-4sjR.js} +1 -1
- package/dist/web/assets/frame-BliO67Wd.js +18 -0
- package/dist/web/assets/index-B1U2Jkz_.js +67 -0
- package/dist/web/assets/index-Ce2EYROA.css +2 -0
- package/dist/web/assets/{logos-gqcS1A90.js → logos-CgYEz85j.js} +1 -1
- package/dist/web/assets/{markdown-BcuknPlh.js → markdown-DSp3tP8i.js} +5 -5
- package/dist/web/assets/{paletteCommands-qeRU49pp.js → paletteCommands-CGFwmBxN.js} +1 -1
- package/dist/web/assets/{parts-C7nGHnut.js → parts-DlmbVDzO.js} +1 -1
- package/dist/web/assets/{productParts-3lWHIbdH.js → productParts-CL2tDIGF.js} +1 -1
- package/dist/web/assets/{qualityParts-B-TQusS6.js → qualityParts-Bs34Dzva.js} +1 -1
- package/dist/web/assets/recordTest-DHsT3pOe.js +1 -0
- package/dist/web/assets/{rows-vVKLONno.js → rows-Baid_ASt.js} +1 -1
- package/dist/web/assets/{segmented-Bi4QAoQY.js → segmented-D0PvwMW_.js} +1 -1
- package/dist/web/assets/{usePageChat-De5Fn1X3.js → usePageChat-lmgkgnb4.js} +1 -1
- package/dist/web/index.html +5 -5
- package/docs/ARCHITECTURE.md +30 -30
- package/docs/BUSINESS_ASSURANCE.md +7 -7
- package/docs/CONTAINERS.md +8 -10
- package/docs/CUSTOM_AGENTS_FIRST_RUN.md +4 -4
- package/docs/DESKTOP.md +8 -10
- package/docs/GRAPHIFY.md +1 -1
- package/docs/MOBILE.md +6 -6
- package/docs/MODEL_ROUTING.md +57 -9
- package/docs/PRODUCT_KNOWLEDGE.md +3 -3
- package/docs/PRODUCT_VIEWS.md +1 -1
- package/docs/WEB_APP.md +6 -6
- package/docs/demo-qi-commerce.md +30 -30
- package/docs/feature-test-prompts.md +3 -3
- package/docs/prompts/graphify-evidence.md +3 -3
- package/docs/security-data-flow.html +23 -23
- package/docs/user-guide.html +214 -165
- package/docs/walkthrough/hotfix-narration.md +19 -19
- package/docs/walkthrough/index.html +26 -26
- package/env.example.yaml +1 -1
- package/evals/evidence/records/forgeqe-test-writing/source.jsonl +1 -1
- package/forgeqe-architecture.html +48 -48
- package/forgeqe.example.yaml +16 -10
- package/package.json +1 -1
- package/prompts/README.md +7 -7
- package/prompts/agent-builder.md +1 -1
- package/prompts/api-tests.md +1 -1
- package/prompts/brain.md +8 -5
- package/prompts/business-interview.md +3 -3
- package/prompts/business-persona.md +3 -3
- package/prompts/business-strategist.md +1 -1
- package/prompts/db-agent.md +3 -3
- package/prompts/doc-reader.md +2 -2
- package/prompts/heal.md +1 -1
- package/prompts/knowledge-agent.md +3 -3
- package/prompts/model-profile.md +1 -1
- package/prompts/page-differs.md +1 -1
- package/prompts/persona-own.md +3 -3
- package/prompts/talk.md +3 -2
- package/prompts/test-agent.md +2 -2
- package/prompts/test-plan.md +2 -2
- package/prompts/tosca-assistant.md +1 -1
- package/py/forgeqe_engine/copilot_gateway.py +1 -1
- package/py/forgeqe_engine/memory.py +48 -2
- package/py/forgeqe_engine/recordsession.py +31 -1
- package/py/forgeqe_engine/video.py +104 -12
- package/py/forgeqe_engine/webrecord_page.py +88 -7
- package/py/forgeqe_tosca/__init__.py +2 -2
- package/py/forgeqe_tosca/render.py +1 -1
- package/py/forgeqe_tosca/tsu.py +2 -2
- package/skills/playwright-automation/SKILL.md +102 -0
- package/skills/playwright-automation/references/dotnet.md +90 -0
- package/skills/playwright-automation/references/java.md +41 -0
- package/skills/playwright-automation/references/python.md +42 -0
- package/skills/playwright-automation/references/typescript.md +54 -0
- package/skills/test-data/SKILL.md +1 -1
- package/skills/writing-skills/SKILL.md +2 -2
- package/dist/web/assets/Agent-Bha4Lr91.js +0 -8
- package/dist/web/assets/ApiTests-xhnOnRi9.js +0 -10
- package/dist/web/assets/Browse-DPfzCrMZ.js +0 -2
- package/dist/web/assets/Chat-DuLj5IPw.js +0 -5
- package/dist/web/assets/Cost-PNcsRgPW.js +0 -1
- package/dist/web/assets/Data-DaKzcO_S.js +0 -6
- package/dist/web/assets/Impact-BqHiKxoG.js +0 -3
- package/dist/web/assets/Jobs-DUfRHoko.js +0 -5
- package/dist/web/assets/KindPage-Dj3vryGF.js +0 -6
- package/dist/web/assets/Migration-CP3o4tLy.js +0 -2
- package/dist/web/assets/Record-V7x9VxRQ.js +0 -2
- package/dist/web/assets/Regression-DgXh0V-X.js +0 -5
- package/dist/web/assets/Response-B1S-n787.js +0 -4
- package/dist/web/assets/Runs-B6bSGdrI.js +0 -2
- package/dist/web/assets/TestData-BiW5r9gA.js +0 -2
- package/dist/web/assets/Tosca-CrvuVNqG.js +0 -3
- package/dist/web/assets/agentLink-ZQZx1pK-.js +0 -1
- package/dist/web/assets/filters-CorGh2vA.js +0 -1
- package/dist/web/assets/frame-BgpCUEoM.js +0 -18
- package/dist/web/assets/index-0YhzcgZJ.css +0 -2
- package/dist/web/assets/index-CEVZ8F8_.js +0 -67
- package/dist/web/assets/recordTest-BmD8jtw0.js +0 -1
- package/skills/dotnet-nunit-playwright/SKILL.md +0 -36
- package/skills/playwright-typescript/SKILL.md +0 -36
|
@@ -6,7 +6,10 @@ and a desktop run (the screen).
|
|
|
6
6
|
Every video is ``video.mp4`` (H.264), made by the ffmpeg that the pinned ``imageio-ffmpeg`` package ships inside
|
|
7
7
|
itself: found in the package's own ``binaries`` folder, never on PATH and never through ``IMAGEIO_FFMPEG_EXE``, started
|
|
8
8
|
with an argument list and system settings only. Frames reach it on stdin as raw RGB pixels of a fixed size, so nothing
|
|
9
|
-
a page or an app shows ever reaches its command line. A video
|
|
9
|
+
a page or an app shows ever reaches its command line. A replay's video can carry a narration track
|
|
10
|
+
(``browser.narrate_video``): one WAV that ForgeQE made itself (src/voice/narration.ts lays the spoken lines into it),
|
|
11
|
+
given to ffmpeg as a second input by its path only -- never a clip of its own, never a filter graph built from a
|
|
12
|
+
page's words. A video runs in real time at ``FPS`` frames a second (the
|
|
10
13
|
latest picture is repeated while nothing changes), stops growing after ``MAX_SECONDS``, and a video that could not be
|
|
11
14
|
finished is removed rather than kept half written.
|
|
12
15
|
"""
|
|
@@ -20,6 +23,7 @@ import subprocess
|
|
|
20
23
|
import sys
|
|
21
24
|
import threading
|
|
22
25
|
import time
|
|
26
|
+
import wave
|
|
23
27
|
from pathlib import Path
|
|
24
28
|
from typing import Any, Callable, Dict, List, Optional, Tuple
|
|
25
29
|
|
|
@@ -67,14 +71,43 @@ def fit_size(width: int, height: int, max_width: int = MAX_WIDTH, max_height: in
|
|
|
67
71
|
return _even(round(width * scale)), _even(round(height * scale))
|
|
68
72
|
|
|
69
73
|
|
|
70
|
-
def ffmpeg_args(exe: str, size: Tuple[int, int], fps: int, out: Path) -> List[str]:
|
|
74
|
+
def ffmpeg_args(exe: str, size: Tuple[int, int], fps: int, out: Path, audio: Optional[Path] = None) -> List[str]:
|
|
75
|
+
"""ffmpeg's arguments: pictures on stdin, and with ``audio`` that one WAV as a second input, by its path alone."""
|
|
71
76
|
w, h = size
|
|
72
|
-
|
|
77
|
+
args = [
|
|
73
78
|
exe, "-hide_banner", "-loglevel", "error", "-y",
|
|
74
79
|
"-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{w}x{h}", "-r", str(fps), "-i", "-",
|
|
75
|
-
"-an", "-c:v", "libx264", "-preset", "veryfast", "-crf", "28", "-pix_fmt", "yuv420p", "-movflags", "+faststart",
|
|
76
|
-
str(out),
|
|
77
80
|
]
|
|
81
|
+
if audio is not None:
|
|
82
|
+
# One more input, and only a WAV ForgeQE wrote: the video still ends when its pictures do (-shortest).
|
|
83
|
+
args += ["-f", "wav", "-i", str(audio), "-c:a", "aac", "-b:a", "96k", "-shortest"]
|
|
84
|
+
else:
|
|
85
|
+
args += ["-an"]
|
|
86
|
+
args += ["-c:v", "libx264", "-preset", "veryfast", "-crf", "28", "-pix_fmt", "yuv420p", "-movflags", "+faststart", str(out)]
|
|
87
|
+
return args
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def wav_ms(file: Path) -> int:
|
|
91
|
+
"""How long a WAV ForgeQE wrote lasts, in milliseconds, from its own header; 0 when it cannot be read."""
|
|
92
|
+
try:
|
|
93
|
+
with wave.open(str(file), "rb") as w:
|
|
94
|
+
rate = w.getframerate()
|
|
95
|
+
return int(w.getnframes() * 1000 / rate) if rate else 0
|
|
96
|
+
except (OSError, wave.Error, EOFError):
|
|
97
|
+
return 0
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def narration_file(raw: Any) -> Optional[Path]:
|
|
101
|
+
"""The narration track to lay under the video: a regular ``.wav`` file that is really there, else None."""
|
|
102
|
+
if not raw:
|
|
103
|
+
return None
|
|
104
|
+
try:
|
|
105
|
+
p = Path(str(raw))
|
|
106
|
+
if p.suffix.lower() != ".wav" or p.is_symlink() or not p.is_file() or not p.stat().st_size:
|
|
107
|
+
return None
|
|
108
|
+
return p
|
|
109
|
+
except OSError:
|
|
110
|
+
return None
|
|
78
111
|
|
|
79
112
|
|
|
80
113
|
def _child_env() -> Dict[str, str]:
|
|
@@ -166,6 +199,13 @@ class FrameVideo:
|
|
|
166
199
|
self._latest = data
|
|
167
200
|
self._fresh = True
|
|
168
201
|
|
|
202
|
+
def where_ms(self) -> int:
|
|
203
|
+
"""
|
|
204
|
+
Where the video is now, in milliseconds: the frames written at ``fps``, so the time held is not counted (it is
|
|
205
|
+
not in the video either). This is what times a step for the narration (browser.narrate_video).
|
|
206
|
+
"""
|
|
207
|
+
return int(self.written * 1000 / self.fps)
|
|
208
|
+
|
|
169
209
|
def hold(self, held: bool) -> None:
|
|
170
210
|
with self._lock:
|
|
171
211
|
if held == self._held:
|
|
@@ -284,10 +324,45 @@ def frames_in(folder: Path) -> List[Tuple[int, Path]]:
|
|
|
284
324
|
return out[:MAX_FRAMES]
|
|
285
325
|
|
|
286
326
|
|
|
287
|
-
def
|
|
327
|
+
def add_narration(video: Any, track: Any, out: Path, *, exe: Optional[str] = None) -> Tuple[Optional[Path], str]:
|
|
328
|
+
"""
|
|
329
|
+
A video already made (a recording's own, written as it happened) with the narration laid under it: its pictures are
|
|
330
|
+
copied, not made again, and ffmpeg is given the two files ForgeQE wrote, by their paths alone.
|
|
331
|
+
"""
|
|
332
|
+
src = Path(str(video))
|
|
333
|
+
if src.suffix.lower() != ".mp4" or src.is_symlink() or not src.is_file() or not src.stat().st_size:
|
|
334
|
+
return None, "there is no video to narrate"
|
|
335
|
+
laid = narration_file(track)
|
|
336
|
+
if laid is None:
|
|
337
|
+
return None, "there is no narration to lay under it"
|
|
338
|
+
exe = exe or ffmpeg_exe()
|
|
339
|
+
if not exe:
|
|
340
|
+
return None, "the engine's video packages are missing (run forgeqe setup)"
|
|
341
|
+
out = Path(out)
|
|
342
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
343
|
+
args = [
|
|
344
|
+
exe, "-hide_banner", "-loglevel", "error", "-y",
|
|
345
|
+
"-i", str(src), "-f", "wav", "-i", str(laid),
|
|
346
|
+
"-map", "0:v:0", "-map", "1:a:0", "-c:v", "copy", "-c:a", "aac", "-b:a", "96k", "-shortest",
|
|
347
|
+
str(out),
|
|
348
|
+
]
|
|
349
|
+
try:
|
|
350
|
+
proc = subprocess.run(args, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=_child_env(), shell=False, timeout=FINISH_SECONDS)
|
|
351
|
+
except (OSError, subprocess.TimeoutExpired) as ex:
|
|
352
|
+
return None, f"ffmpeg did not finish ({ex.__class__.__name__})"
|
|
353
|
+
if proc.returncode != 0 or not out.is_file() or not out.stat().st_size:
|
|
354
|
+
try:
|
|
355
|
+
out.unlink()
|
|
356
|
+
except OSError:
|
|
357
|
+
pass
|
|
358
|
+
return None, f"ffmpeg ended with {proc.returncode}"
|
|
359
|
+
return out, ""
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def encode_frames(folder: Path, out: Path, *, fps: int = FPS, max_seconds: float = MAX_SECONDS, exe: Optional[str] = None, audio: Any = None) -> Tuple[Optional[Path], str]:
|
|
288
363
|
"""
|
|
289
364
|
A video of frames kept with their times (a replay's): each moment shows the latest frame taken by then. (path, "")
|
|
290
|
-
or (None, why not).
|
|
365
|
+
or (None, why not). ``audio``: a WAV ForgeQE made (the narration), laid under it when it is really a .wav file.
|
|
291
366
|
"""
|
|
292
367
|
frames = frames_in(folder)
|
|
293
368
|
if not frames:
|
|
@@ -299,14 +374,18 @@ def encode_frames(folder: Path, out: Path, *, fps: int = FPS, max_seconds: float
|
|
|
299
374
|
if first is None:
|
|
300
375
|
return None, "the first frame is not a picture"
|
|
301
376
|
size = fit_size(first.width, first.height)
|
|
377
|
+
track = narration_file(audio)
|
|
302
378
|
out = Path(out)
|
|
303
379
|
out.parent.mkdir(parents=True, exist_ok=True)
|
|
304
380
|
try:
|
|
305
|
-
proc = subprocess.Popen(ffmpeg_args(exe, size, fps, out), stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=_child_env(), shell=False)
|
|
381
|
+
proc = subprocess.Popen(ffmpeg_args(exe, size, fps, out, track), stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=_child_env(), shell=False)
|
|
306
382
|
except OSError as ex:
|
|
307
383
|
return None, f"ffmpeg did not start ({ex.__class__.__name__})"
|
|
308
384
|
start = frames[0][0]
|
|
309
385
|
end = min(frames[-1][0] - start, int(max_seconds * 1000))
|
|
386
|
+
# With a narration, the video lasts as long as it does: the last frame is held, so its closing line is never cut.
|
|
387
|
+
if track is not None:
|
|
388
|
+
end = min(max(end, wav_ms(track)), int(max_seconds * 1000))
|
|
310
389
|
count = end * fps // 1000 + 1
|
|
311
390
|
i, pixels, ok = 0, _letterbox(first, size), True
|
|
312
391
|
assert proc.stdin is not None
|
|
@@ -405,11 +484,24 @@ class ScreenVideo:
|
|
|
405
484
|
|
|
406
485
|
|
|
407
486
|
def main(args: List[str], out: Any) -> int:
|
|
408
|
-
"""
|
|
409
|
-
|
|
410
|
-
|
|
487
|
+
"""
|
|
488
|
+
``python -m forgeqe_engine video <frames folder> <file.mp4> [narration.wav]``: a replay's frames as a video
|
|
489
|
+
(src/code/replay.ts), with the narration track under it when one is given (src/voice/narration.ts).
|
|
490
|
+
``video narrate <made.mp4> <narration.wav> <out.mp4>``: a recording's own video, written as it happened, with that
|
|
491
|
+
track laid under it afterwards (its pictures copied, not made again).
|
|
492
|
+
"""
|
|
493
|
+
if args and args[0] == "narrate":
|
|
494
|
+
if len(args) != 4 or not args[1].endswith(".mp4") or not args[2].endswith(".wav") or not args[3].endswith(".mp4"):
|
|
495
|
+
result: Dict[str, Any] = {"success": False, "error": "usage: video narrate <made.mp4> <narration.wav> <out.mp4>"}
|
|
496
|
+
else:
|
|
497
|
+
path, why = add_narration(args[1], args[2], Path(args[3]))
|
|
498
|
+
result = {"success": True, "video": str(path)} if path else {"success": False, "error": why}
|
|
499
|
+
out.write(json.dumps({"type": "done", "result": result}) + "\n")
|
|
500
|
+
return 0 if result["success"] else 1
|
|
501
|
+
if len(args) not in (2, 3) or not args[1].endswith(".mp4") or (len(args) == 3 and not args[2].endswith(".wav")):
|
|
502
|
+
result = {"success": False, "error": "usage: video <frames folder> <file.mp4> [narration.wav]"}
|
|
411
503
|
else:
|
|
412
|
-
path, why = encode_frames(Path(args[0]), Path(args[1]))
|
|
504
|
+
path, why = encode_frames(Path(args[0]), Path(args[1]), audio=args[2] if len(args) == 3 else None)
|
|
413
505
|
result = {"success": True, "video": str(path)} if path else {"success": False, "error": why}
|
|
414
506
|
out.write(json.dumps({"type": "done", "result": result}) + "\n")
|
|
415
507
|
return 0 if result["success"] else 1
|
|
@@ -14,7 +14,7 @@ from __future__ import annotations
|
|
|
14
14
|
import json
|
|
15
15
|
from typing import Any, Dict, Optional
|
|
16
16
|
|
|
17
|
-
from .memory import STATE_CLASS
|
|
17
|
+
from .memory import SHAKY_TEXT, STATE_CLASS, TEXT_GEN
|
|
18
18
|
|
|
19
19
|
# The leader key, then one letter: what each letter does, as the key bar and the panel's hint show it.
|
|
20
20
|
COMMAND_KEYS = (
|
|
@@ -147,13 +147,62 @@ RECORDER_JS = r"""(() => {
|
|
|
147
147
|
// No XPath for an element inside a shadow root: an XPath cannot reach into one, so it would find nothing on replay.
|
|
148
148
|
const xpath = (e) => inShadow(e) ? '' : xpathOf(e);
|
|
149
149
|
const xpathOf = (e) => { const parts = []; for (; e && e.nodeType === 1; e = e.parentElement) { let i = 1; for (let s = e.previousElementSibling; s; s = s.previousElementSibling) if (s.tagName === e.tagName) i++; parts.unshift(e.tagName.toLowerCase() + '[' + i + ']'); } return parts.join('/'); };
|
|
150
|
+
// ---- a relative XPath: anchored on what the page says, never on where the element sits ------------------------
|
|
151
|
+
// An absolute path (/html[1]/body[1]/div[1]/…) breaks when anything above the element moves. These are built from
|
|
152
|
+
// the element's own identifying attribute or its text, and where that is not unique, from a text that identifies an
|
|
153
|
+
// ancestor, so the path survives a re-ordered page. Page text goes in as an XPath string literal only (xpLit), so a
|
|
154
|
+
// quote in it can never end the literal and add a step of its own.
|
|
155
|
+
const XP_TEXT_MAX = 60;
|
|
156
|
+
// A framework's own attribute value (ember1423, :r3:, a hash): it changes on the next load, so it is never put in
|
|
157
|
+
// a path. A long run of digits counts here, where an attribute is concerned.
|
|
158
|
+
const XP_GEN = /\d{4,}|^(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{8,}$|:[rR][0-9a-zA-Z]*:|^(?:ember|mui-|react-select-|headlessui-|radix-|yui_|j_id|__)/i;
|
|
159
|
+
// Text the page shows is judged more narrowly (memory.py TEXT_GEN): an order or invoice number ("INV-1042") is the
|
|
160
|
+
// steadiest anchor a row has, so digits alone never rule a text out. Only an opaque token does.
|
|
161
|
+
const XP_GEN_TEXT = new RegExp(CFG.textGen, 'i');
|
|
162
|
+
const XP_ATTRS = ['data-testid', 'data-test-id', 'data-test', 'data-qa', 'data-cy', 'id', 'name', 'aria-label', 'placeholder', 'title', 'alt'];
|
|
163
|
+
const xpLit = (s) => s.indexOf("'") < 0 ? "'" + s + "'" : s.indexOf('"') < 0 ? '"' + s + '"'
|
|
164
|
+
: 'concat(' + s.split("'").map((p) => "'" + p + "'").join(', "\'", ') + ')';
|
|
165
|
+
const xpCount = (xp) => { try { return document.evaluate('count(' + xp + ')', document, null, XPathResult.NUMBER_TYPE, null).numberValue; } catch (err) { return -1; } };
|
|
166
|
+
// What identifies the element itself: a stable attribute, else its own text.
|
|
167
|
+
const xpOwn = (f) => {
|
|
168
|
+
for (const k of XP_ATTRS) { const v = f.attributes[k]; if (v && v.length <= 120 && !XP_GEN.test(v)) return '[@' + k + '=' + xpLit(v) + ']'; }
|
|
169
|
+
const t = norm(f.text || f.name);
|
|
170
|
+
return t && t.length <= XP_TEXT_MAX && !XP_GEN_TEXT.test(t) ? '[normalize-space()=' + xpLit(t) + ']' : '';
|
|
171
|
+
};
|
|
172
|
+
const relXpath = (e, f) => {
|
|
173
|
+
// An XPath cannot reach into a shadow root, so there is nothing to build (xpathOf does the same).
|
|
174
|
+
if (inShadow(e)) return '';
|
|
175
|
+
const own = xpOwn(f);
|
|
176
|
+
const self = '//' + f.tag + own;
|
|
177
|
+
// Its own attribute or text is enough, where that finds only it. With neither, only the anchored form below can
|
|
178
|
+
// tell it from the other elements of its tag, so a bare "//input" is never the answer.
|
|
179
|
+
if (own && xpCount(self) === 1) return self;
|
|
180
|
+
// Not unique on its own: the item that holds it (a card, a row), reached from a text only that item has. The
|
|
181
|
+
// ancestor axis takes the nearest one, so a wrapper that holds every card does not match as well.
|
|
182
|
+
const mine = norm(f.text || f.name);
|
|
183
|
+
const tail = '//' + f.tag + own;
|
|
184
|
+
for (let box = up(e), i = 0; box && i < 6 && box !== document.body && box !== document.documentElement; box = up(box), i++) {
|
|
185
|
+
if (box.nodeType !== 1 || inShadow(box)) continue;
|
|
186
|
+
const btag = box.tagName.toLowerCase();
|
|
187
|
+
for (const t of anchorTexts(box, mine, [box], e)) {
|
|
188
|
+
if (!t || t.length > XP_TEXT_MAX || XP_GEN_TEXT.test(t)) continue;
|
|
189
|
+
const xp = '//*[normalize-space()=' + xpLit(t) + ']/ancestor::' + btag + '[1]' + tail;
|
|
190
|
+
if (xpCount(xp) === 1) return xp;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return '';
|
|
194
|
+
};
|
|
195
|
+
|
|
150
196
|
const facts = (e) => {
|
|
151
197
|
const attrs = {};
|
|
152
198
|
for (const k of CFG.kept) { const v = e.getAttribute(k); if (v) attrs[k] = v; }
|
|
153
199
|
const name = accName(e);
|
|
154
200
|
// Never a state class (active, selected, is-open): it moves to another element (memory.py STATE_CLASS).
|
|
155
201
|
const classes = [...e.classList].filter((c) => /^[A-Za-z_-][\w-]*$/.test(c) && !STATE_CLASS.test(c)).slice(0, 4);
|
|
156
|
-
|
|
202
|
+
const f = { tag: e.tagName.toLowerCase(), attributes: attrs, classes, xpath: xpath(e), role: e.getAttribute('role') || implicitRole(e), name: name.slice(0, 120), text: name ? '' : textOf(e).slice(0, 120) };
|
|
203
|
+
const rel = relXpath(e, f);
|
|
204
|
+
if (rel) f.rel_xpath = rel;
|
|
205
|
+
return f;
|
|
157
206
|
};
|
|
158
207
|
// How many elements each kind of locator for `e` matches right now, counted at the event: ForgeQE checks locators
|
|
159
208
|
// through the DevTools protocol, but a click that opens another page can take the element away before it looks.
|
|
@@ -178,6 +227,8 @@ RECORDER_JS = r"""(() => {
|
|
|
178
227
|
if (/\d/.test(f.name) || f.name.length > 80) out.role_names = same.slice(0, 400).map((x) => accName(x).slice(0, 160));
|
|
179
228
|
}
|
|
180
229
|
if (f.name) out.label = deepAll('input, select, textarea, [aria-label]', rs).filter((x) => labelText(x) === f.name).length;
|
|
230
|
+
// The relative path is counted here too: it is built to find one element, and a page can still hold a second.
|
|
231
|
+
if (f.rel_xpath) out.rel_xpath = xpCount(f.rel_xpath);
|
|
181
232
|
return out;
|
|
182
233
|
};
|
|
183
234
|
const shown = (e) => {
|
|
@@ -190,7 +241,11 @@ RECORDER_JS = r"""(() => {
|
|
|
190
241
|
// Nine cards with the same "Book online now" button: the card that holds it, by a text only that card has ("FABIA
|
|
191
242
|
// Auto"), then the button inside it, as Playwright writes it: getByRole('listitem').filter({ hasText }).getByRole(…).
|
|
192
243
|
// A field with no label of its own is found the same way, by the text beside it in the group that holds it.
|
|
193
|
-
|
|
244
|
+
// Roles a thing that holds other things has. Only roles Playwright matches without an accessible name: `region` and
|
|
245
|
+
// `form` need one, so a <section> or a <form> is addressed by its tag below instead.
|
|
246
|
+
const CONTAINER_ROLES = new Set(['listitem', 'row', 'article', 'dialog', 'alertdialog', 'group', 'tabpanel', 'gridcell',
|
|
247
|
+
'cell', 'status', 'alert', 'list', 'table', 'grid', 'rowgroup', 'menu', 'menubar', 'toolbar', 'tablist', 'figure',
|
|
248
|
+
'note', 'tooltip', 'log', 'banner', 'main', 'navigation', 'complementary', 'contentinfo', 'treegrid', 'tree']);
|
|
194
249
|
const containerRole = (x) => {
|
|
195
250
|
const r = x.getAttribute('role');
|
|
196
251
|
if (r) return CONTAINER_ROLES.has(r) ? r : '';
|
|
@@ -201,13 +256,31 @@ RECORDER_JS = r"""(() => {
|
|
|
201
256
|
if (x.tagName === 'FIELDSET') return 'group';
|
|
202
257
|
return '';
|
|
203
258
|
};
|
|
259
|
+
// Tags that hold other things and are worth addressing by the tag alone: which one is meant is settled by the text
|
|
260
|
+
// filter, and the count below proves only one of them has that text.
|
|
261
|
+
const CONTAINER_TAGS = new Set(['section', 'article', 'aside', 'nav', 'header', 'footer', 'main', 'form', 'fieldset',
|
|
262
|
+
'figure', 'details', 'dialog', 'table', 'thead', 'tbody', 'tr', 'td', 'th', 'li', 'dl', 'dd', 'blockquote']);
|
|
263
|
+
// An attribute that names a container and carries no value of its own making. The value is put in a selector, so a
|
|
264
|
+
// quote or an angle bracket in it rules it out rather than being escaped away.
|
|
265
|
+
const CONTAINER_ATTRS = ['data-testid', 'data-test-id', 'data-test', 'data-qa', 'data-cy', 'aria-label'];
|
|
266
|
+
const plainAttr = (v) => !!v && v.length <= 80 && !/["'\\<>\u0000-\u001f]/.test(v) && !XP_GEN.test(v);
|
|
204
267
|
const stableClass = (c) => /^[A-Za-z][\w-]{2,40}$/.test(c) && !/\d{3,}|__|^(?:css|sc|jsx|svelte|emotion)-/i.test(c) && !STATE_CLASS.test(c);
|
|
205
268
|
// A class a page sets for a state (the item under the pointer, the one chosen, a menu open): it moves between elements.
|
|
206
269
|
const STATE_CLASS = new RegExp(CFG.stateClass, 'i');
|
|
207
270
|
// A web component by its tag alone (memory.py _COMPONENT_TAG): <promo-card>, whose controls are in its shadow root.
|
|
208
271
|
const COMPONENT_TAG = /^[a-z][a-z0-9]{0,30}(?:-[a-z0-9]{1,30}){1,4}$/;
|
|
209
272
|
const componentTag = (x) => { const t = x.tagName.toLowerCase(); return COMPONENT_TAG.test(t) ? t : ''; };
|
|
210
|
-
const containerCss = (x) => {
|
|
273
|
+
const containerCss = (x) => {
|
|
274
|
+
const tag = x.tagName.toLowerCase();
|
|
275
|
+
// Its own test id or label first: a card a repository marked is the steadiest container there is.
|
|
276
|
+
for (const k of CONTAINER_ATTRS) { const v = x.getAttribute(k); if (plainAttr(v)) return '[' + k + '="' + v + '"]'; }
|
|
277
|
+
const c = [...x.classList].find(stableClass);
|
|
278
|
+
if (c) return tag + '.' + c;
|
|
279
|
+
const comp = componentTag(x);
|
|
280
|
+
if (comp) return comp;
|
|
281
|
+
// A tag that holds things, with nothing else to go on (a <section> whose classes a build makes up).
|
|
282
|
+
return CONTAINER_TAGS.has(tag) ? tag : '';
|
|
283
|
+
};
|
|
211
284
|
const lowText = (x) => norm(x.textContent).toLowerCase();
|
|
212
285
|
// A component's own roots: it, its open shadow roots, and the one the element is in (a closed root is reached only
|
|
213
286
|
// from inside it), so what it holds is searched where it is, not only in its light DOM.
|
|
@@ -219,7 +292,12 @@ RECORDER_JS = r"""(() => {
|
|
|
219
292
|
return out;
|
|
220
293
|
};
|
|
221
294
|
const boxText = (box, e) => norm(boxRoots(box, e).map((r) => (r === box ? flatText(box) : r === box.shadowRoot ? '' : flatText(r))).join(' ')).toLowerCase();
|
|
222
|
-
//
|
|
295
|
+
// A text that reports a state or a running total rather than naming the thing: a status ("Overdue", "Active"), an
|
|
296
|
+
// amount, a time, a date, a count. It is a poor anchor — it changes while the thing it sits in stays the same — so
|
|
297
|
+
// it is kept, but only after every steadier text.
|
|
298
|
+
const SHAKY_TEXT = new RegExp(CFG.shakyText, 'i');
|
|
299
|
+
// The texts that could tell this container from the others: its headings, then its labels, then short texts of its
|
|
300
|
+
// own — each group with the texts that name a thing before the ones that report its state.
|
|
223
301
|
const anchorTexts = (box, own, rs = [box], self = null) => {
|
|
224
302
|
const out = [];
|
|
225
303
|
const add = (t, at) => { t = norm(t); if (t && t.length <= 80 && t !== own && !(self && at && deepContains(self, at)) && !out.includes(t)) out.push(t); };
|
|
@@ -231,7 +309,10 @@ RECORDER_JS = r"""(() => {
|
|
|
231
309
|
// Never the control's own text (a "×" of a Close): it tells nothing of which container this is.
|
|
232
310
|
for (let n = walker.nextNode(); n && k < 40; n = walker.nextNode(), k++) if (!['STYLE', 'SCRIPT', 'TEMPLATE'].includes(n.parentNode && n.parentNode.nodeName)) add(n.data, n.parentNode);
|
|
233
311
|
}
|
|
234
|
-
|
|
312
|
+
// A steady text first, in the order it was found; a state or an amount only after them.
|
|
313
|
+
const steady = out.filter((t) => !SHAKY_TEXT.test(t.trim()));
|
|
314
|
+
const shaky = out.filter((t) => SHAKY_TEXT.test(t.trim()));
|
|
315
|
+
return [...steady, ...shaky].slice(0, 12);
|
|
235
316
|
};
|
|
236
317
|
const innerOf = (e, f, box, rs = [box]) => {
|
|
237
318
|
const inBox = (sel) => rs.flatMap((r) => [...r.querySelectorAll(sel)]).filter(visible);
|
|
@@ -1065,5 +1146,5 @@ def recorder_js(binding: str, kept: Any, *, leader: Dict[str, Any], badge: bool
|
|
|
1065
1146
|
The page script; ``badge``: no panel, only a badge that says it records (a recording started from the web app);
|
|
1066
1147
|
``pw``: the saved logins' password fingerprints for this recording (recordsession.password_prints), never a password.
|
|
1067
1148
|
"""
|
|
1068
|
-
config = {"binding": binding, "kept": list(kept), "leader": leader, "commands": [list(c) for c in COMMAND_KEYS], "badge": bool(badge), "stateClass": STATE_CLASS, **({"pw": pw} if pw else {})}
|
|
1149
|
+
config = {"binding": binding, "kept": list(kept), "leader": leader, "commands": [list(c) for c in COMMAND_KEYS], "badge": bool(badge), "stateClass": STATE_CLASS, "textGen": TEXT_GEN, "shakyText": SHAKY_TEXT, **({"pw": pw} if pw else {})}
|
|
1069
1150
|
return RECORDER_JS.replace("__CONFIG__", json.dumps(config))
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"""ForgeQE's Tosca reader: Tricentis Tosca .tsu exports → NTIR (neutral test JSON) and a readable view per test case.
|
|
2
2
|
|
|
3
|
-
The .tsu graph is read by ToscaTSU's parser (vendor/toscatsu, MIT, unchanged); this package wraps it, adds what
|
|
4
|
-
|
|
3
|
+
The .tsu graph is read by ToscaTSU's parser (vendor/toscatsu, MIT, unchanged); this package wraps it, adds what
|
|
4
|
+
Bridge needs (routes by engine, tool-neutral locators, secrets as variable names, fidelity anchors), and never
|
|
5
5
|
runs or trusts anything inside the export.
|
|
6
6
|
"""
|
|
7
7
|
from __future__ import annotations
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""A test case's NTIR as plain text: what
|
|
1
|
+
"""A test case's NTIR as plain text: what Bridge and a person read in place of the binary .tsu.
|
|
2
2
|
|
|
3
3
|
Every action line carries its node id ([n12]) so the converted test can name the Tosca step it implements, and the
|
|
4
4
|
fidelity check can match them. Values from the .tsu are quoted as data; secrets show only their variable's name.
|
package/py/forgeqe_tosca/tsu.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""Read a Tosca .tsu export safely, and index what
|
|
1
|
+
"""Read a Tosca .tsu export safely, and index what Bridge needs that ToscaTSU's manifest does not carry.
|
|
2
2
|
|
|
3
3
|
A .tsu is gzip-compressed JSON: {"Entities": [{Surrogate, ObjectClass, Attributes, Assocs}, ...]}. It comes from
|
|
4
4
|
someone else's workspace, so it is untrusted: its size is capped before and after unpacking, nothing in it is run, and
|
|
@@ -19,7 +19,7 @@ _CHUNK = 1024 * 1024
|
|
|
19
19
|
|
|
20
20
|
|
|
21
21
|
class TsuError(Exception):
|
|
22
|
-
"""The file is not a .tsu
|
|
22
|
+
"""The file is not a .tsu Bridge can read; the message says why in plain words."""
|
|
23
23
|
|
|
24
24
|
|
|
25
25
|
def load(path: Path) -> Dict[str, Any]:
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: playwright-automation
|
|
3
|
+
description: "Use when the repository's browser tests are Playwright in any language — TypeScript or JavaScript (@playwright/test, playwright.config.ts), Python (pytest-playwright), Java (JUnit/TestNG) or .NET (MSTest/NUnit/xUnit): where its settings and fixtures live, narrowing a locator instead of indexing, strict mode, sign-in state, frames and shadow DOM, reading a ForgeQE recording handoff, and the command that runs one test."
|
|
4
|
+
agents: [scribe]
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# Playwright
|
|
8
|
+
|
|
9
|
+
This adds Playwright's own mechanics to the test rules you already have; it never replaces them. Where a rule
|
|
10
|
+
says what to do (locator order, retrying assertions, overlays, test data, repository conventions), that rule
|
|
11
|
+
stands — what follows is how Playwright does it.
|
|
12
|
+
|
|
13
|
+
The browser API is the same in every language; the names and the runner differ. Read the reference for the
|
|
14
|
+
repository's language before writing code:
|
|
15
|
+
|
|
16
|
+
- `references/typescript.md` — TypeScript / JavaScript (`@playwright/test`, the full runner)
|
|
17
|
+
- `references/python.md` — Python (`pytest-playwright`)
|
|
18
|
+
- `references/java.md` — Java (JUnit 5 / TestNG, Maven or Gradle)
|
|
19
|
+
- `references/dotnet.md` — .NET (NUnit, MSTest, xUnit)
|
|
20
|
+
|
|
21
|
+
## Read the setup first
|
|
22
|
+
- Find the runner's config and note base URL, browser, headless, timeouts, retries and trace. Each reference
|
|
23
|
+
names the file for its language and which settings belong in it.
|
|
24
|
+
- Find the base class or fixture the repository's tests use, and its page objects. New tests use them; never
|
|
25
|
+
build a browser by hand when the repository hands one out.
|
|
26
|
+
- Find how sign-in is done and reuse the saved storage state. Sign in inside a test only when sign-in is the
|
|
27
|
+
thing under test.
|
|
28
|
+
|
|
29
|
+
## Never install anything
|
|
30
|
+
- Do not run `npm install`, `pip install`, `playwright install`, `playwright.ps1 install`, `mvn dependency:get`,
|
|
31
|
+
`dotnet add package`, or any other installer. Packages and browsers are installed by ForgeQE. If something is
|
|
32
|
+
missing, name the package or browser and the version and stop.
|
|
33
|
+
- Do not edit a manifest or lockfile (`package.json`, `package-lock.json`, `pyproject.toml`,
|
|
34
|
+
`requirements.txt`, `pom.xml`, `build.gradle`, `*.csproj`). Ask through your request tools instead.
|
|
35
|
+
|
|
36
|
+
## Making a locator unique
|
|
37
|
+
- Narrow, do not index: `filter({ hasText, hasNotText, has, hasNot, visible })`, chaining,
|
|
38
|
+
`and()`, `or()`, `within(other)` (v1.64+: `saveButton.within(dialog)`), `visible()` (v1.63+).
|
|
39
|
+
- Strict mode is a signal, not an obstacle. When a one-element action throws because the locator matched
|
|
40
|
+
several, the locator is ambiguous: scope it to the container holding the one you mean.
|
|
41
|
+
- `getByTestId` reads `data-testid` by default. A repository can point it elsewhere (`testIdAttribute` in the
|
|
42
|
+
config, or `selectors.setTestIdAttribute()`), so check before using it; when unsure, use an attribute
|
|
43
|
+
selector.
|
|
44
|
+
- An accessible name comes from `aria-label`, `aria-labelledby`, a wired `<label>`, or the element's own text —
|
|
45
|
+
in that order. If a role locator will not match, the name you expect is probably not the computed one.
|
|
46
|
+
- `describe()` (v1.53+) names a locator in the trace and the report. Use it where an expression is unavoidably
|
|
47
|
+
opaque.
|
|
48
|
+
|
|
49
|
+
## From ForgeQE's handoff
|
|
50
|
+
- A locator marked ✓ was verified against the live page during the run. Use it.
|
|
51
|
+
- A locator carrying a warning ("a framework made this value", "the page gave this element another value",
|
|
52
|
+
"this name holds data that changes") passes the run it was recorded on and fails the next. Never reach for it
|
|
53
|
+
first; use the steadier one listed beside it.
|
|
54
|
+
- A `within` locator is already the scoped form
|
|
55
|
+
(`getByRole('listitem').filter({ hasText: … }).getByRole(…)`). Keep it; do not flatten it to a path.
|
|
56
|
+
- A `role_pattern` or `text_pattern` locator matches the part of the name that holds. Keep the pattern; do not
|
|
57
|
+
spell out this run's value.
|
|
58
|
+
- A step shown with only an XPath means every semantic locator was checked and none was unique. Read the page
|
|
59
|
+
snapshot under that step and build a scoped locator from what it shows before falling back to the path.
|
|
60
|
+
|
|
61
|
+
## The retrying assertions
|
|
62
|
+
These are the ones that retry, so these are the ones to use:
|
|
63
|
+
`toBeVisible`, `toBeHidden`, `toBeAttached`, `toHaveText`, `toContainText`, `toHaveValue`, `toHaveValues`,
|
|
64
|
+
`toHaveCount`, `toHaveAttribute`, `toHaveClass`, `toContainClass`, `toHaveCSS`, `toHaveId`, `toHaveJSProperty`,
|
|
65
|
+
`toBeChecked`, `toBeEnabled`, `toBeDisabled`, `toBeEditable`, `toBeEmpty`, `toBeFocused`, `toBeInViewport`,
|
|
66
|
+
`toHaveRole`, `toHaveAccessibleName`, `toHaveAccessibleDescription`, `toHaveAccessibleErrorMessage`,
|
|
67
|
+
`toMatchAriaSnapshot`, `toHaveScreenshot`; on the page, `toHaveTitle`, `toHaveURL`; on a response, `toBeOK`.
|
|
68
|
+
|
|
69
|
+
- A plain assertion on a value you read yourself (`isVisible()`, `textContent()`) does not retry, whatever it
|
|
70
|
+
is wrapped in.
|
|
71
|
+
- To wait for a request, create the response promise *before* the click that triggers it
|
|
72
|
+
(`waitForResponse` / `RunAndWaitForResponseAsync`), not after.
|
|
73
|
+
- `expect.soft`, `expect.poll` and `toPass` are the Node runner's only. In Python, Java and .NET use the test
|
|
74
|
+
framework's own retry.
|
|
75
|
+
|
|
76
|
+
## Isolation and sign-in
|
|
77
|
+
- One context per test. Playwright gives a fresh context by default; state shared through a static field or a
|
|
78
|
+
module-level variable defeats it.
|
|
79
|
+
- Save sign-in once and load it. That file holds live session credentials: it belongs in `.gitignore`, never in
|
|
80
|
+
a commit. Read secret values from the environment and fail with a clear message when one is missing; add new
|
|
81
|
+
names to the repository's example file without values.
|
|
82
|
+
- Session storage is not saved with storage state; restore it by hand if the app needs it. For an app keeping
|
|
83
|
+
tokens in IndexedDB, enable the IndexedDB option when saving.
|
|
84
|
+
- If tests write server-side data, give each worker its own account.
|
|
85
|
+
|
|
86
|
+
## Frames and shadow DOM
|
|
87
|
+
- A control in an iframe needs `frameLocator` / `frame_locator`; an ordinary locator will not cross into it.
|
|
88
|
+
The handoff names the frame chain for the step.
|
|
89
|
+
- Locators pierce **open** shadow roots; XPath does not. A closed root is unreachable — when the handoff says
|
|
90
|
+
the recording opened closed roots, do the same once in the fixture or base-class setup with the init script
|
|
91
|
+
the handoff gives, before the site loads.
|
|
92
|
+
|
|
93
|
+
## Overlay handlers
|
|
94
|
+
The test rules say when to use a handler and when to use a helper. Playwright's part: the handler exists from
|
|
95
|
+
1.42 (`addLocatorHandler` / `AddLocatorHandlerAsync`), takes the overlay's own container as its locator, and
|
|
96
|
+
its body runs on every action that the overlay blocks. Each reference gives the call for its language.
|
|
97
|
+
|
|
98
|
+
## Running and finishing
|
|
99
|
+
- Run only the test you wrote, with the repository's own command, and read the failure before changing
|
|
100
|
+
anything. Record a trace on failure and read it rather than re-running blind.
|
|
101
|
+
- Never commit a focus marker, a headed flag, or a pause (`test.only`, `--headed`, `page.pause()`, `PWDEBUG`).
|
|
102
|
+
- Mock third parties you do not control (`route` / `RouteAsync`) rather than testing their live site.
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# Playwright in .NET (C#)
|
|
2
|
+
|
|
3
|
+
Official statement: "Playwright is distributed as a .NET Standard 2.0 library. We recommend .NET 8"
|
|
4
|
+
(playwright.dev/dotnet/docs/intro). Match the `TargetFramework` in the repository's `.csproj`.
|
|
5
|
+
|
|
6
|
+
## Read the setup first
|
|
7
|
+
- The test project: the `.csproj` referencing `Microsoft.Playwright.NUnit` (or `.MSTest`, `.Xunit`,
|
|
8
|
+
`.Xunit.v3`). Note its target framework, `Nullable`, `TreatWarningsAsErrors`, analyzers, and anything set in
|
|
9
|
+
`Directory.Build.props` and `.editorconfig`.
|
|
10
|
+
- Base classes: tests inherit `PageTest` (giving `Page`, `Context`, `Browser` and `Expect`), or `ContextTest` /
|
|
11
|
+
`BrowserTest`. Repositories usually add their own (`BaseTest : PageTest`) that signs in, sets context options
|
|
12
|
+
or starts tracing. Inherit the repository's base, never `PageTest` directly when one exists.
|
|
13
|
+
- Page objects: classes taking `IPage`, exposing `ILocator` properties, with `async Task` methods.
|
|
14
|
+
|
|
15
|
+
## Shape of a test
|
|
16
|
+
```csharp
|
|
17
|
+
using Microsoft.Playwright;
|
|
18
|
+
using Microsoft.Playwright.NUnit;
|
|
19
|
+
|
|
20
|
+
public class CheckoutTests : PageTest
|
|
21
|
+
{
|
|
22
|
+
[Test]
|
|
23
|
+
public async Task PlacesOrder()
|
|
24
|
+
{
|
|
25
|
+
await Page.GotoAsync("/cart");
|
|
26
|
+
await Page.GetByRole(AriaRole.Button, new() { Name = "Checkout" }).ClickAsync();
|
|
27
|
+
await Expect(Page.GetByRole(AriaRole.Heading, new() { Name = "Payment" })).ToBeVisibleAsync();
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
```
|
|
31
|
+
Attributes by framework: NUnit `[TestFixture]`/`[Test]` with `[Parallelizable(ParallelScope.Self)]`;
|
|
32
|
+
MSTest `[TestClass]`/`[TestMethod]`; xUnit `[Fact]`.
|
|
33
|
+
|
|
34
|
+
## Browser and context settings
|
|
35
|
+
- Launch settings live in the `.runsettings` file's `<Playwright>` section:
|
|
36
|
+
`<BrowserName>chromium</BrowserName>` and
|
|
37
|
+
`<LaunchOptions><Channel>chrome</Channel><Headless>true</Headless></LaunchOptions>`. It is used through
|
|
38
|
+
`dotnet test --settings <file>` or `<RunSettingsFilePath>` in the `.csproj`. `BROWSER` and `HEADED=1`
|
|
39
|
+
override it.
|
|
40
|
+
- Context settings (viewport, locale, time zone, base URL, storage state) go in an override of
|
|
41
|
+
`public override BrowserNewContextOptions ContextOptions()` in the base class.
|
|
42
|
+
|
|
43
|
+
## Naming and style
|
|
44
|
+
- PascalCase with an `Async` suffix and `new() { ... }` option objects: `GotoAsync`, `FillAsync`,
|
|
45
|
+
`ToHaveTextAsync`, `FrameLocator`, `Context.StorageStateAsync(new() { Path = ... })`,
|
|
46
|
+
`.Filter(new() { HasText = "FABIA Auto" })`.
|
|
47
|
+
- Tests are `public async Task` methods that await every call. Never `.Result`, `.Wait()`, `Thread.Sleep` or
|
|
48
|
+
`Task.Delay`.
|
|
49
|
+
- Use `ConfigureAwait(false)` exactly where the repository does (an analyzer such as CA2007 asks for it).
|
|
50
|
+
Follow the analyzers so the build gains no warnings.
|
|
51
|
+
- Retrying assertions: `await Expect(locator).ToBeVisibleAsync()`, `ToHaveTextAsync`, `ToHaveValueAsync`,
|
|
52
|
+
`await Expect(Page).ToHaveURLAsync(...)`. Use `Assert.That` for plain values only, never on
|
|
53
|
+
`await locator.IsVisibleAsync()`.
|
|
54
|
+
- Wait for outcomes with `Page.WaitForURLAsync`, `Page.RunAndWaitForResponseAsync`, or an assertion.
|
|
55
|
+
|
|
56
|
+
## The overlay handler's call
|
|
57
|
+
The test rules say when a handler is right and when a helper is. Playwright's call, from 1.42, registered in
|
|
58
|
+
`[SetUp]` of the base class:
|
|
59
|
+
```csharp
|
|
60
|
+
await Page.AddLocatorHandlerAsync(banner, async () => {
|
|
61
|
+
await banner.GetByRole(AriaRole.Button, new() { Name = "Accept all", Exact = true }).ClickAsync();
|
|
62
|
+
await Expect(banner).ToBeHiddenAsync();
|
|
63
|
+
});
|
|
64
|
+
```
|
|
65
|
+
In .NET terms, the rule that an "if present" helper may ignore only the overlay not showing means catching
|
|
66
|
+
`TimeoutException` alone — never `PlaywrightException`.
|
|
67
|
+
|
|
68
|
+
## Run one test
|
|
69
|
+
```bash
|
|
70
|
+
dotnet build <Tests.csproj>
|
|
71
|
+
dotnet test <Tests.csproj> --no-build --settings <file>.runsettings \
|
|
72
|
+
--filter "FullyQualifiedName~MyTests.CheckoutTests.PlacesOrder" --logger "console;verbosity=normal"
|
|
73
|
+
```
|
|
74
|
+
`--filter "Category=Smoke"` runs a category. `HEADED=1` runs headed, `BROWSER=firefox` switches browser,
|
|
75
|
+
`PWDEBUG=1` opens the Inspector. Trace: `pwsh bin/Debug/<tfm>/playwright.ps1 show-trace trace.zip`.
|
|
76
|
+
|
|
77
|
+
Browsers are installed by ForgeQE, not by you. If one is missing, name it and stop; do not run
|
|
78
|
+
`playwright.ps1 install` or `dotnet tool install`.
|
|
79
|
+
|
|
80
|
+
## Data, secrets, attributes
|
|
81
|
+
- Data: `[TestCase(...)]`, `[TestCaseSource(nameof(Cases))]`, or the repository's data files and builders.
|
|
82
|
+
- Secrets:
|
|
83
|
+
`Environment.GetEnvironmentVariable("SHOP_USER") ?? throw new InvalidOperationException("Set SHOP_USER")`.
|
|
84
|
+
If the repository reads `TestContext.Parameters` from `.runsettings`, follow that, without committing values.
|
|
85
|
+
- Match the repository's `[Category]`, `[Parallelizable]`, `[Description]` and naming. `PageTest` gives each
|
|
86
|
+
test its own context, so tests must not share state through static fields.
|
|
87
|
+
|
|
88
|
+
## Gaps against the Node runner
|
|
89
|
+
No projects, sharding or HTML reporter. Isolation comes from the `PageTest` / `ContextTest` base classes;
|
|
90
|
+
parallelism from NUnit, MSTest or xUnit settings the repository already has.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# Playwright in Java
|
|
2
|
+
|
|
3
|
+
Official requirement: Java 8 or higher (playwright.dev/java/docs/intro). The docs' example pom pins
|
|
4
|
+
`com.microsoft.playwright:playwright` at 1.64.0 and sets maven-compiler source/target to 1.8. Use whatever
|
|
5
|
+
version the repository's `pom.xml` or `build.gradle` already declares — do not bump it.
|
|
6
|
+
|
|
7
|
+
## Shape of a test
|
|
8
|
+
```java
|
|
9
|
+
import com.microsoft.playwright.*;
|
|
10
|
+
import com.microsoft.playwright.options.AriaRole;
|
|
11
|
+
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
|
|
12
|
+
|
|
13
|
+
page.navigate("/cart");
|
|
14
|
+
page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Checkout")).click();
|
|
15
|
+
assertThat(page.getByRole(AriaRole.HEADING,
|
|
16
|
+
new Page.GetByRoleOptions().setName("Payment"))).isVisible();
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Naming
|
|
20
|
+
camelCase plus option builder objects: `new Page.ClickOptions().setTimeout(5000)`,
|
|
21
|
+
`new Locator.FilterOptions().setHasText("FABIA Auto")`. Roles are the `AriaRole` enum, not strings.
|
|
22
|
+
Assertions are `assertThat(locator).hasText(...)`, `.isVisible()`, `assertThat(page).hasURL(...)`.
|
|
23
|
+
|
|
24
|
+
## Isolation
|
|
25
|
+
Create `Playwright` and `Browser` once per class; create a fresh `BrowserContext` per test in
|
|
26
|
+
`@BeforeEach` and close it in `@AfterEach`. JUnit 5 users may have `@UsePlaywright` fixtures instead —
|
|
27
|
+
follow whichever the repository uses.
|
|
28
|
+
|
|
29
|
+
## Running one test
|
|
30
|
+
```bash
|
|
31
|
+
mvn test -Dtest=CheckoutTest#completesOrder
|
|
32
|
+
```
|
|
33
|
+
Tracing:
|
|
34
|
+
```java
|
|
35
|
+
context.tracing().start(new Tracing.StartOptions().setScreenshots(true).setSnapshots(true));
|
|
36
|
+
context.tracing().stop(new Tracing.StopOptions().setPath(Paths.get("trace.zip")));
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Gaps against the Node runner
|
|
40
|
+
No projects, fixtures-as-config, sharding or HTML reporter. Parallelism and reporting come from
|
|
41
|
+
JUnit 5 or TestNG and whatever Surefire configuration the repository has.
|