@orion-qa/orion 3.4.1 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/.claude/agents/change-agent.md +1 -1
  2. package/.claude/agents/requirement-analyst.md +1 -1
  3. package/.claude/agents/test-reporter.md +1 -1
  4. package/.claude/skills/appium/templates/project-java/src/test/java/automation/pageObjects/BaseScreen.java +36 -2
  5. package/.claude/skills/appium/templates/project-java/src/test/java/automation/tests/unit/UtilsTest.java +10 -0
  6. package/.claude/skills/appium/templates/project-java/src/test/java/automation/utils/AutomationError.java +21 -0
  7. package/.claude/skills/automation-implementation/SKILL.md +1 -1
  8. package/.claude/skills/automation-implementation/references/patterns.md +14 -0
  9. package/.claude/skills/change-management/SKILL.md +1 -1
  10. package/.claude/skills/code-review/SKILL.md +1 -1
  11. package/.claude/skills/code-review/references/pattern-rules.md +4 -0
  12. package/.claude/skills/documentation/SKILL.md +2 -1
  13. package/.claude/skills/execution/SKILL.md +1 -0
  14. package/.claude/skills/orion/SKILL.md +6 -3
  15. package/.claude/skills/orion/references/conversation.md +1 -1
  16. package/.claude/skills/orion/references/project-context-files.md +3 -1
  17. package/.claude/skills/orion/references/setup-card.md +2 -1
  18. package/.claude/skills/orion/scripts/browser_setup.mjs +4 -4
  19. package/.claude/skills/orion/scripts/case_check.mjs +69 -0
  20. package/.claude/skills/orion/scripts/cases_coverage.py +179 -0
  21. package/.claude/skills/orion/scripts/cases_export.py +3 -0
  22. package/.claude/skills/orion/scripts/cases_model.py +256 -0
  23. package/.claude/skills/orion/scripts/context_guard.mjs +172 -0
  24. package/.claude/skills/orion/scripts/graph.mjs +112 -22
  25. package/.claude/skills/orion/scripts/lib/scan.mjs +8 -2
  26. package/.claude/skills/orion/scripts/report_make.mjs +15 -11
  27. package/.claude/skills/orion/scripts/run_state.mjs +4 -0
  28. package/.claude/skills/orion/scripts/screen_map.mjs +392 -0
  29. package/.claude/skills/orion/scripts/suite_check.mjs +1 -1
  30. package/.claude/skills/playwright/templates/dotnet/PageObjects/BasePage.cs +46 -0
  31. package/.claude/skills/playwright/templates/dotnet/Tests/Unit/UtilsTests.cs +10 -0
  32. package/.claude/skills/playwright/templates/dotnet/Utils/AutomationError.cs +19 -1
  33. package/.claude/skills/playwright/templates/javascript/pageObjects/basePage.js +52 -0
  34. package/.claude/skills/playwright/templates/javascript/reporters/summaryReporter.js +18 -9
  35. package/.claude/skills/playwright/templates/javascript/tests/unit/basePage.test.js +51 -0
  36. package/.claude/skills/playwright/templates/javascript/utils/errors.js +9 -2
  37. package/.claude/skills/playwright/templates/project/pageObjects/basePage.ts +54 -1
  38. package/.claude/skills/playwright/templates/project/reporters/summaryReporter.ts +18 -9
  39. package/.claude/skills/playwright/templates/project/tests/unit/basePage.test.ts +52 -0
  40. package/.claude/skills/playwright/templates/project/utils/errors.ts +12 -2
  41. package/.claude/skills/playwright/templates/python/page_objects/base_page.py +43 -0
  42. package/.claude/skills/playwright/templates/python/tests/unit/test_fail_fast_helpers.py +57 -0
  43. package/.claude/skills/playwright/templates/python/utils/errors.py +7 -3
  44. package/.claude/skills/requests/templates/python-pytest/src/services/api_client.py +11 -1
  45. package/.claude/skills/requests/templates/python-pytest/tests/unit/test_api_client.py +16 -0
  46. package/.claude/skills/requirement-analysis/references/test-case-import.md +9 -1
  47. package/.claude/skills/requirement-analysis/scripts/tm.py +422 -2
  48. package/.claude/skills/rest-assured/templates/java-testng/src/test/java/automation/config/Flags.java +19 -0
  49. package/.claude/skills/rest-assured/templates/java-testng/src/test/java/automation/services/ApiSpec.java +10 -3
  50. package/.claude/skills/selenium/templates/csharp-nunit/PageObjects/BasePage.cs +89 -11
  51. package/.claude/skills/selenium/templates/csharp-nunit/Tests/Unit/UtilsTests.cs +10 -0
  52. package/.claude/skills/selenium/templates/csharp-nunit/Utils/AutomationError.cs +19 -1
  53. package/.claude/skills/selenium/templates/java-testng/src/test/java/automation/pageObjects/BasePage.java +65 -8
  54. package/.claude/skills/selenium/templates/java-testng/src/test/java/automation/tests/unit/UtilsTest.java +10 -0
  55. package/.claude/skills/selenium/templates/java-testng/src/test/java/automation/utils/AutomationError.java +21 -0
  56. package/.claude/skills/selenium/templates/python-pytest/page_objects/base_page.py +70 -11
  57. package/.claude/skills/selenium/templates/python-pytest/tests/unit/test_fail_fast_helpers.py +43 -0
  58. package/.claude/skills/selenium/templates/python-pytest/utils/errors.py +7 -3
  59. package/.claude/skills/test-design/SKILL.md +1 -1
  60. package/.claude/skills/test-reporting/SKILL.md +1 -0
  61. package/.claude/skills/ui-observation/SKILL.md +4 -1
  62. package/.claude-plugin/plugin.json +1 -1
  63. package/.cursor/rules/orion-quiet.mdc +13 -0
  64. package/AGENTS.md +1 -1
  65. package/README.md +2 -2
  66. package/bin/orion.mjs +5 -1
  67. package/hosts/gemini-extension/gemini-extension.json +1 -1
  68. package/package.json +2 -1
