@capagents/forgeqe 2.7.1 → 2.7.3
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 +82 -18
- package/THIRD_PARTY_NOTICES.md +62 -22
- package/bin/forgeqe.js +1 -1
- package/dist/docs-site/docs/architecture/index.html +1 -1
- package/dist/docs-site/docs/containers/index.html +1 -1
- package/dist/docs-site/docs/index.html +71 -2
- package/dist/docs-site/docs/search.js +1 -1
- package/dist/forgeqe.js +1775 -1520
- package/dist/web/THIRD_PARTY_NOTICES.md +578 -51
- package/dist/web/assets/Agent-DU51Em-3.js +4 -0
- package/dist/web/assets/ApiTests-D6YhbfPF.js +10 -0
- package/dist/web/assets/Chat-CQsQvyDs.js +3 -0
- package/dist/web/assets/Data-Djj0u25X.js +3 -0
- package/dist/web/assets/Evidence-R2GZ5yW9.js +1 -0
- package/dist/web/assets/Features-C1qvr-oy.js +1 -0
- package/dist/web/assets/Jobs-BOr2nkQa.js +5 -0
- package/dist/web/assets/KindPage-CB2gMzhI.js +6 -0
- package/dist/web/assets/Migration-71lvv1zU.js +2 -0
- package/dist/web/assets/Product-BAQtMlzO.js +7 -0
- package/dist/web/assets/Product-DLioOiRN.css +1 -0
- package/dist/web/assets/Quality-DeUvoOND.js +1 -0
- package/dist/web/assets/Record-CPjgxHRX.js +2 -0
- package/dist/web/assets/Regression-D8V0CNAw.js +5 -0
- package/dist/web/assets/Reports-Bhv6gqFl.js +2 -0
- package/dist/web/assets/Response-CXyWQxrt.js +4 -0
- package/dist/web/assets/Runs-Ba8X4nId.js +2 -0
- package/dist/web/assets/Shell-BoXDubsc.js +3 -0
- package/dist/web/assets/TestCases-DEciDMh1.js +1 -0
- package/dist/web/assets/TestData-DY6MVYdx.js +2 -0
- package/dist/web/assets/Tosca-BzNnPm0_.js +2 -0
- package/dist/web/assets/WhatsNew-7O1MlqCy.js +1 -0
- package/dist/web/assets/dataParts-0a9Sjn2u.js +3 -0
- package/dist/web/assets/index-C9TchKsF.css +2 -0
- package/dist/web/assets/index-DcmN4YB2.js +43 -0
- package/dist/web/assets/logos-BnPN8M-S.js +1 -0
- package/dist/web/assets/parts-mP2z3tbH.js +1 -0
- package/dist/web/assets/productParts-B2wO-b1i.js +1 -0
- package/dist/web/assets/qualityParts-ByR8_rNE.js +1 -0
- package/dist/web/assets/segmented-BZcnZadS.js +1 -0
- package/dist/web/assets/{thread-CHhZJi-Y.js → thread-DLf1W085.js} +2 -2
- package/dist/web/assets/usePageChat-lpZh_ziF.js +1 -0
- package/dist/web/index.html +3 -3
- package/docs/ARCHITECTURE.md +1 -1
- package/docs/CONTAINERS.md +1 -1
- package/docs/EVIDENCE.md +9 -4
- package/docs/GRAPHIFY.md +178 -0
- package/docs/PRODUCT_KNOWLEDGE.md +25 -4
- package/docs/PRODUCT_VIEWS.md +5 -2
- package/docs/prompts/graphify-evidence.md +167 -0
- package/docs/user-guide.html +71 -2
- package/evals/evidence/domain/base/orders-api/src/report.ts +4 -0
- package/evals/evidence/domain/base/orders-api/src/routes/admin.ts +2 -1
- package/evals/evidence/domain/cases/bad-function-removed/after/src/workflow.ts +6 -0
- package/evals/evidence/domain/cases/bad-function-removed/case.json +14 -0
- package/evals/evidence/domain/cases/bad-signature-changed/after/src/workflow.ts +6 -0
- package/evals/evidence/domain/cases/bad-signature-changed/case.json +14 -0
- package/evals/evidence/domain/cases/bad-state-set-directly/after/src/routes/admin.ts +2 -1
- package/evals/evidence/domain/cases/bad-untested-change/after/src/routes/admin.ts +2 -1
- package/evals/evidence/domain/cases/bad-untested-helper/after/src/report.ts +4 -0
- package/evals/evidence/domain/cases/bad-untested-helper/case.json +14 -0
- package/evals/evidence/domain/cases/good-optional-parameter/after/src/workflow.ts +6 -0
- package/evals/evidence/domain/cases/good-optional-parameter/case.json +12 -0
- package/evals/evidence/domain/cases/good-tested-helper/after/src/clients/payments.ts +8 -0
- package/evals/evidence/domain/cases/good-tested-helper/case.json +12 -0
- package/forgeqe.example.yaml +14 -1
- package/package.json +17 -14
- package/prompts/README.md +1 -0
- package/prompts/product-investigate.md +1 -1
- package/prompts/tosca.md +64 -0
- package/py/forgeqe_desktop/models.py +14 -5
- package/py/forgeqe_engine/__init__.py +1 -1
- package/py/forgeqe_knowledge/graphify_bridge.py +156 -0
- package/py/forgeqe_tosca/__init__.py +85 -0
- package/py/forgeqe_tosca/__main__.py +50 -0
- package/py/forgeqe_tosca/ntir.py +484 -0
- package/py/forgeqe_tosca/render.py +128 -0
- package/py/forgeqe_tosca/tsu.py +187 -0
- package/py/forgeqe_tosca/vendor/toscatsu/LICENSE +26 -0
- package/py/forgeqe_tosca/vendor/toscatsu/UPSTREAM +7 -0
- package/py/forgeqe_tosca/vendor/toscatsu/gen_tsu.py +735 -0
- package/py/forgeqe_tosca/vendor/toscatsu/parse_tsu.py +1979 -0
- package/py/forgeqe_tosca/vendor/toscatsu/spec_to_manifest.py +878 -0
- package/py/forgeqe_tosca/vendored.py +50 -0
- package/skills/tosca-knowledge/SKILL.md +56 -0
- package/skills/tosca-knowledge/references/actions-and-values.md +63 -0
- package/skills/tosca-knowledge/references/locators.md +29 -0
- package/skills/tosca-knowledge/references/mapping-cypress.md +21 -0
- package/skills/tosca-knowledge/references/mapping-playwright.md +31 -0
- package/skills/tosca-knowledge/references/mapping-selenium-webdriverio.md +26 -0
- package/skills/tosca-knowledge/references/ntir.md +46 -0
- package/dist/web/assets/Agent-Ol1sf0Me.js +0 -4
- package/dist/web/assets/ApiTests-BfN5VysH.js +0 -10
- package/dist/web/assets/Chat-Bk2ECB9h.js +0 -3
- package/dist/web/assets/Data-DSZ9xkqr.js +0 -3
- package/dist/web/assets/Evidence-BVjGRwcr.js +0 -1
- package/dist/web/assets/Features-DQEzR0Mz.js +0 -1
- package/dist/web/assets/Jobs-chEiiqmE.js +0 -5
- package/dist/web/assets/KindPage-D-Jah0cx.js +0 -6
- package/dist/web/assets/Migration-DMIBgW27.js +0 -2
- package/dist/web/assets/Product-B3buEWja.js +0 -1
- package/dist/web/assets/Quality-DuELzB5I.js +0 -1
- package/dist/web/assets/Record-DLTuuxTP.js +0 -2
- package/dist/web/assets/Regression-Bjz4Xfbo.js +0 -5
- package/dist/web/assets/Reports-p8Qp2KwM.js +0 -2
- package/dist/web/assets/Response-DGJAmOI0.js +0 -4
- package/dist/web/assets/Runs-CnPPwEq7.js +0 -2
- package/dist/web/assets/Shell-Molb7AUz.js +0 -3
- package/dist/web/assets/TestCases-CUZ-kHja.js +0 -1
- package/dist/web/assets/TestData-B3P1fBRO.js +0 -2
- package/dist/web/assets/WhatsNew-CdiZ0Eob.js +0 -1
- package/dist/web/assets/arrow-down-D5oPK0MM.js +0 -1
- package/dist/web/assets/arrow-right-2yt0QgFJ.js +0 -1
- package/dist/web/assets/circle-DIklM9wF.js +0 -1
- package/dist/web/assets/circle-dashed-BZvX5dyl.js +0 -1
- package/dist/web/assets/circle-dot-Cd20PWQi.js +0 -1
- package/dist/web/assets/dataParts-D0dUqael.js +0 -3
- package/dist/web/assets/index-BC72t3H1.js +0 -43
- package/dist/web/assets/index-BiJ_Nvm1.css +0 -2
- package/dist/web/assets/keyboard-Dab5j5YB.js +0 -1
- package/dist/web/assets/pencil-DeEsXRZX.js +0 -1
- package/dist/web/assets/productParts-Ciuentrl.js +0 -1
- package/dist/web/assets/qualityParts-CZCG8hDs.js +0 -1
- package/dist/web/assets/segmented-BMOboT4H.js +0 -1
- package/dist/web/assets/usePageChat-eO0J5JlP.js +0 -1
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
"""ToscaTSU manifest → NTIR, the Neutral Test IR (described in skills/tosca-knowledge/references/ntir.md).
|
|
2
|
+
|
|
3
|
+
NTIR says what a Tosca test case does without any tool's syntax: pages and elements with ranked, tool-neutral
|
|
4
|
+
locators; a closed set of actions, assertions and control flow; data as literals, variables and environment variables.
|
|
5
|
+
Every action and assertion keeps a `tosca` anchor (step, element, ActionMode, property, value) so the fidelity check
|
|
6
|
+
can tell, step by step, whether a converted test still does what the Tosca test did.
|
|
7
|
+
|
|
8
|
+
Secrets: a Tosca-encrypted value is never kept. It becomes an environment variable's name, and the anchor shows
|
|
9
|
+
"<secret>".
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import re
|
|
14
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
15
|
+
|
|
16
|
+
NTIR_VERSION = "1.0"
|
|
17
|
+
|
|
18
|
+
ENCRYPTED_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}[A-Za-z0-9+/=]{20,}$")
|
|
19
|
+
REF_RE = re.compile(r"\{(PL|B|CP|XL)\[([^\]]+)\]\}")
|
|
20
|
+
WHOLE_REF_RE = re.compile(r"^\{(PL|B|CP|XL)\[([^\]]+)\]\}\*?$")
|
|
21
|
+
EXPR_RE = re.compile(r"^\{(CALC|DATE|RND|RANDOM|RANDOMTEXT|NUMBERTOSTRING|STRINGTONUMBER|STRINGREPLACE|TRIM|BASE64|MATH|REGEX|STRINGLENGTH|STRINGTOUPPER|STRINGTOLOWER|SUBSTRING)\b", re.I)
|
|
22
|
+
RESERVED_ENV = {"USERNAME", "USER", "PASSWORD", "HOME", "PATH", "SHELL", "TERM", "LANG", "LOGNAME", "PWD", "OLDPWD",
|
|
23
|
+
"SHLVL", "TMPDIR", "TEMP", "TMP", "COMPUTERNAME", "USERDOMAIN", "APPDATA", "SYSTEMROOT", "NODE_OPTIONS"}
|
|
24
|
+
|
|
25
|
+
MODE_NAMES = {"1": "input", "37": "set", "69": "verify", "101": "waitFor", "165": "bufferRead", "517": "optionalSet"}
|
|
26
|
+
|
|
27
|
+
CLICKS = {"CLICK": {}, "DOUBLECLICK": {"double": True}, "RIGHTCLICK": {"button": "right"},
|
|
28
|
+
"CLICKDOWN": {"phase": "down"}, "CLICKUP": {"phase": "up"}}
|
|
29
|
+
POINTER = {"HOVER": "hover", "MOUSEOVER": "hover", "SCROLL": "scroll", "SCROLLINTOVIEW": "scroll", "FOCUS": "focus", "BLUR": "blur"}
|
|
30
|
+
KEYS = {"ENTER": "Enter", "RETURN": "Enter", "TAB": "Tab", "ESCAPE": "Escape", "ESC": "Escape", "SPACE": "Space",
|
|
31
|
+
"BACKSPACE": "Backspace", "DELETE": "Delete", "DEL": "Delete", "HOME": "Home", "END": "End",
|
|
32
|
+
"ARROWUP": "ArrowUp", "UP": "ArrowUp", "ARROWDOWN": "ArrowDown", "DOWN": "ArrowDown", "ARROWLEFT": "ArrowLeft",
|
|
33
|
+
"LEFT": "ArrowLeft", "ARROWRIGHT": "ArrowRight", "RIGHT": "ArrowRight", "PGUP": "PageUp", "PAGEUP": "PageUp",
|
|
34
|
+
"PGDN": "PageDown", "PAGEDOWN": "PageDown", "INSERT": "Insert", "INS": "Insert"}
|
|
35
|
+
MODIFIERS = {"CTRL": "Control", "CONTROL": "Control", "SHIFT": "Shift", "ALT": "Alt", "OPT": "Alt", "CMD": "Meta",
|
|
36
|
+
"META": "Meta", "WIN": "Meta"}
|
|
37
|
+
|
|
38
|
+
# ActionProperty → (assertion when True, assertion when False)
|
|
39
|
+
BOOL_PROPS = {"visible": ("visible", "hidden"), "enabled": ("enabled", "disabled"), "disabled": ("disabled", "enabled"),
|
|
40
|
+
"checked": ("checked", "unchecked"), "selected": ("checked", "unchecked"), "focused": ("focused", "unfocused"),
|
|
41
|
+
"editable": ("editable", "readonly"), "readonly": ("readonly", "editable"), "exists": ("attached", "detached")}
|
|
42
|
+
|
|
43
|
+
ROLE_MAP = {"BUTTON": "button", "A": "link", "INPUT": "textbox", "TEXTAREA": "textbox", "IMG": "img", "SELECT": "combobox",
|
|
44
|
+
"H1": "heading", "H2": "heading", "H3": "heading", "H4": "heading", "H5": "heading", "H6": "heading",
|
|
45
|
+
"NAV": "navigation", "UL": "list", "OL": "list", "LI": "listitem"}
|
|
46
|
+
ANGULAR_CLASS_RE = re.compile(r"\bng-tns-c\d+-\d+\b|\bng-star-inserted\b")
|
|
47
|
+
DYNAMIC_RE = re.compile(r"(pn_id_|p-menubar(sub)?_|mat-[a-z-]+-\d+|ember\d+|react-select-\d+|\b[0-9a-f]{8,}\b|_\d{3,})", re.I)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def slug(s: str, sep: str = "_") -> str:
|
|
51
|
+
out = re.sub(r"[^A-Za-z0-9]+", sep, s or "").strip(sep).lower()
|
|
52
|
+
return out or "item"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def env_name(raw: str) -> str:
|
|
56
|
+
"""CP[UserPWD] → USER_PWD; never a name the shell or Node already uses."""
|
|
57
|
+
s = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", raw or "")
|
|
58
|
+
s = re.sub(r"[^A-Za-z0-9]+", "_", s).strip("_").upper() or "TOSCA_VALUE"
|
|
59
|
+
if s[0].isdigit():
|
|
60
|
+
s = "TOSCA_" + s
|
|
61
|
+
return "TOSCA_" + s if s in RESERVED_ENV else s
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class Builder:
|
|
65
|
+
def __init__(self, manifest: Dict[str, Any], engines: Dict[str, str], route_of) -> None:
|
|
66
|
+
self.m = manifest
|
|
67
|
+
self.meta = manifest.get("meta", {})
|
|
68
|
+
self.engines = engines
|
|
69
|
+
self.route_of = route_of
|
|
70
|
+
self.test_attributes = [a.lower() for a in (self.meta.get("config", {}).get("test_attributes") or [])]
|
|
71
|
+
self.pages: Dict[str, Dict[str, Any]] = {}
|
|
72
|
+
self.env: Dict[str, Dict[str, Any]] = {}
|
|
73
|
+
self.vars: Dict[str, str] = {}
|
|
74
|
+
self.unmapped: List[Dict[str, Any]] = []
|
|
75
|
+
self.warnings: List[str] = []
|
|
76
|
+
self.routes: Dict[str, int] = {}
|
|
77
|
+
self.counts = {"steps": 0, "actions": 0, "asserts": 0, "stores": 0, "unsupported": 0}
|
|
78
|
+
self.seq = 0
|
|
79
|
+
|
|
80
|
+
# Values -------------------------------------------------------------------------------------------------------
|
|
81
|
+
def secret_env(self, hint: str, origin: str) -> Dict[str, Any]:
|
|
82
|
+
name = env_name(hint)
|
|
83
|
+
self.env.setdefault(name, {"name": name, "from": origin, "secret": True})
|
|
84
|
+
self.env[name]["secret"] = True
|
|
85
|
+
return {"env": name, "secret": True}
|
|
86
|
+
|
|
87
|
+
def value(self, raw: str, resolved: Optional[str], element: str) -> Tuple[Dict[str, Any], Optional[str]]:
|
|
88
|
+
"""The NTIR value of a Tosca value, and a warning when it needs a person."""
|
|
89
|
+
v = resolved if resolved not in (None, "") else raw
|
|
90
|
+
if v is None:
|
|
91
|
+
v = ""
|
|
92
|
+
if ENCRYPTED_RE.match(v):
|
|
93
|
+
hint = raw[4:-2] if raw.startswith("{PL[") else element
|
|
94
|
+
return self.secret_env(hint, f"Tosca-encrypted value for '{element}'"), None
|
|
95
|
+
if v.startswith("$CONFIG:"):
|
|
96
|
+
key = v[len("$CONFIG:"):]
|
|
97
|
+
name = env_name(key)
|
|
98
|
+
secret = bool(re.search(r"(pass|pwd|secret|token|key)", key, re.I))
|
|
99
|
+
e = self.env.setdefault(name, {"name": name, "from": f"CP[{key}]", "secret": secret})
|
|
100
|
+
return {"env": name, "secret": e["secret"]}, None
|
|
101
|
+
m = WHOLE_REF_RE.match(v)
|
|
102
|
+
if m:
|
|
103
|
+
kind, name = m.group(1), m.group(2)
|
|
104
|
+
if kind == "CP":
|
|
105
|
+
n = env_name(name)
|
|
106
|
+
self.env.setdefault(n, {"name": n, "from": f"CP[{name}]", "secret": bool(re.search(r"(pass|pwd|secret|token)", name, re.I))})
|
|
107
|
+
return {"env": n, "secret": self.env[n]["secret"]}, None
|
|
108
|
+
if kind == "B":
|
|
109
|
+
return {"var": name}, None
|
|
110
|
+
if kind == "PL":
|
|
111
|
+
return {"param": name}, f"parameter {{PL[{name}]}} has no value at this call"
|
|
112
|
+
return {"data": name}, f"{{XL[{name}]}} reads a TestCaseDesign / Excel value; map it to the target's test data"
|
|
113
|
+
if EXPR_RE.match(v):
|
|
114
|
+
return {"expr": v}, f"Tosca expression {v[:60]} needs the target's own code"
|
|
115
|
+
if REF_RE.search(v):
|
|
116
|
+
parts: List[Any] = []
|
|
117
|
+
pos = 0
|
|
118
|
+
for mm in REF_RE.finditer(v):
|
|
119
|
+
if mm.start() > pos:
|
|
120
|
+
parts.append({"literal": v[pos:mm.start()]})
|
|
121
|
+
sub, _ = self.value(mm.group(0), None, element)
|
|
122
|
+
parts.append(sub)
|
|
123
|
+
pos = mm.end()
|
|
124
|
+
if pos < len(v):
|
|
125
|
+
parts.append({"literal": v[pos:]})
|
|
126
|
+
return {"concat": parts}, None
|
|
127
|
+
return {"literal": v}, None
|
|
128
|
+
|
|
129
|
+
def pick(self, raw: str, resolved: Optional[str]) -> str:
|
|
130
|
+
"""The raw value when its buffer references name variables this test sets (keeps the link), else the resolved one."""
|
|
131
|
+
refs = re.findall(r"\{B\[([^\]]+)\]\}", raw or "")
|
|
132
|
+
if refs and all(r in self.vars for r in refs) and not re.search(r"\{(PL|CP)\[", raw):
|
|
133
|
+
return raw
|
|
134
|
+
return resolved if resolved not in (None, "") else (raw or "")
|
|
135
|
+
|
|
136
|
+
# Pages and locators ---------------------------------------------------------------------------------------------
|
|
137
|
+
def locators(self, raw: Dict[str, Any], value_hint: str = "") -> Dict[str, Any]:
|
|
138
|
+
sh = {(c.get("name") or "").lower(): float(c.get("weight") or 0) for c in raw.get("_self_healing") or [] if isinstance(c, dict)}
|
|
139
|
+
cands: List[Dict[str, Any]] = []
|
|
140
|
+
|
|
141
|
+
def add(c: Dict[str, Any], score: float, key: str = "") -> None:
|
|
142
|
+
c["score"] = round(score + sh.get(key.lower(), 0) * 10, 1) if key else score
|
|
143
|
+
cands.append(c)
|
|
144
|
+
|
|
145
|
+
tag = str(raw.get("Tag") or "").upper()
|
|
146
|
+
text = str(raw.get("InnerText") or "").strip()
|
|
147
|
+
for k, v in raw.items():
|
|
148
|
+
if not k.startswith("attributes_") or not isinstance(v, str) or not v:
|
|
149
|
+
continue
|
|
150
|
+
attr = k[len("attributes_"):]
|
|
151
|
+
if attr.lower() in self.test_attributes:
|
|
152
|
+
rank = self.test_attributes.index(attr.lower())
|
|
153
|
+
add({"strategy": "testid", "attr": attr, "value": v}, 100 - rank, attr)
|
|
154
|
+
elif attr.lower() == "aria-label":
|
|
155
|
+
add({"strategy": "label", "value": v}, 65, attr)
|
|
156
|
+
elif attr.lower() not in ("class", "style", "id"):
|
|
157
|
+
add({"strategy": "attr", "attr": attr, "value": v, **({"fragile": True} if DYNAMIC_RE.search(v) else {})},
|
|
158
|
+
40 if DYNAMIC_RE.search(v) else 70, attr)
|
|
159
|
+
if isinstance(raw.get("Id"), str) and raw["Id"]:
|
|
160
|
+
dyn = bool(DYNAMIC_RE.search(raw["Id"]))
|
|
161
|
+
add({"strategy": "id", "value": raw["Id"], **({"fragile": True} if dyn else {})}, 30 if dyn else 90, "Id")
|
|
162
|
+
if isinstance(raw.get("AriaLabel"), str) and raw["AriaLabel"]:
|
|
163
|
+
add({"strategy": "label", "value": raw["AriaLabel"]}, 65, "AriaLabel")
|
|
164
|
+
if tag in ROLE_MAP and text and len(text) <= 80:
|
|
165
|
+
add({"strategy": "role", "role": ROLE_MAP[tag], "name": text}, 60, "InnerText")
|
|
166
|
+
if isinstance(raw.get("Href"), str) and raw["Href"]:
|
|
167
|
+
add({"strategy": "attr", "attr": "href", "value": raw["Href"]}, 50, "Href")
|
|
168
|
+
if isinstance(raw.get("Src"), str) and raw["Src"] and "cdn" not in raw["Src"].lower():
|
|
169
|
+
add({"strategy": "attr", "attr": "src", "value": raw["Src"]}, 45, "Src")
|
|
170
|
+
if text and len(text) <= 80 and not (tag in ROLE_MAP):
|
|
171
|
+
add({"strategy": "text", "value": text.strip("*"), **({"match": "contains"} if text.endswith("*") or text.startswith("*") else {})}, 40, "InnerText")
|
|
172
|
+
cls = ANGULAR_CLASS_RE.sub("", str(raw.get("ClassName") or "")).split()
|
|
173
|
+
if cls:
|
|
174
|
+
add({"strategy": "css", "value": (tag.lower() if tag else "") + "." + ".".join(cls)}, 25, "ClassName")
|
|
175
|
+
if "-" in tag:
|
|
176
|
+
add({"strategy": "css", "value": tag.lower()}, 20)
|
|
177
|
+
xp = raw.get("XPath") or raw.get("Xpath")
|
|
178
|
+
if isinstance(xp, str) and xp:
|
|
179
|
+
norm = re.sub(r"^id\('([^']+)'\)", r"//*[@id='\1']", xp.strip().strip("'\""))
|
|
180
|
+
dyn = bool(DYNAMIC_RE.search(xp))
|
|
181
|
+
add({"strategy": "xpath", "value": norm, **({"fragile": True} if dyn else {})}, 5 if dyn else 15, "XPath")
|
|
182
|
+
cands.sort(key=lambda c: -c["score"])
|
|
183
|
+
scope = [str(p.get("tag")).lower() for p in raw.get("_parent_chain") or [] if isinstance(p, dict) and "-" in str(p.get("tag") or "")]
|
|
184
|
+
meta = raw.get("_meta") or {}
|
|
185
|
+
out: Dict[str, Any] = {"locators": cands}
|
|
186
|
+
if scope:
|
|
187
|
+
out["scope"] = list(reversed(scope))[-1:] # the nearest custom-element ancestor, as ToscaTSU scopes
|
|
188
|
+
nth = meta.get("ConstraintIndex") if isinstance(meta, dict) else None
|
|
189
|
+
if isinstance(nth, str) and nth.isdigit() and int(nth) > 0:
|
|
190
|
+
out["nth"] = int(nth) - 1
|
|
191
|
+
return out
|
|
192
|
+
|
|
193
|
+
def element(self, module: str, name: str, raw: Dict[str, Any]) -> str:
|
|
194
|
+
pid = slug(module)
|
|
195
|
+
page = self.pages.setdefault(pid, {"id": pid, "name": module, "engine": self.engines.get(module, ""),
|
|
196
|
+
"route": self.route_of(self.engines.get(module, "")), "elements": []})
|
|
197
|
+
eid = slug(name)
|
|
198
|
+
existing = next((e for e in page["elements"] if e["id"] == eid), None)
|
|
199
|
+
if existing is None:
|
|
200
|
+
el = {"id": eid, "name": name, "tag": str(raw.get("Tag") or "").lower(), **self.locators(raw)}
|
|
201
|
+
if not el["locators"]:
|
|
202
|
+
self.warnings.append(f"'{name}' on '{module}' has no locator Tosca recorded")
|
|
203
|
+
page["elements"].append(el)
|
|
204
|
+
return f"{pid}.{eid}"
|
|
205
|
+
|
|
206
|
+
# Actions ------------------------------------------------------------------------------------------------------
|
|
207
|
+
def anchor(self, step: str, a: Dict[str, Any], secret: bool) -> Dict[str, Any]:
|
|
208
|
+
return {"step": step, "element": a.get("element", ""), "mode": a.get("mode", ""), "property": a.get("property", ""),
|
|
209
|
+
"value": "<secret>" if secret else a.get("value", "")}
|
|
210
|
+
|
|
211
|
+
def node_id(self) -> str:
|
|
212
|
+
self.seq += 1
|
|
213
|
+
return f"n{self.seq}"
|
|
214
|
+
|
|
215
|
+
def unsupported(self, step: str, a: Dict[str, Any], reason: str, module: str = "") -> Dict[str, Any]:
|
|
216
|
+
self.counts["unsupported"] += 1
|
|
217
|
+
self.unmapped.append({"step": step, "element": a.get("element", ""), "mode": a.get("mode", ""),
|
|
218
|
+
"property": a.get("property", ""), "value": a.get("value", ""), "reason": reason})
|
|
219
|
+
return {"kind": "unsupported", "id": self.node_id(), "reason": reason, "module": module,
|
|
220
|
+
"tosca": self.anchor(step, a, ENCRYPTED_RE.match(a.get("value") or "") is not None)}
|
|
221
|
+
|
|
222
|
+
def tokens(self, v: str) -> Optional[List[Tuple[str, Optional[str]]]]:
|
|
223
|
+
"""Split '{KEYDOWN[CTRL]}{KEYPRESS[A]}' or '2 {TAB}' into (token, arg) and ('text', value) parts; None if unbalanced."""
|
|
224
|
+
out: List[Tuple[str, Optional[str]]] = []
|
|
225
|
+
i = 0
|
|
226
|
+
while i < len(v):
|
|
227
|
+
if v[i] == "{":
|
|
228
|
+
m = re.match(r"\{([A-Za-z]+)(?:\[((?:[^\[\]]|\[[^\[\]]*\]|\{[^{}]*\})*)\])?\}", v[i:])
|
|
229
|
+
if not m:
|
|
230
|
+
return None
|
|
231
|
+
name, arg = m.group(1).upper(), m.group(2)
|
|
232
|
+
if name in ("PL", "B", "CP", "XL"):
|
|
233
|
+
out.append(("text", m.group(0)))
|
|
234
|
+
else:
|
|
235
|
+
out.append((name, arg))
|
|
236
|
+
i += m.end()
|
|
237
|
+
else:
|
|
238
|
+
j = v.find("{", i)
|
|
239
|
+
j = len(v) if j < 0 else j
|
|
240
|
+
out.append(("text", v[i:j]))
|
|
241
|
+
i = j
|
|
242
|
+
# Merge neighbouring text parts (a reference sits inside text).
|
|
243
|
+
merged: List[Tuple[str, Optional[str]]] = []
|
|
244
|
+
for t in out:
|
|
245
|
+
if t[0] == "text" and merged and merged[-1][0] == "text":
|
|
246
|
+
merged[-1] = ("text", (merged[-1][1] or "") + (t[1] or ""))
|
|
247
|
+
else:
|
|
248
|
+
merged.append(t)
|
|
249
|
+
return merged
|
|
250
|
+
|
|
251
|
+
def set_action(self, step: str, a: Dict[str, Any], target: str, optional: bool) -> List[Dict[str, Any]]:
|
|
252
|
+
raw_v = a.get("value") or ""
|
|
253
|
+
resolved = a.get("value_resolved")
|
|
254
|
+
el_name = a.get("element", "")
|
|
255
|
+
secret = bool(ENCRYPTED_RE.match(resolved or raw_v or ""))
|
|
256
|
+
anchor = self.anchor(step, a, secret)
|
|
257
|
+
base = {"target": target, "tosca": anchor, **({"optional": True} if optional else {})}
|
|
258
|
+
if raw_v in ("{NULL}", ""):
|
|
259
|
+
return []
|
|
260
|
+
if secret or (resolved or raw_v).startswith("$CONFIG:"):
|
|
261
|
+
val, warn = self.value(raw_v, resolved, el_name)
|
|
262
|
+
return [{"kind": "action", "id": self.node_id(), "op": "fill", "value": val, **base}]
|
|
263
|
+
toks = self.tokens(self.pick(raw_v, resolved))
|
|
264
|
+
if toks is None:
|
|
265
|
+
return [self.unsupported(step, a, "value has unbalanced Tosca braces")]
|
|
266
|
+
nodes: List[Dict[str, Any]] = []
|
|
267
|
+
i = 0
|
|
268
|
+
while i < len(toks):
|
|
269
|
+
name, arg = toks[i]
|
|
270
|
+
nid = self.node_id
|
|
271
|
+
if name == "text":
|
|
272
|
+
text = arg or ""
|
|
273
|
+
if text.strip() == "" and len(toks) > 1:
|
|
274
|
+
i += 1
|
|
275
|
+
continue
|
|
276
|
+
val, warn = self.value(text.strip() if len(toks) > 1 else text, None, el_name)
|
|
277
|
+
if warn:
|
|
278
|
+
self.warnings.append(f"{step} / {el_name}: {warn}")
|
|
279
|
+
if a.get("_checkbox") and text.strip().lower() in ("true", "false"):
|
|
280
|
+
nodes.append({"kind": "action", "id": nid(), "op": "check" if text.strip().lower() == "true" else "uncheck", **base})
|
|
281
|
+
else:
|
|
282
|
+
nodes.append({"kind": "action", "id": nid(), "op": "fill", "value": val, **base})
|
|
283
|
+
elif name in CLICKS:
|
|
284
|
+
nodes.append({"kind": "action", "id": nid(), "op": "click", **({"modifiers": CLICKS[name]} if CLICKS[name] else {}), **base})
|
|
285
|
+
elif name in POINTER:
|
|
286
|
+
nodes.append({"kind": "action", "id": nid(), "op": POINTER[name], **base})
|
|
287
|
+
elif name in KEYS:
|
|
288
|
+
nodes.append({"kind": "action", "id": nid(), "op": "press", "key": KEYS[name], **base})
|
|
289
|
+
elif name == "KEY" and arg:
|
|
290
|
+
nodes.append({"kind": "action", "id": nid(), "op": "press", "key": chord(arg), **base})
|
|
291
|
+
elif name == "KEYDOWN" and arg and i + 2 < len(toks) and toks[i + 1][0] == "KEYPRESS" and toks[i + 2][0] == "KEYUP" \
|
|
292
|
+
and (toks[i + 2][1] or "").upper() == arg.upper():
|
|
293
|
+
nodes.append({"kind": "action", "id": nid(), "op": "press", "key": chord(f"{arg}+{toks[i + 1][1] or ''}"), **base})
|
|
294
|
+
i += 3
|
|
295
|
+
continue
|
|
296
|
+
elif name == "KEYPRESS" and arg:
|
|
297
|
+
nodes.append({"kind": "action", "id": nid(), "op": "press", "key": chord(arg), **base})
|
|
298
|
+
elif name in ("SENDKEYS", "TYPE", "TEXTINPUT") and arg is not None:
|
|
299
|
+
val, warn = self.value(arg, None, el_name)
|
|
300
|
+
if warn:
|
|
301
|
+
self.warnings.append(f"{step} / {el_name}: {warn}")
|
|
302
|
+
nodes.append({"kind": "action", "id": nid(), "op": "fill", "value": val, **base})
|
|
303
|
+
elif name == "SELECT" and arg is not None:
|
|
304
|
+
sel = {"index": int(arg) - 1} if arg.isdigit() else {"label": arg}
|
|
305
|
+
nodes.append({"kind": "action", "id": nid(), "op": "select", "option": sel, **base})
|
|
306
|
+
elif name == "WAIT" and arg and arg.isdigit():
|
|
307
|
+
nodes.append({"kind": "wait", "id": nid(), "ms": int(arg), "tosca": anchor})
|
|
308
|
+
elif EXPR_RE.match("{" + name):
|
|
309
|
+
nodes.append({"kind": "action", "id": nid(), "op": "fill", "value": {"expr": "{" + name + (f"[{arg}]" if arg is not None else "") + "}"}, **base})
|
|
310
|
+
self.warnings.append(f"{step} / {el_name}: Tosca expression {{{name}}} needs the target's own code")
|
|
311
|
+
else:
|
|
312
|
+
return [self.unsupported(step, a, f"unknown value token {{{name}}}")]
|
|
313
|
+
i += 1
|
|
314
|
+
return nodes
|
|
315
|
+
|
|
316
|
+
def assert_action(self, step: str, a: Dict[str, Any], target: str, wait: bool) -> Dict[str, Any]:
|
|
317
|
+
prop = (a.get("property") or "").strip()
|
|
318
|
+
raw_v = a.get("value") or ""
|
|
319
|
+
resolved = a.get("value_resolved")
|
|
320
|
+
anchor = self.anchor(step, a, False)
|
|
321
|
+
base = {"kind": "assert", "id": self.node_id(), "target": target, "tosca": anchor, **({"wait": True} if wait else {})}
|
|
322
|
+
key = prop.lower()
|
|
323
|
+
if key in BOOL_PROPS:
|
|
324
|
+
truth = (resolved or raw_v).strip().lower()
|
|
325
|
+
if truth not in ("true", "false"):
|
|
326
|
+
return {**base, "op": "property", "property": prop, "expected": self.value(raw_v, resolved, a.get("element", ""))[0]}
|
|
327
|
+
return {**base, "op": BOOL_PROPS[key][0 if truth == "true" else 1]}
|
|
328
|
+
val = self.pick(raw_v, resolved)
|
|
329
|
+
match = "exact"
|
|
330
|
+
if isinstance(val, str) and (val.startswith("*") or val.endswith("*")):
|
|
331
|
+
match = "contains"
|
|
332
|
+
val = val.strip("*")
|
|
333
|
+
expected, warn = self.value(val, None, a.get("element", ""))
|
|
334
|
+
if warn:
|
|
335
|
+
self.warnings.append(f"{step} / {a.get('element', '')}: {warn}")
|
|
336
|
+
if key == "count":
|
|
337
|
+
return {**base, "op": "count", "expected": expected}
|
|
338
|
+
if key == "value":
|
|
339
|
+
return {**base, "op": "value", "expected": expected, "match": match}
|
|
340
|
+
if key in ("", "innertext", "text", "label"):
|
|
341
|
+
return {**base, "op": "text", "expected": expected, "match": match}
|
|
342
|
+
return {**base, "op": "property", "property": prop, "expected": expected, "match": match}
|
|
343
|
+
|
|
344
|
+
def step_nodes(self, s: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
345
|
+
step, module = s.get("name", ""), s.get("module", "")
|
|
346
|
+
self.counts["steps"] += 1
|
|
347
|
+
out: List[Dict[str, Any]] = []
|
|
348
|
+
if module == "TBox Set Buffer":
|
|
349
|
+
for a in s.get("actions", []):
|
|
350
|
+
var = a.get("explicit_name") or a.get("element") or "buffer"
|
|
351
|
+
val, _ = self.value(a.get("value") or "", a.get("value_resolved"), var)
|
|
352
|
+
self.vars[var] = a.get("value") or ""
|
|
353
|
+
out.append({"kind": "set_var", "id": self.node_id(), "var": var, "value": val, "tosca": self.anchor(step, a, "secret" in val)})
|
|
354
|
+
return out
|
|
355
|
+
if module == "TBox Evaluation Tool":
|
|
356
|
+
return []
|
|
357
|
+
if module.startswith("TBox "):
|
|
358
|
+
for a in s.get("actions", []):
|
|
359
|
+
out.append(self.unsupported(step, a, f"Tosca TBox module '{module}' has no web equivalent; route it to the desktop agent or code it by hand", module))
|
|
360
|
+
return out
|
|
361
|
+
route = self.route_of(self.engines.get(module, ""))
|
|
362
|
+
self.routes[route] = self.routes.get(route, 0) + 1
|
|
363
|
+
for a in s.get("actions", []):
|
|
364
|
+
mode = a.get("mode", "")
|
|
365
|
+
raw = (a.get("locator") or {}).get("raw") or {}
|
|
366
|
+
if str(raw.get("Tag") or "").upper() == "INPUT" and str(raw.get("attributes_type") or "").lower() in ("checkbox", "radio"):
|
|
367
|
+
a = {**a, "_checkbox": True}
|
|
368
|
+
target = self.element(module, a.get("element", ""), raw)
|
|
369
|
+
if mode in ("set", "input", "optionalSet"):
|
|
370
|
+
nodes = self.set_action(step, a, target, mode == "optionalSet")
|
|
371
|
+
self.counts["actions"] += sum(1 for n in nodes if n["kind"] == "action")
|
|
372
|
+
out += nodes
|
|
373
|
+
elif mode in ("verify", "waitFor"):
|
|
374
|
+
self.counts["asserts"] += 1
|
|
375
|
+
out.append(self.assert_action(step, a, target, mode == "waitFor"))
|
|
376
|
+
elif mode == "bufferRead":
|
|
377
|
+
self.counts["stores"] += 1
|
|
378
|
+
var = a.get("value") or a.get("explicit_name") or "value"
|
|
379
|
+
out.append({"kind": "store", "id": self.node_id(), "var": var, "target": target,
|
|
380
|
+
"property": a.get("property") or "InnerText", "tosca": self.anchor(step, a, False)})
|
|
381
|
+
else:
|
|
382
|
+
out.append(self.unsupported(step, a, f"unknown ActionMode '{mode}'"))
|
|
383
|
+
return out
|
|
384
|
+
|
|
385
|
+
# Structure ----------------------------------------------------------------------------------------------------
|
|
386
|
+
def body(self, steps: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
|
387
|
+
root: List[Dict[str, Any]] = []
|
|
388
|
+
stack: List[List[Dict[str, Any]]] = [root]
|
|
389
|
+
ifs: List[Dict[str, Any]] = []
|
|
390
|
+
for s in steps:
|
|
391
|
+
t = s.get("type")
|
|
392
|
+
cur = stack[-1]
|
|
393
|
+
if t == "folder":
|
|
394
|
+
g = {"kind": "group", "id": self.node_id(), "name": s.get("name", ""), "role": folder_role(s.get("name", "")), "body": []}
|
|
395
|
+
cur.append(g)
|
|
396
|
+
stack.append(g["body"])
|
|
397
|
+
elif t == "block_start":
|
|
398
|
+
args = {}
|
|
399
|
+
for k, v in (s.get("parameters") or {}).items():
|
|
400
|
+
args[k] = self.value(v, None, k)[0]
|
|
401
|
+
g = {"kind": "group", "id": self.node_id(), "name": s.get("name", ""), "role": "block", "block": slug(s.get("name", "")), "args": args, "body": []}
|
|
402
|
+
cur.append(g)
|
|
403
|
+
stack.append(g["body"])
|
|
404
|
+
elif t in ("folder_end", "block_end", "then_end", "else_end", "loop_end"):
|
|
405
|
+
if len(stack) > 1:
|
|
406
|
+
stack.pop()
|
|
407
|
+
elif t == "step":
|
|
408
|
+
cur.extend(self.step_nodes(s))
|
|
409
|
+
elif t == "if":
|
|
410
|
+
cond = s.get("condition", "")
|
|
411
|
+
res = s.get("condition_resolved", "")
|
|
412
|
+
node = {"kind": "if", "id": self.node_id(), "name": s.get("name", ""), "condition": {"tosca": cond, "resolved": res}, "then": [], "else": []}
|
|
413
|
+
const = constant_condition(res)
|
|
414
|
+
if const is not None:
|
|
415
|
+
node["condition"]["constant"] = const
|
|
416
|
+
cur.append(node)
|
|
417
|
+
ifs.append(node)
|
|
418
|
+
elif t in ("then_start", "else_start", "loop_start") and ifs:
|
|
419
|
+
key = {"then_start": "then", "else_start": "else", "loop_start": "loop"}[t]
|
|
420
|
+
ifs[-1].setdefault(key, [])
|
|
421
|
+
if key == "loop":
|
|
422
|
+
ifs[-1]["kind"] = "loop"
|
|
423
|
+
stack.append(ifs[-1][key])
|
|
424
|
+
elif t == "if_end" and ifs:
|
|
425
|
+
ifs.pop()
|
|
426
|
+
return root
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def folder_role(name: str) -> str:
|
|
430
|
+
n = (name or "").strip().lower()
|
|
431
|
+
if n.startswith("precondition") or n in ("setup", "pre-condition"):
|
|
432
|
+
return "before"
|
|
433
|
+
if n.startswith("postcondition") or n in ("teardown", "cleanup", "post-condition"):
|
|
434
|
+
return "after"
|
|
435
|
+
return "folder"
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def constant_condition(resolved: str) -> Optional[bool]:
|
|
439
|
+
m = re.match(r'^\s*"?([^"={}]*)"?\s*(==|!=)\s*"?([^"={}]*)"?\s*$', resolved or "")
|
|
440
|
+
if not m:
|
|
441
|
+
return None
|
|
442
|
+
left, op, right = m.group(1).strip(), m.group(2), m.group(3).strip()
|
|
443
|
+
return (left == right) if op == "==" else (left != right)
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def chord(arg: str) -> str:
|
|
447
|
+
parts = [p.strip() for p in re.split(r"\+", arg) if p.strip()]
|
|
448
|
+
out = []
|
|
449
|
+
for p in parts:
|
|
450
|
+
u = p.upper()
|
|
451
|
+
if u in MODIFIERS:
|
|
452
|
+
out.append(MODIFIERS[u])
|
|
453
|
+
elif u in KEYS:
|
|
454
|
+
out.append(KEYS[u])
|
|
455
|
+
elif len(p) == 1:
|
|
456
|
+
out.append(p.lower())
|
|
457
|
+
else:
|
|
458
|
+
out.append(p[:1].upper() + p[1:].lower())
|
|
459
|
+
return "+".join(out)
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def build(manifest: Dict[str, Any], case: Dict[str, Any], engines: Dict[str, str], route_of) -> Dict[str, Any]:
|
|
463
|
+
"""One test case's NTIR document."""
|
|
464
|
+
b = Builder(manifest, engines, route_of)
|
|
465
|
+
body = b.body(manifest.get("steps") or [])
|
|
466
|
+
meta = manifest.get("meta", {})
|
|
467
|
+
for item in meta.get("unmapped") or []: # what ToscaTSU itself could not map stays visible even if NTIR could
|
|
468
|
+
if not any(u["step"] == item.get("step") and u["element"] == item.get("element") and u["value"] == item.get("value") for u in b.unmapped):
|
|
469
|
+
b.warnings.append(f"ToscaTSU: {item.get('step', '')} / {item.get('element', '')}: {item.get('reason', '')}")
|
|
470
|
+
routes = sorted(r for r in b.routes)
|
|
471
|
+
return {
|
|
472
|
+
"ntir_version": NTIR_VERSION,
|
|
473
|
+
"source": {"tool": "tosca", "file": meta.get("source_file", ""), "project": meta.get("project", ""),
|
|
474
|
+
"test_case": {"name": case.get("name") or meta.get("test_name", ""), "surrogate": case.get("surrogate") or meta.get("surrogate", ""),
|
|
475
|
+
"folders": case.get("folders", []), "area": case.get("area", []), "suites": case.get("suites", []),
|
|
476
|
+
"id": case.get("id", "")}},
|
|
477
|
+
"config": {"base_url": meta.get("base_url", ""), "urls": meta.get("all_urls", []), "env": sorted(b.env.values(), key=lambda e: e["name"])},
|
|
478
|
+
"route": routes[0] if len(routes) == 1 else ("mixed" if routes else "web"),
|
|
479
|
+
"routes": {r: b.routes[r] for r in routes},
|
|
480
|
+
"pages": sorted(b.pages.values(), key=lambda p: p["id"]),
|
|
481
|
+
"data": {"buffers": dict(manifest.get("test_data") or {})},
|
|
482
|
+
"body": body,
|
|
483
|
+
"report": {"counts": b.counts, "unmapped": b.unmapped, "warnings": sorted(set(b.warnings))},
|
|
484
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""A test case's NTIR as plain text: what the Tosca agent and a person read in place of the binary .tsu.
|
|
2
|
+
|
|
3
|
+
Every action line carries its node id ([n12]) so the converted test can name the Tosca step it implements, and the
|
|
4
|
+
fidelity check can match them. Values from the .tsu are quoted as data; secrets show only their variable's name.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
from typing import Any, Dict, List
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def value_text(v: Any) -> str:
|
|
13
|
+
if not isinstance(v, dict):
|
|
14
|
+
return json.dumps(v)
|
|
15
|
+
if "literal" in v:
|
|
16
|
+
return json.dumps(v["literal"], ensure_ascii=False)
|
|
17
|
+
if "env" in v:
|
|
18
|
+
return f"env {v['env']}" + (" (secret)" if v.get("secret") else "")
|
|
19
|
+
if "var" in v:
|
|
20
|
+
return f"variable {v['var']}"
|
|
21
|
+
if "param" in v:
|
|
22
|
+
return f"parameter {v['param']}"
|
|
23
|
+
if "data" in v:
|
|
24
|
+
return f"test data {v['data']}"
|
|
25
|
+
if "expr" in v:
|
|
26
|
+
return f"Tosca expression {json.dumps(v['expr'], ensure_ascii=False)}"
|
|
27
|
+
if "concat" in v:
|
|
28
|
+
return " + ".join(value_text(p) for p in v["concat"])
|
|
29
|
+
return json.dumps(v, ensure_ascii=False)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def locator_text(loc: Dict[str, Any]) -> str:
|
|
33
|
+
s = loc["strategy"]
|
|
34
|
+
if s == "role":
|
|
35
|
+
t = f"role={loc['role']} name={json.dumps(loc['name'], ensure_ascii=False)}"
|
|
36
|
+
elif s in ("testid", "attr"):
|
|
37
|
+
t = f"[{loc['attr']}={json.dumps(loc['value'], ensure_ascii=False)}]"
|
|
38
|
+
else:
|
|
39
|
+
t = f"{s}={json.dumps(loc['value'], ensure_ascii=False)}"
|
|
40
|
+
return t + (" (fragile)" if loc.get("fragile") else "")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def node_lines(n: Dict[str, Any], depth: int) -> List[str]:
|
|
44
|
+
pad = " " * depth
|
|
45
|
+
k = n["kind"]
|
|
46
|
+
tag = f"[{n['id']}] " if "id" in n else ""
|
|
47
|
+
if k == "group":
|
|
48
|
+
head = {"before": "Before (precondition)", "after": "After (postcondition)", "block": "Reusable block"}.get(n.get("role", ""), "Folder")
|
|
49
|
+
args = ""
|
|
50
|
+
if n.get("args"):
|
|
51
|
+
args = " with " + ", ".join(f"{a}={value_text(v)}" for a, v in n["args"].items())
|
|
52
|
+
out = [f"{pad}- {head}: {n['name']}{args}"]
|
|
53
|
+
for c in n["body"]:
|
|
54
|
+
out += node_lines(c, depth + 1)
|
|
55
|
+
return out
|
|
56
|
+
if k in ("if", "loop"):
|
|
57
|
+
c = n["condition"]
|
|
58
|
+
const = f" (always {'true' if c['constant'] else 'false'} with these values)" if "constant" in c else ""
|
|
59
|
+
out = [f"{pad}- {tag}{'If' if k == 'if' else 'Loop'} {n['name']}: {c.get('tosca', '')}{const}"]
|
|
60
|
+
for branch in ("then", "else", "loop"):
|
|
61
|
+
if n.get(branch):
|
|
62
|
+
out.append(f"{pad} {branch.capitalize()}:")
|
|
63
|
+
for ch in n[branch]:
|
|
64
|
+
out += node_lines(ch, depth + 2)
|
|
65
|
+
return out
|
|
66
|
+
t = n.get("tosca", {})
|
|
67
|
+
where = f" (Tosca step \"{t.get('step', '')}\", {t.get('mode', '')})" if t else ""
|
|
68
|
+
if k == "action":
|
|
69
|
+
extra = ""
|
|
70
|
+
if "value" in n:
|
|
71
|
+
extra = " " + value_text(n["value"])
|
|
72
|
+
if "key" in n:
|
|
73
|
+
extra = f" {n['key']}"
|
|
74
|
+
if "option" in n:
|
|
75
|
+
extra = " " + json.dumps(n["option"])
|
|
76
|
+
if n.get("modifiers"):
|
|
77
|
+
extra += " " + json.dumps(n["modifiers"])
|
|
78
|
+
opt = " (optional: may be absent)" if n.get("optional") else ""
|
|
79
|
+
return [f"{pad}- {tag}{n['op']} {n['target']}{extra}{opt}{where}"]
|
|
80
|
+
if k == "assert":
|
|
81
|
+
exp = f" {n.get('match', 'exact')} {value_text(n['expected'])}" if "expected" in n else ""
|
|
82
|
+
w = " (wait until)" if n.get("wait") else ""
|
|
83
|
+
prop = f" {n['property']}" if n.get("property") else ""
|
|
84
|
+
return [f"{pad}- {tag}assert {n['op']}{prop} {n['target']}{exp}{w}{where}"]
|
|
85
|
+
if k == "store":
|
|
86
|
+
return [f"{pad}- {tag}store {n['target']} {n['property']} into variable {n['var']}{where}"]
|
|
87
|
+
if k == "set_var":
|
|
88
|
+
return [f"{pad}- {tag}set variable {n['var']} = {value_text(n['value'])}{where}"]
|
|
89
|
+
if k == "wait":
|
|
90
|
+
return [f"{pad}- {tag}wait {n['ms']} ms{where}"]
|
|
91
|
+
if k == "unsupported":
|
|
92
|
+
return [f"{pad}- {tag}NOT CONVERTIBLE: {n['reason']}{where}"]
|
|
93
|
+
return [f"{pad}- {tag}{k}"]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def render(doc: Dict[str, Any]) -> str:
|
|
97
|
+
tc = doc["source"]["test_case"]
|
|
98
|
+
lines = [f"# Tosca test case: {tc['name']}", ""]
|
|
99
|
+
if tc.get("folders"):
|
|
100
|
+
lines.append(f"Folder: {' / '.join(tc['folders'])}")
|
|
101
|
+
if tc.get("suites"):
|
|
102
|
+
lines.append(f"Tosca execution lists (suites) that run it: {', '.join(tc['suites'])}")
|
|
103
|
+
lines.append(f"Route: {doc['route']}" + (f" (steps by route: {doc['routes']})" if doc["route"] == "mixed" else ""))
|
|
104
|
+
if doc["config"].get("base_url"):
|
|
105
|
+
lines.append(f"Recorded base URL: {doc['config']['base_url']}")
|
|
106
|
+
lines += ["", "## Steps", ""]
|
|
107
|
+
for n in doc["body"]:
|
|
108
|
+
lines += node_lines(n, 0)
|
|
109
|
+
lines += ["", "## Pages and elements (locators best first, as Tosca recorded them)", ""]
|
|
110
|
+
for p in doc["pages"]:
|
|
111
|
+
lines.append(f"- {p['id']}: \"{p['name']}\" (engine {p['engine'] or 'unknown'}, route {p['route']})")
|
|
112
|
+
for e in p["elements"]:
|
|
113
|
+
scope = f" inside {' > '.join(e['scope'])}" if e.get("scope") else ""
|
|
114
|
+
nth = f" nth={e['nth']}" if "nth" in e else ""
|
|
115
|
+
locs = "; ".join(locator_text(l) for l in e["locators"][:4]) or "no locator recorded"
|
|
116
|
+
lines.append(f" - {p['id']}.{e['id']} \"{e['name']}\"{scope}{nth}: {locs}")
|
|
117
|
+
if doc["config"]["env"]:
|
|
118
|
+
lines += ["", "## Environment variables the test needs (values are never in the .tsu export)", ""]
|
|
119
|
+
for e in doc["config"]["env"]:
|
|
120
|
+
lines.append(f"- {e['name']}{' (secret)' if e['secret'] else ''}: from {e['from']}")
|
|
121
|
+
rep = doc["report"]
|
|
122
|
+
if rep["unmapped"] or rep["warnings"]:
|
|
123
|
+
lines += ["", "## Needs attention", ""]
|
|
124
|
+
for u in rep["unmapped"]:
|
|
125
|
+
lines.append(f"- not convertible: {u['step']} / {u['element']}: {u['reason']}")
|
|
126
|
+
for w in rep["warnings"]:
|
|
127
|
+
lines.append(f"- {w}")
|
|
128
|
+
return "\n".join(lines) + "\n"
|