@@ -14,7 +14,8 @@ ID, Title, Preconditions, Steps, Expected, Priority, Requirement, Data, Postcond
14
14
  python tm.py xray-import-junit --file results.xml --project CALC [--test-plan CALC-12] --approved D-008 --approver @handle
15
15
 
16
16
  Settings: TESTRAIL_URL, TESTRAIL_USER, TESTRAIL_API_KEY · XRAY_CLIENT_ID, XRAY_CLIENT_SECRET,
17
- XRAY_BASE_URL (default https://xray.cloud.getxray.app). Environment variables win; `--env <path>` points at the test
17
+ XRAY_BASE_URL (default https://xray.cloud.getxray.app) · ZEPHYR_TOKEN, ZEPHYR_URL ·
18
+ ADO_ORG or ADO_URL, ADO_PROJECT, ADO_TM_PAT (Azure Test Plans). Environment variables win; `--env <path>` points at the test
18
19
  project's .env (default ./.env; `NAME=value`, quotes around a value are removed). On Windows run it with `py` instead of
19
20
  `python3`. The approval id is checked for its form only (`D-` and digits): the decision record itself is the orchestrator's
20
21
  check, before it passes the id on.
@@ -25,11 +26,13 @@ import argparse
25
26
  import base64
26
27
  import csv
27
28
  import datetime
29
+ import hashlib
28
30
  import io
29
31
  import json
30
32
  import os
31
33
  import re
32
34
  import sys
35
+ import time
33
36
  import urllib.error
34
37
  import urllib.request
35
38
  import xml.etree.ElementTree as ET
@@ -479,6 +482,416 @@ def xlsx_to_csv(args) -> None:
479
482
  out.writerow(row)
480
483
 
481
484
 
485
+ # ---------- Pushing test cases (orion-cases/1 → a test-management tool). Dry run unless approved; never deletes. ----------
486
+
487
+ def _load_json(path: str, default):
488
+ """A JSON file, or `default` when it doesn't exist yet."""
489
+ if not os.path.exists(path):
490
+ return default
491
+ with open(path, encoding="utf-8") as f:
492
+ return json.load(f)
493
+
494
+
495
+ def _save_json(path: str, value) -> None:
496
+ """Write JSON, creating its folder."""
497
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
498
+ with open(path, "w", encoding="utf-8") as f:
499
+ json.dump(value, f, indent=1, ensure_ascii=False)
500
+
501
+
502
+ def _where(url: str) -> str:
503
+ """An address without user info, query or trailing slash: safe to store in the push map."""
504
+ parts = urllib.request.urlparse(url or "")
505
+ return f"{parts.scheme}://{parts.hostname or ''}{':' + str(parts.port) if parts.port else ''}{parts.path}".rstrip("/") if parts.scheme else ""
506
+
507
+
508
+ CASE_CONTENT = ["title", "ac", "type", "priority", "preconditions", "steps", "expected", "data", "postconditions"]
509
+
510
+
511
+ def _content_hash(case: dict) -> str:
512
+ """What a case says, hashed here (a file's own fingerprint may be missing or stale)."""
513
+ return hashlib.sha1(json.dumps({k: case.get(k) for k in CASE_CONTENT}, sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest()[:12]
514
+
515
+
516
+ def _case_ref(case: dict) -> str:
517
+ """The case's name in the push map: story and id, since every story numbers its cases from TS-1."""
518
+ return f"{case['story']}/{case['id']}" if case.get("story") else case["id"]
519
+
520
+
521
+ def _steps_text(case: dict) -> tuple:
522
+ """(numbered steps, the case's expected result) as plain text, for tools without separate step fields."""
523
+ steps = "\n".join(f"{i}. {s['action']}" for i, s in enumerate(case.get("steps", []), 1))
524
+ expected = case.get("expected") or "\n".join(s["expected"] for s in case.get("steps", []) if s.get("expected"))
525
+ return steps, expected
526
+
527
+
528
+ class TestRailCases:
529
+ """TestRail API v2: add_case/<section>, update_case/<case>, get_case/<case> (updated_on is the change stamp)."""
530
+
531
+ name = "testrail"
532
+
533
+ def __init__(self, args):
534
+ self.section = args.section
535
+ self.template = args.template_id
536
+ self._priorities = None
537
+
538
+ def target(self) -> str:
539
+ """Which TestRail this is (its address, never a credential)."""
540
+ return _where(os.environ.get("TESTRAIL_URL", ""))
541
+
542
+ def _call(self, method: str, path: str, body: dict = None):
543
+ """One API v2 call with HTTP Basic (user and API key from the environment)."""
544
+ base = setting("TESTRAIL_URL").rstrip("/")
545
+ token = base64.b64encode(f"{setting('TESTRAIL_USER')}:{setting('TESTRAIL_API_KEY')}".encode()).decode()
546
+ _, out = http(method, f"{base}/index.php?/api/v2/{path}",
547
+ {"Authorization": f"Basic {token}", "Content-Type": "application/json"},
548
+ json.dumps(body).encode() if body is not None else None, shown=f"/api/v2/{path}")
549
+ return out
550
+
551
+ def _priority_id(self, name: str):
552
+ """The project's priority id for High/Medium/Low (by short name), or None to keep TestRail's default."""
553
+ if self._priorities is None:
554
+ self._priorities = {str(n).split(" - ")[-1].lower(): i for i, n in testrail_priorities().items()}
555
+ return self._priorities.get((name or "").lower())
556
+
557
+ def payload(self, case: dict) -> dict:
558
+ """The case as TestRail's fields: steps separated (step and expected), references with story and criteria."""
559
+ steps, expected = _steps_text(case)
560
+ body = {"title": case["title"],
561
+ "refs": ", ".join(x for x in [case.get("story", "")] + case.get("ac", []) if x),
562
+ "custom_preconds": "\n".join(x for x in (case.get("preconditions", ""), case.get("data") and f"Test data: {case['data']}") if x),
563
+ "custom_steps_separated": [{"content": s["action"], "expected": s.get("expected", "")} for s in case.get("steps", [])],
564
+ "custom_expected": expected}
565
+ if self.template:
566
+ body["template_id"] = int(self.template)
567
+ pid = self._priority_id(case.get("priority"))
568
+ if pid:
569
+ body["priority_id"] = pid
570
+ return body
571
+
572
+ def create(self, case: dict) -> tuple:
573
+ """Add the case to the section; returns (key, change stamp)."""
574
+ if not self.section:
575
+ raise ToolError("Push", "testrail", "needs --section <id> (the section new cases go into)", 2)
576
+ out = self._call("POST", f"add_case/{self.section}", self.payload(case))
577
+ return f"C{out['id']}", str(out.get("updated_on", ""))
578
+
579
+ def read(self, key: str) -> tuple:
580
+ """(the remote case, its change stamp)."""
581
+ out = self._call("GET", f"get_case/{key.lstrip('C')}")
582
+ return out, str(out.get("updated_on", ""))
583
+
584
+ def update(self, key: str, case: dict) -> str:
585
+ """Update the case's fields; returns the new change stamp."""
586
+ out = self._call("POST", f"update_case/{key.lstrip('C')}", self.payload(case))
587
+ return str(out.get("updated_on", ""))
588
+
589
+
590
+ class ZephyrScaleCases:
591
+ """Zephyr Scale Cloud API v2 (Bearer token): POST /testcases, GET/PUT /testcases/<key>, steps through
592
+ POST /testcases/<key>/teststeps (mode OVERWRITE). The API gives no change stamp, so the stamp is a hash of the
593
+ fields Orion writes (name, objective, precondition, steps): an edit by a person changes it."""
594
+
595
+ name = "zephyr"
596
+ PRIORITY = {"high": "High", "medium": "Normal", "low": "Low"}
597
+
598
+ def __init__(self, args):
599
+ self.project = args.project_key
600
+ self.folder = args.folder
601
+
602
+ def target(self) -> str:
603
+ """Which Zephyr and project this is."""
604
+ return f"{_where(os.environ.get('ZEPHYR_URL') or 'https://api.zephyrscale.smartbear.com/v2')} {self.project or ''}".strip()
605
+
606
+ def _call(self, method: str, path: str, body=None):
607
+ """One API call; base URL from ZEPHYR_URL (default the Cloud API), token from ZEPHYR_TOKEN."""
608
+ base = (os.environ.get("ZEPHYR_URL") or "https://api.zephyrscale.smartbear.com/v2").rstrip("/")
609
+ _, out = http(method, f"{base}{path}", {"Authorization": f"Bearer {setting('ZEPHYR_TOKEN')}",
610
+ "Content-Type": "application/json"},
611
+ json.dumps(body).encode() if body is not None else None, shown=f"/v2{path}")
612
+ return out
613
+
614
+ def _fields(self, case: dict) -> dict:
615
+ """Name, objective (what it covers and the expected result), precondition with the test data, labels."""
616
+ _, expected = _steps_text(case)
617
+ covers = ", ".join(x for x in [case.get("story", "")] + case.get("ac", []) if x)
618
+ return {"name": case["title"],
619
+ "objective": "\n".join(x for x in (f"Covers {covers}" if covers else "", f"Expected: {expected}" if expected else "") if x),
620
+ "precondition": "\n".join(x for x in (case.get("preconditions", ""), case.get("data") and f"Test data: {case['data']}") if x),
621
+ "labels": case.get("labels", [])}
622
+
623
+ def _steps(self, key: str, case: dict) -> None:
624
+ """Replace the case's steps (action, data, expected)."""
625
+ self._call("POST", f"/testcases/{key}/teststeps", {"mode": "OVERWRITE", "items": [
626
+ {"inline": {"description": s["action"], "testData": "", "expectedResult": s.get("expected", "")}} for s in case.get("steps", [])]})
627
+
628
+ def _stamp(self, remote: dict, steps: list) -> str:
629
+ """A hash of the fields Orion writes, as the tool holds them now."""
630
+ keep = {k: remote.get(k) for k in ("name", "objective", "precondition")}
631
+ keep["steps"] = [(x.get("inline") or {}).get("description") for x in steps]
632
+ return hashlib.sha1(json.dumps(keep, sort_keys=True).encode()).hexdigest()[:12]
633
+
634
+ def create(self, case: dict) -> tuple:
635
+ """Create the case and its steps; returns (key, stamp)."""
636
+ if not self.project:
637
+ raise ToolError("Push", "zephyr", "needs --project-key <KEY> (the Jira project the cases belong to)", 2)
638
+ body = {"projectKey": self.project, "priorityName": self.PRIORITY.get((case.get("priority") or "").lower(), "Normal"),
639
+ **self._fields(case)}
640
+ if self.folder:
641
+ body["folderId"] = int(self.folder)
642
+ key = self._call("POST", "/testcases", body)["key"]
643
+ self._steps(key, case)
644
+ return key, self.read(key)[1]
645
+
646
+ def read(self, key: str) -> tuple:
647
+ """(the remote case with its steps, its stamp)."""
648
+ remote = self._call("GET", f"/testcases/{key}")
649
+ steps = (self._call("GET", f"/testcases/{key}/teststeps") or {}).get("values", [])
650
+ return {**remote, "steps": steps}, self._stamp(remote, steps)
651
+
652
+ def update(self, key: str, case: dict) -> str:
653
+ """Update the fields on the whole case (Zephyr's PUT needs it), then replace the steps; returns the new stamp."""
654
+ remote = self._call("GET", f"/testcases/{key}")
655
+ self._call("PUT", f"/testcases/{key}", {**remote, **self._fields(case)})
656
+ self._steps(key, case)
657
+ return self.read(key)[1]
658
+
659
+
660
+ class XrayCloudCases:
661
+ """Xray Cloud: create through the bulk test import (a job, polled a bounded number of times), steps updated through
662
+ GraphQL (removeAllTestSteps, addTestStep), read through getTest. The key is `<JIRA-KEY>#<issueId>`; the stamp is a
663
+ hash of the summary, Jira's `updated` and the steps. The summary is a Jira field: a changed title is reported, not
664
+ written (that needs Jira write access, a separate approval)."""
665
+
666
+ name = "xray"
667
+
668
+ def __init__(self, args):
669
+ self.project = args.project_key
670
+ self._auth = None
671
+
672
+ def target(self) -> str:
673
+ """Which Xray and project this is."""
674
+ return f"{_where(os.environ.get('XRAY_BASE_URL') or 'https://xray.cloud.getxray.app')} {self.project or ''}".strip()
675
+
676
+ def _token(self) -> tuple:
677
+ """(base URL, bearer token), fetched once."""
678
+ if not self._auth:
679
+ self._auth = xray_token()
680
+ return self._auth
681
+
682
+ def _call(self, method: str, path: str, body=None):
683
+ """One REST call to Xray Cloud."""
684
+ base, token = self._token()
685
+ _, out = http(method, f"{base}{path}", {"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
686
+ json.dumps(body).encode() if body is not None else None, shown=path)
687
+ return out
688
+
689
+ def _gql(self, query: str, variables: dict):
690
+ """One GraphQL call; GraphQL errors fail naming the first message."""
691
+ out = self._call("POST", "/api/v2/graphql", {"query": query, "variables": variables}) or {}
692
+ if out.get("errors"):
693
+ raise ToolError("Call POST", "/api/v2/graphql", out["errors"][0].get("message", "error")[:200])
694
+ return out.get("data") or {}
695
+
696
+ @staticmethod
697
+ def _steps(case: dict) -> list:
698
+ """Steps as Xray's action, data, result."""
699
+ return [{"action": s["action"], "data": "", "result": s.get("expected", "")} for s in case.get("steps", [])]
700
+
701
+ def create(self, case: dict) -> tuple:
702
+ """Import one Manual test and wait (at most 20 checks, 1 s apart) for its key."""
703
+ if not self.project:
704
+ raise ToolError("Push", "xray", "needs --project-key <KEY> (the Jira project of the tests)", 2)
705
+ _, expected = _steps_text(case)
706
+ covers = ", ".join(x for x in [case.get("story", "")] + case.get("ac", []) if x)
707
+ desc = "\n".join(x for x in (case.get("preconditions") and f"Preconditions: {case['preconditions']}",
708
+ case.get("data") and f"Test data: {case['data']}", covers and f"Covers: {covers}",
709
+ expected and f"Expected: {expected}") if x)
710
+ job = self._call("POST", "/api/v2/import/test/bulk", [{"testtype": "Manual", "steps": self._steps(case),
711
+ "fields": {"project": {"key": self.project}, "summary": case["title"], "description": desc}}])["jobId"]
712
+ for _ in range(20):
713
+ st = self._call("GET", f"/api/v2/import/test/bulk/{job}/status") or {}
714
+ if st.get("status") == "successful":
715
+ res = st.get("result") or {}
716
+ if res.get("errors") or not res.get("issues"):
717
+ raise ToolError("Push", f"xray job {job}", f"the import reported errors: {str(res.get('errors'))[:200]}")
718
+ issue = res["issues"][0]
719
+ key = f"{issue['key']}#{issue['id']}"
720
+ return key, self.read(key)[1]
721
+ if st.get("status") in ("failed", "unsuccessful"):
722
+ raise ToolError("Push", f"xray job {job}", f"failed: {str(st)[:200]}")
723
+ time.sleep(1)
724
+ raise ToolError("Push", f"xray job {job}", "not finished after 20 checks; look at the job in Xray before pushing again")
725
+
726
+ def read(self, key: str) -> tuple:
727
+ """(the remote test, its stamp)."""
728
+ issue_id = key.split("#")[-1]
729
+ t = self._gql('query($issueId: String!) { getTest(issueId: $issueId) { issueId steps { action data result } '
730
+ 'jira(fields: ["key", "summary", "updated"]) } }', {"issueId": issue_id}).get("getTest")
731
+ if not t:
732
+ raise ToolError("Read", f"xray test {key}", "not found")
733
+ j = t.get("jira") or {}
734
+ stamp = hashlib.sha1(json.dumps([j.get("summary"), j.get("updated"), t.get("steps")], sort_keys=True).encode()).hexdigest()[:12]
735
+ return t, stamp
736
+
737
+ def update(self, key: str, case: dict) -> str:
738
+ """Replace the steps; a changed title is reported (it is a Jira field). Returns the new stamp."""
739
+ issue_id = key.split("#")[-1]
740
+ remote, _ = self.read(key)
741
+ self._gql('mutation($issueId: String!) { removeAllTestSteps(issueId: $issueId) }', {"issueId": issue_id})
742
+ for step in self._steps(case):
743
+ self._gql('mutation($issueId: String!, $step: CreateStepInput!) { addTestStep(issueId: $issueId, step: $step) { id } }',
744
+ {"issueId": issue_id, "step": step})
745
+ if (remote.get("jira") or {}).get("summary") != case["title"]:
746
+ print(f" note: {key.split('#')[0]} title differs from the case; change the summary in Jira if wanted")
747
+ return self.read(key)[1]
748
+
749
+
750
+ class AzureTestCases:
751
+ """Azure Test Plans: a test case is a `Test Case` work item (REST wit/workitems, JSON Patch). Steps go in
752
+ Microsoft.VSTS.TCM.Steps as Azure's steps XML; the stamp is the work item's `rev`, and every update also sends
753
+ `op: test /rev` so a person's edit between the read and the write is refused by Azure itself. With --plan and
754
+ --suite a new case is added to that suite. Auth: a PAT (Work Items and Test Management, read and write) as HTTP
755
+ Basic with an empty user."""
756
+
757
+ name = "azure"
758
+ PRIORITY = {"high": 1, "medium": 2, "low": 3}
759
+
760
+ def __init__(self, args):
761
+ self.plan, self.suite = args.plan, args.suite
762
+ if bool(self.plan) != bool(self.suite):
763
+ raise ToolError("Push", "azure", "--plan and --suite go together (the suite the new cases join)", 2)
764
+
765
+ def target(self) -> str:
766
+ """Which organization and project this is."""
767
+ base = os.environ.get("ADO_URL") or f"https://dev.azure.com/{os.environ.get('ADO_ORG', '')}"
768
+ return f"{_where(base)} {os.environ.get('ADO_PROJECT', '')}".strip()
769
+
770
+ def _call(self, method: str, path: str, body=None, patch: bool = False):
771
+ """One REST call under <ADO_URL>/<ADO_PROJECT>/_apis (api-version 7.1)."""
772
+ base = (os.environ.get("ADO_URL") or f"https://dev.azure.com/{setting('ADO_ORG')}").rstrip("/")
773
+ project = urllib.request.quote(setting("ADO_PROJECT"))
774
+ token = base64.b64encode(f":{setting('ADO_TM_PAT')}".encode()).decode()
775
+ sep = "&" if "?" in path else "?"
776
+ _, out = http(method, f"{base}/{project}/_apis{path}{sep}api-version=7.1",
777
+ {"Authorization": f"Basic {token}",
778
+ "Content-Type": "application/json-patch+json" if patch else "application/json"},
779
+ json.dumps(body).encode() if body is not None else None, shown=f"/_apis{path}")
780
+ return out
781
+
782
+ @staticmethod
783
+ def steps_xml(case: dict) -> str:
784
+ """The steps as Azure's steps XML (action and expected result per step, text escaped)."""
785
+ from xml.sax.saxutils import escape
786
+ items = case.get("steps", [])
787
+ body = "".join(f'<step id="{i + 2}" type="{"ValidateStep" if s.get("expected") else "ActionStep"}">'
788
+ f'<parameterizedString isformatted="true">{escape(escape(s["action"]))}</parameterizedString>'
789
+ f'<parameterizedString isformatted="true">{escape(escape(s.get("expected", "")))}</parameterizedString>'
790
+ f'<description/></step>' for i, s in enumerate(items))
791
+ return f'<steps id="0" last="{len(items) + 1}">{body}</steps>'
792
+
793
+ def _ops(self, case: dict, op: str) -> list:
794
+ """The JSON Patch operations for the fields Orion writes."""
795
+ from xml.sax.saxutils import escape
796
+ _, expected = _steps_text(case)
797
+ covers = ", ".join(x for x in [case.get("story", "")] + case.get("ac", []) if x)
798
+ desc = "".join(f"<p>{escape(x)}</p>" for x in (case.get("preconditions") and f"Preconditions: {case['preconditions']}",
799
+ case.get("data") and f"Test data: {case['data']}",
800
+ covers and f"Covers: {covers}", expected and f"Expected: {expected}") if x)
801
+ fields = {"System.Title": case["title"], "Microsoft.VSTS.TCM.Steps": self.steps_xml(case), "System.Description": desc,
802
+ "Microsoft.VSTS.Common.Priority": self.PRIORITY.get((case.get("priority") or "").lower(), 2)}
803
+ tags = "; ".join(x for x in [case.get("story", "")] + case.get("labels", []) if x)
804
+ if tags:
805
+ fields["System.Tags"] = tags
806
+ return [{"op": op, "path": f"/fields/{k}", "value": v} for k, v in fields.items()]
807
+
808
+ def create(self, case: dict) -> tuple:
809
+ """Create the work item (and add it to --plan/--suite when given); returns (id, rev)."""
810
+ item = self._call("POST", "/wit/workitems/$Test%20Case", self._ops(case, "add"), patch=True)
811
+ if self.plan:
812
+ self._call("POST", f"/testplan/Plans/{self.plan}/Suites/{self.suite}/TestCase", [{"workItem": {"id": item["id"]}}])
813
+ return str(item["id"]), str(item["rev"])
814
+
815
+ def read(self, key: str) -> tuple:
816
+ """(the remote work item, its rev)."""
817
+ item = self._call("GET", f"/wit/workitems/{key}")
818
+ return item, str(item["rev"])
819
+
820
+ def update(self, key: str, case: dict) -> str:
821
+ """Replace the fields, only if the rev is still the one just read; returns the new rev."""
822
+ remote, rev = self.read(key)
823
+ ops = self._ops(case, "add")
824
+ have = [t.strip() for t in str((remote.get("fields") or {}).get("System.Tags") or "").split(";") if t.strip()]
825
+ for o in ops:
826
+ if o["path"] == "/fields/System.Tags":
827
+ o["value"] = "; ".join(dict.fromkeys(have + [t.strip() for t in o["value"].split(";")]))
828
+ item = self._call("PATCH", f"/wit/workitems/{key}", [{"op": "test", "path": "/rev", "value": int(rev)}] + ops, patch=True)
829
+ return str(item["rev"])
830
+
831
+
832
+ PUSHERS = {"testrail": TestRailCases, "zephyr": ZephyrScaleCases, "xray": XrayCloudCases, "azure": AzureTestCases}
833
+
834
+
835
+ def push_cases(args) -> None:
836
+ """Create or update test cases in a tool from an orion-cases/1 file.
837
+
838
+ Without --approved it is a dry run that prints the plan. With it: each case new to the tool is created, each
839
+ case Orion pushed before and changed since is updated (after a backup, and only if nobody changed it in the
840
+ tool meanwhile), unchanged ones are skipped; a map remembers which case is which key, per tool, per instance and
841
+ project, and per story (every story numbers its cases from TS-1), so a second push never duplicates or overwrites
842
+ another story's case. Nothing is ever deleted.
843
+ """
844
+ doc = _load_json(args.cases, None)
845
+ if not doc or doc.get("format") != "orion-cases/1":
846
+ raise ToolError("Read", args.cases, "not an orion-cases/1 file (cases_model.py to-json makes one)", 2)
847
+ only = set(x.strip() for x in (args.only or "").split(",") if x.strip())
848
+ cases = [c for c in doc["cases"] if not only or c["id"] in only]
849
+ tool = PUSHERS[args.tool](args)
850
+ mapping = _load_json(args.map, {})
851
+ target = tool.target() or "default"
852
+ known = mapping.setdefault(args.tool, {}).setdefault(target, {})
853
+ plan = []
854
+ for c in cases:
855
+ entry = known.get(_case_ref(c))
856
+ if not entry:
857
+ plan.append(("create", c, None))
858
+ elif entry.get("fingerprint") != _content_hash(c):
859
+ plan.append(("update", c, entry))
860
+ else:
861
+ plan.append(("unchanged", c, entry))
862
+ counts = {k: sum(1 for p in plan if p[0] == k) for k in ("create", "update", "unchanged")}
863
+ print(f"{args.tool} ({target}): create {counts['create']} · update {counts['update']} · unchanged {counts['unchanged']}")
864
+ for act, c, entry in plan:
865
+ print(f" {act:<9} {c['id']:<8} {('→ ' + entry['key']) if entry else '':<10} {c.get('title', '')[:70]}")
866
+ if not args.approved:
867
+ print("dry run: nothing was written (add --approved D-nnn --approver @handle after the user's yes)")
868
+ return
869
+ require_approval(args)
870
+ backups = os.path.join(os.path.dirname(os.path.abspath(args.map)), "tm-backups", args.tool)
871
+ done, refused = 0, []
872
+ for act, c, entry in plan:
873
+ if act == "unchanged":
874
+ continue
875
+ if act == "create":
876
+ key, stamp = tool.create(c)
877
+ else:
878
+ remote, stamp_now = tool.read(entry["key"])
879
+ if entry.get("stamp") and stamp_now != entry["stamp"]:
880
+ refused.append(f"{c['id']} ({entry['key']}): changed in {args.tool} since the last push; import it again first")
881
+ continue
882
+ _save_json(os.path.join(backups, f"{entry['key']}-{stamp_now or 'now'}.json"), remote)
883
+ key, stamp = entry["key"], tool.update(entry["key"], c)
884
+ known[_case_ref(c)] = {"key": key, "fingerprint": _content_hash(c), "stamp": stamp}
885
+ _save_json(args.map, mapping)
886
+ done += 1
887
+ print(f" {act}d {c['id']} → {key}")
888
+ print(f"{args.tool}: {done} written, {len(refused)} refused, approved by @{args.approver.lstrip('@')} ({args.approved})")
889
+ for r in refused:
890
+ print(f" refused: {r}")
891
+ if refused:
892
+ raise ToolError("Push", args.tool, f"{len(refused)} case(s) changed in the tool meanwhile; nothing was overwritten", 4)
893
+
894
+
482
895
  def main() -> int:
483
896
  """Parse the command line, run one command, and map failures to exit codes.
484
897
 
@@ -502,10 +915,17 @@ def main() -> int:
502
915
  p.add_argument("--approved"); p.add_argument("--approver")
503
916
  p = command("xray-import-junit"); p.add_argument("--file", required=True); p.add_argument("--project", required=True)
504
917
  p.add_argument("--test-plan"); p.add_argument("--approved"); p.add_argument("--approver")
918
+ p = command("push-cases"); p.add_argument("--tool", choices=sorted(PUSHERS), required=True)
919
+ p.add_argument("--cases", required=True, help="an orion-cases/1 file"); p.add_argument("--map", default="project-context/tm-map.json")
920
+ p.add_argument("--only", help="case ids, comma-separated"); p.add_argument("--section"); p.add_argument("--template-id")
921
+ p.add_argument("--project-key", help="Zephyr, Xray: the project key"); p.add_argument("--folder", help="Zephyr: the folder id")
922
+ p.add_argument("--plan", help="Azure: the test plan id"); p.add_argument("--suite", help="Azure: the suite id in that plan")
923
+ p.add_argument("--approved"); p.add_argument("--approver")
505
924
  args = ap.parse_args()
506
925
  load_env(args.env)
507
926
  handlers = {"testrail-cases": testrail_cases, "xray-tests": xray_tests, "xlsx-to-csv": xlsx_to_csv,
508
- "testrail-add-result": testrail_add_result, "xray-import-junit": xray_import_junit}
927
+ "testrail-add-result": testrail_add_result, "xray-import-junit": xray_import_junit,
928
+ "push-cases": push_cases}
509
929
  try:
510
930
  handlers[args.cmd](args)
511
931
  except ToolError as err:
@@ -14,4 +14,23 @@ public final class Flags {
14
14
  public static String logLevel() {
15
15
  return Env.value("LOG_LEVEL").orElse("info");
16
16
  }
17
+
18
+ /**
19
+ * How long one request may take before it fails naming the call, so a hung API never blocks a test.
20
+ *
21
+ * @return seconds: `TIMEOUT_SECONDS`; else the site's measured `requestTimeout` in `timeouts.json` (written by
22
+ * Orion's timing profile); default 30
23
+ */
24
+ public static int timeoutSeconds() {
25
+ String value = Env.value("TIMEOUT_SECONDS").orElse("");
26
+ if (value.matches("[1-9][0-9]*")) return Integer.parseInt(value);
27
+ try {
28
+ String json = java.nio.file.Files.readString(Paths.ROOT.resolve("timeouts.json"));
29
+ java.util.regex.Matcher m = java.util.regex.Pattern.compile("\"requestTimeout\"\\s*:\\s*(\\d+)").matcher(json);
30
+ if (m.find()) return (int) Math.ceil(Integer.parseInt(m.group(1)) / 1000.0);
31
+ } catch (java.io.IOException | NumberFormatException e) {
32
+ // No measured value: the default below applies.
33
+ }
34
+ return 30;
35
+ }
17
36
  }
@@ -2,6 +2,8 @@ package automation.services;
2
2
 
3
3
  import automation.config.Env;
4
4
  import io.restassured.builder.RequestSpecBuilder;
5
+ import automation.config.Flags;
6
+ import io.restassured.config.HttpClientConfig;
5
7
  import io.restassured.config.LogConfig;
6
8
  import io.restassured.config.RestAssuredConfig;
7
9
  import io.restassured.http.ContentType;
@@ -20,9 +22,14 @@ public final class ApiSpec {
20
22
  RequestSpecBuilder builder = new RequestSpecBuilder()
21
23
  .setBaseUri(Env.baseUrl())
22
24
  .setContentType(ContentType.JSON)
23
- .setConfig(RestAssuredConfig.config().logConfig(LogConfig.logConfig()
24
- .enableLoggingOfRequestAndResponseIfValidationFails()
25
- .blacklistHeader("Authorization")));
25
+ .setConfig(RestAssuredConfig.config()
26
+ .logConfig(LogConfig.logConfig()
27
+ .enableLoggingOfRequestAndResponseIfValidationFails()
28
+ .blacklistHeader("Authorization"))
29
+ // Bounded: a hung API fails after the timeout instead of blocking the test (rule U16).
30
+ .httpClient(HttpClientConfig.httpClientConfig()
31
+ .setParam("http.connection.timeout", Flags.timeoutSeconds() * 1000)
32
+ .setParam("http.socket.timeout", Flags.timeoutSeconds() * 1000)));
26
33
  Env.token().ifPresent(token -> builder.addHeader("Authorization", "Bearer " + token));
27
34
  spec = builder.build();
28
35
  }
@@ -24,6 +24,8 @@ public abstract class BasePage
24
24
  {
25
25
  Driver = driver;
26
26
  Wait = new WebDriverWait(driver, Flags.Timeout());
27
+ // A page that re-renders replaces elements: a stale one is retried within the same bounded wait.
28
+ Wait.IgnoreExceptionTypes(typeof(StaleElementReferenceException));
27
29
  }
28
30
 
29
31
  /// <summary>The page's path relative to <c>BASE_URL</c> (from <c>TestData</c>); "" for a page with no path of its own.</summary>
@@ -69,35 +71,111 @@ public abstract class BasePage
69
71
  return this;
70
72
  }
71
73
 
72
- /// <summary>An element once it is visible.</summary>
74
+ /// <summary>An element once it is visible; see <see cref="EnsureVisible"/>.</summary>
73
75
  /// <param name="locator">The element's locator.</param>
74
76
  /// <returns>The element.</returns>
75
- protected IWebElement Visible(By locator) =>
76
- Wait.Until(d => d.FindElements(locator).FirstOrDefault(e => e.Displayed))!;
77
+ protected IWebElement Visible(By locator) => EnsureVisible(locator, locator.ToString());
78
+
79
+ /// <summary>
80
+ /// Requires an element to be visible, and fails fast with a named reason when it isn't: what was missing, on which
81
+ /// page, after how long. One bounded wait (no polling loop, no Thread.Sleep).
82
+ /// </summary>
83
+ /// <param name="locator">The element's locator.</param>
84
+ /// <param name="what">The element in the user's words, e.g. "the Webhooks section".</param>
85
+ /// <returns>The element.</returns>
86
+ /// <exception cref="AutomationError">"Wait for &lt;what&gt;: not visible within &lt;n&gt;s (page: &lt;url&gt;)".</exception>
87
+ protected IWebElement EnsureVisible(By locator, string what)
88
+ {
89
+ try
90
+ {
91
+ return Wait.Until(d => d.FindElements(locator).FirstOrDefault(e => e.Displayed))!;
92
+ }
93
+ catch (WebDriverTimeoutException)
94
+ {
95
+ throw new AutomationError("Wait for", what, $"not visible within {Flags.Timeout().TotalSeconds}s",
96
+ new Dictionary<string, string?> { ["page"] = Driver.Url });
97
+ }
98
+ }
99
+
100
+ /// <summary>
101
+ /// Asks whether an element is shown now, without failing: for choosing a path in a page action, never for what a
102
+ /// test checks. @toolkit: kept for page actions to reuse.
103
+ /// </summary>
104
+ /// <param name="locator">The element's locator.</param>
105
+ /// <returns>Whether it is shown (no implicit wait).</returns>
106
+ protected bool IsShown(By locator) => Driver.FindElements(locator).Any(e => e.Displayed);
77
107
 
78
108
  /// <summary>Clears a visible field and types into it.</summary>
79
109
  /// <param name="locator">The field's locator.</param>
80
110
  /// <param name="text">What to type.</param>
81
111
  protected void Type(By locator, string text)
82
112
  {
83
- var element = Visible(locator);
84
- element.Clear();
85
- element.SendKeys(text);
113
+ // Find, clear and type in one step of the wait, so a re-rendered field is found again instead of going stale.
114
+ try
115
+ {
116
+ Wait.Until(d =>
117
+ {
118
+ var element = d.FindElements(locator).FirstOrDefault(e => e.Displayed);
119
+ if (element is null) return false;
120
+ element.Clear();
121
+ element.SendKeys(text);
122
+ return true;
123
+ });
124
+ }
125
+ catch (WebDriverTimeoutException)
126
+ {
127
+ throw new AutomationError("Type into", locator.ToString(), $"not visible within {Flags.Timeout().TotalSeconds}s",
128
+ new Dictionary<string, string?> { ["page"] = Driver.Url });
129
+ }
86
130
  }
87
131
 
88
132
  /// <summary>Clicks an element once it is visible and enabled.</summary>
89
133
  /// <param name="locator">The element's locator.</param>
90
- protected void Click(By locator) =>
91
- Wait.Until(d => d.FindElements(locator).FirstOrDefault(e => e.Displayed && e.Enabled))!.Click();
134
+ protected void Click(By locator)
135
+ {
136
+ try
137
+ {
138
+ Wait.Until(d =>
139
+ {
140
+ var element = d.FindElements(locator).FirstOrDefault(e => e.Displayed && e.Enabled);
141
+ if (element is null) return false;
142
+ element.Click();
143
+ return true;
144
+ });
145
+ }
146
+ catch (WebDriverTimeoutException)
147
+ {
148
+ throw new AutomationError("Click", locator.ToString(), $"not clickable within {Flags.Timeout().TotalSeconds}s",
149
+ new Dictionary<string, string?> { ["page"] = Driver.Url });
150
+ }
151
+ }
92
152
 
93
153
  /// <summary>An element's text once it is visible and not empty (readiness, not a check of the value).</summary>
94
154
  /// <param name="locator">The element's locator.</param>
95
155
  /// <returns>Its text.</returns>
96
156
  protected string TextWhenPresent(By locator)
97
157
  {
98
- var element = Visible(locator);
99
- Wait.Until(_ => !string.IsNullOrWhiteSpace(element.Text));
100
- return element.Text;
158
+ // Look the element up on every check: a page that re-renders the message would leave a kept reference stale.
159
+ try
160
+ {
161
+ return Wait.Until(d =>
162
+ {
163
+ try
164
+ {
165
+ var text = d.FindElements(locator).FirstOrDefault(e => e.Displayed)?.Text;
166
+ return string.IsNullOrWhiteSpace(text) ? null : text;
167
+ }
168
+ catch (StaleElementReferenceException)
169
+ {
170
+ return null;
171
+ }
172
+ })!;
173
+ }
174
+ catch (WebDriverTimeoutException)
175
+ {
176
+ throw new AutomationError("Wait for", locator.ToString(), $"no text within {Flags.Timeout().TotalSeconds}s",
177
+ new Dictionary<string, string?> { ["page"] = Driver.Url });
178
+ }
101
179
  }
102
180
 
103
181
  /// <summary>Sets one form field (used by `Utils/FormFill`): text typed, a select chosen by text, a check box set.</summary>