Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(coverage): ingest Salesforce Apex test coverage (#4413)

Raghav Chamadiyaf08b34f1ea5f
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.md
index 7c119c057..70f3450b5 100644
--- a/docs/architecture/language-support.md
+++ b/docs/architecture/language-support.md
@@ -976,6 +976,10 @@ An `HttpRequest` callout is a consumer when its endpoint and verb are literal
within one method; `callout:Name` keeps the Named Credential as the base. The
credential's own endpoint is not read.
+Salesforce CLI coverage names a class or trigger, never a file, so it maps to
+the one `.cls` or `.trigger` file of that name, ignoring case. A name two files
+share, or no file has, stays unmapped.
+
### QML
Module specs resolve against an index built from the `qmldir` manifests in the
diff --git a/docs/architecture/test-intelligence.md b/docs/architecture/test-intelligence.md
index 0daad1102..fcf9f3a81 100644
--- a/docs/architecture/test-intelligence.md
+++ b/docs/architecture/test-intelligence.md
@@ -153,13 +153,15 @@ The file is sniffed unless `--format` or `coverage.format` names a parser:
| Clover XML | `<coverage` plus `<project` |
| JaCoCo XML | The JaCoCo doctype, or a `<report` root |
| Go coverprofile | Leading `mode:` line |
+| Salesforce Apex JSON | `{` naming `orgWideCoverage`, `testRunCoverage` or `ApexClassOrTrigger`, or a `[` list with `totalLines` and `lines` |
| coverage.py `.coverage` | SQLite file |
| Normalized JSON (`repowise-coverage-v1`) | Leading `{` plus `repowise-coverage` or `line_coverage_pct` |
With no path, `coverage add` looks for `coverage/lcov.info`, `lcov.info`,
`coverage.lcov`, `coverage.xml`, `**/cobertura.xml`, `**/clover.xml`,
`target/llvm-cov/**/*.lcov`, `coverage.out`, `cover.out`,
-`**/target/site/jacoco*/jacoco.xml`, `build/reports/jacoco/**/*.xml`, a repo-root
+`**/target/site/jacoco*/jacoco.xml`, `build/reports/jacoco/**/*.xml`,
+`**/test-result-codecoverage.json` (Salesforce CLI and VS Code), a repo-root
`.coverage` and a few more (`coverage.artifacts` overrides them). Multiple reports merge
by unioning covered and coverable lines.
diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.md
index 26ec48bc2..234003433 100644
--- a/docs/layers/LANGUAGE_SUPPORT.md
+++ b/docs/layers/LANGUAGE_SUPPORT.md
@@ -76,7 +76,8 @@ Scala, Elixir and F# have dedicated import resolvers with known gaps; see
calls are entry paths the repository graph cannot observe.
Apex (`.cls`, `.trigger`, `.apex`) is parsed for symbols, heritage and calls,
and is excluded from dead-code claims the same way until triggers, annotations
-and platform interfaces are modelled as entry points.
+and platform interfaces are modelled as entry points. Apex test coverage from the
+Salesforce CLI is read as a coverage report ([formats](TEST_INTELLIGENCE.md#supported-formats)).
## How accurate is the graph per language
diff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.md
index e306cc38d..7b7ec6a77 100644
--- a/docs/layers/TEST_INTELLIGENCE.md
+++ b/docs/layers/TEST_INTELLIGENCE.md
@@ -66,13 +66,16 @@ Each inferred answer about a file is one of six states
## Supported formats
**LCOV**, **Cobertura**, **Clover** and **JaCoCo** XML, **Go coverprofile**
-(`go test -coverprofile`), **coverage.py `.coverage`** and **normalized JSON**
-(`repowise-coverage-v1`). Two carry a per-test map: LCOV when each record has a
-non-blank `TN:` test name, and `.coverage` when recorded with per-test contexts.
+(`go test -coverprofile`), **Salesforce Apex JSON** (`sf apex run test
+--code-coverage --result-format json`, or `test-result-codecoverage.json`),
+**coverage.py `.coverage`** and **normalized JSON** (`repowise-coverage-v1`).
+Three carry a per-test map: LCOV when each record has a non-blank `TN:` test
+name, `.coverage` when recorded with per-test contexts, and the Apex run result
+(`test-result-<run id>.json`), keyed `TestClass.method`.
- The format is sniffed and found in the usual locations
([rules](../architecture/test-intelligence.md#report-formats-and-discovery)); force
- one with `--format lcov|cobertura|clover|repowise-json|go-coverprofile|jacoco`. Go
+ one with `--format lcov|cobertura|clover|repowise-json|go-coverprofile|jacoco|apex`. Go
percentages are line-based, not `go tool cover`'s statement percentage.
- Paths map by suffix, a tie is reported, never guessed
([rules](../architecture/test-intelligence.md#report-path-matching)); `--strict` fails
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 4f164b7dd..850caea96 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -119,7 +119,7 @@ Workspaces add repo scanning, per-repo indexing, cross-repo analysis (co-changes
| `--skip-tests` | No docs for test files. | off |
| `--skip-infra` | No docs for infra (Dockerfiles, Makefiles, Terraform). | off |
| `--include-submodules` | Include git submodules. | excluded |
-| `--coverage-report` | LCOV, Cobertura, Clover, JaCoCo, Go coverprofile. Repeatable. Feeds code health only; every code file is documented regardless. | auto-discovered |
+| `--coverage-report` | LCOV, Cobertura, Clover, JaCoCo, Go coverprofile, Salesforce Apex JSON. Repeatable. Feeds code health only; every code file is documented regardless. | auto-discovered |
| `--commit-limit` | Max commits per file and for co-change; cap 10000. Saved. | `5000` |
| `--follow-renames` | Track renames via `git log --follow` (slower, more accurate). Saved. | off |
| `--resume` | Continue a previous run; see notes. | off |
@@ -1102,7 +1102,7 @@ repowise coverage add .coverage # per-test map
| Flag | What it does | Default |
|------|--------------|---------|
| `--path` | Repo path. | `add`: cwd / workspace primary; `status`: cwd |
-| `--format` | `add`: force a parser (`lcov`, `cobertura`, `clover`, `repowise-json`, `go-coverprofile`, `jacoco`). `status`: `table` or `json`. | `add`: auto-detect; `status`: `table` |
+| `--format` | `add`: force a parser (`lcov`, `cobertura`, `clover`, `repowise-json`, `go-coverprofile`, `jacoco`, `apex`). `status`: `table` or `json`. | `add`: auto-detect; `status`: `table` |
| `--strict` | `add`: also exit non-zero when some report files do not map. | off |
| `--allow-partial` | `add`: store even when over half does not map; rows flagged partial. | off |
| `--verbose` / `-v` | `add`: debug logs. | off |
@@ -1112,7 +1112,7 @@ repowise coverage add .coverage # per-test map
`hooks.coverage_reingest`.
- Over half unmapped: stores nothing, exits `1`, suggests a `coverage.strip_prefix` or `coverage.path_prefix`. `init` /
`update` keep nothing from it, so their re-read clears an `--allow-partial` fragment.
-- Formats: LCOV, Cobertura, Clover, JaCoCo XML, Go coverprofile (`go test -coverprofile`). With no path, discovers
+- Formats: LCOV, Cobertura, Clover, JaCoCo XML, Go coverprofile (`go test -coverprofile`), Salesforce Apex JSON. With no path, discovers
`coverage/lcov.info`, `.coverage`, `coverage.out`, `target/site/jacoco/jacoco.xml` and similar.
- *Test-to-code map* (which test covers which lines: "which tests exercise this change"): from a context-recorded
`.coverage` or per-test lcov; without contexts, per-file only. Separate from the per-file aggregate and `health`.
diff --git a/docs/start/CI.md b/docs/start/CI.md
index 22671bffe..cfac2bd9f 100644
--- a/docs/start/CI.md
+++ b/docs/start/CI.md
@@ -251,6 +251,7 @@ Reports must list every runnable line, including new files no test loads
| Java (Maven) | `mvn test jacoco:report` (`report-aggregate` for multi-module) | `target/site/jacoco/jacoco.xml` |
| JavaScript or TypeScript | `c8 --all --reporter=lcov`, or a runner's `lcov` reporter including every source file | `coverage/lcov.info` |
| Rust | `cargo llvm-cov --lcov --output-path coverage/lcov.info` | `coverage/lcov.info` |
+| Salesforce Apex | `sf apex run test --code-coverage --result-format json --output-dir coverage` (lists only the classes and triggers the run touched) | `coverage/test-result-<run id>.json` (with the per-test map) |
- Several reports merge: a line any of them ran counts as run.
- Export a coverage.py `.coverage` database first; it is not a text report.
diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-coverage.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-coverage.md
index c476064d7..eb0d3d2b6 100644
--- a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-coverage.md
+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-coverage.md
@@ -1,5 +1,5 @@
---
-description: Ingest or inspect test-coverage reports (LCOV, Cobertura, Clover, Go cover profiles, JaCoCo, or repowise JSON; a coverage.py .coverage builds the per-test map only), or gate a change on its patch coverage in CI.
+description: Ingest or inspect test-coverage reports (LCOV, Cobertura, Clover, Go cover profiles, JaCoCo, Salesforce Apex JSON, or repowise JSON; a coverage.py .coverage builds the per-test map only), or gate a change on its patch coverage in CI.
---
# Repowise Coverage
@@ -25,7 +25,7 @@ repowise coverage status
Handle `$ARGUMENTS`:
- "status" / "show" → `repowise coverage status`
- A report path (`coverage.lcov`, `lcov.info`, `coverage.xml`, `coverage.out`,
- `jacoco.xml`, `.coverage`, …) → `repowise coverage add <path>`
+ `jacoco.xml`, `test-result-codecoverage.json`, `.coverage`, …) → `repowise coverage add <path>`
- "add" with no path → `repowise coverage add` (auto-discover common report paths)
- Multiple paths → `repowise coverage add <a> <b>` (merged; hit wins)
- "check" / "gate" / "patch coverage" → `repowise coverage check [REVSPEC]`
@@ -56,6 +56,7 @@ repowise coverage check origin/main...HEAD --report coverage/lcov.info --fail-un
- The **per-test map** (needed by `/prompts:repowise-impacted-tests`) is built only
when the report carries per-test contexts — e.g. a coverage.py `.coverage`
recorded with `pytest --cov=<package> --cov-context=test` (needs
- pytest-cov), or a per-test lcov. Reports
+ pytest-cov), a per-test lcov, or a Salesforce `test-result-<run id>.json`
+ from `sf apex run test --code-coverage --output-dir <dir>`. Reports
without contexts ingest aggregates only; say so plainly.
- After ingesting, suggest `repowise health --recompute` so untested-hotspot markers update.
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/coverage_reingest.py b/packages/cli/src/repowise/cli/commands/augment_cmd/coverage_reingest.py
index 8d8d54aa6..a1e2edd44 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/coverage_reingest.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/coverage_reingest.py
@@ -52,6 +52,7 @@ DEFAULT_REPORTS = (
"coverage.out",
"cover.out",
"target/site/jacoco/jacoco.xml",
+ ".sfdx/tools/testresults/apex/test-result-codecoverage.json",
)
QUEUED_FILENAME = ".coverage.queued"
diff --git a/packages/cli/src/repowise/cli/commands/coverage_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_cmd.py
index e150044e1..f171fe73e 100644
--- a/packages/cli/src/repowise/cli/commands/coverage_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/coverage_cmd.py
@@ -497,6 +497,15 @@ def coverage_status(repo: str | None, fmt: str) -> None:
f" Files: {map_summary['source_file_count']}\n"
f" Records: {map_summary['pair_count']}"
)
+ elif summary.get("source_format") == "apex":
+ # test-result-codecoverage.json is per class only; the run's
+ # own result file carries the per-test records.
+ console.print(
+ "[dim]No test-to-code map yet - add the run's "
+ "[cyan]test-result-<run id>.json[/cyan] from "
+ "[cyan]sf apex run test --code-coverage --output-dir <dir>[/cyan] with "
+ "[cyan]repowise coverage add[/cyan].[/dim]"
+ )
else:
console.print(
"[dim]No test-to-code map yet - record one with "
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/README.md b/packages/core/src/repowise/core/analysis/health/coverage/README.md
index fb660a6e6..06bb20178 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/README.md
+++ b/packages/core/src/repowise/core/analysis/health/coverage/README.md
@@ -17,7 +17,7 @@ from repowise.core.analysis.health.coverage import (
- `parse(text, format=None)` → `CoverageReport`. Auto-detects format
when `format` is ``None``; pass an explicit ``"lcov" | "cobertura" |
- "clover" | "repowise-json" | "go-coverprofile" | "jacoco"`` to override
+ "clover" | "repowise-json" | "go-coverprofile" | "jacoco" | "apex"`` to override
(`detector.PARSERS` is the registry).
- `parse_lcov(text)`, `parse_cobertura(text)`, `parse_clover(text)`,
`parse_repowise_json(text)`, `parse_go_coverprofile(text)`,
@@ -34,6 +34,9 @@ from repowise.core.analysis.health.coverage import (
test. Callers holding the stored `is_test` flag use that instead.
- `paired_test_file(path, all_paths)`: find the conventional test partner for
a source path.
+- `apex.py` (`parse_apex`, `parse_apex_contexts`): Salesforce CLI JSON. Paths
+ are `Name.cls` / `Name.trigger`, mapped to the one file of that name; the run
+ result's `ApexCodeCoverage` records are the per-test map.
- `contexts.py` (`parse_contexts_file`, `parse_lcov_contexts`): per-test readers
for a coverage.py `.coverage` SQLite file with contexts and for per-test LCOV
`TN:` records; a report without contexts yields no records.
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py b/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
index 02a02799f..dfe5381db 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+from .apex import parse_apex, parse_apex_contexts
from .clover import parse_clover
from .cobertura import parse_cobertura
from .contexts import (
@@ -80,6 +81,8 @@ __all__ = [
"measurement_ref",
"normalize_report_path",
"parse",
+ "parse_apex",
+ "parse_apex_contexts",
"parse_clover",
"parse_cobertura",
"parse_contexts_file",
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/apex.py b/packages/core/src/repowise/core/analysis/health/coverage/apex.py
new file mode 100644
index 000000000..2d70ed6c2
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/coverage/apex.py
@@ -0,0 +1,137 @@
+"""Salesforce Apex coverage parser (Salesforce CLI JSON).
+
+Reads what ``sf apex run test --code-coverage --result-format json`` (or the
+legacy ``sfdx force:apex:test:run -c -r json``, or ``sf apex get test``)
+prints, and the files its ``--output-dir`` writes:
+
+- the whole result, as stdout or ``test-result-<run id>.json``::
+
+ {"status": 0, "result": {"summary": {...}, "tests": [...],
+ "coverage": {"coverage": [<entry>, ...], "records": [<record>, ...]}}}
+
+- ``test-result-codecoverage.json``, the bare ``[<entry>, ...]`` list.
+
+An entry is one class or trigger's coverage for the run::
+
+ {"id": "01p...", "name": "AccountService", "totalLines": 28,
+ "lines": {"4": 1, "18": 0}, "totalCovered": 22, "coveredPercent": 79}
+
+``lines`` holds every executable line, ``1`` covered and ``0`` not. A record
+is one test method's coverage of one class or trigger (``ApexCodeCoverage``)::
+
+ {"ApexTestClass": {"Name": "AccountServiceTest"}, "TestMethodName": "creates",
+ "ApexClassOrTrigger": {"Id": "01p...", "Name": "AccountService"},
+ "Coverage": {"coveredLines": [3, 4], "uncoveredLines": [8]}}
+
+Names are API names, never file paths: the file path is the name plus
+``.cls`` for an ``ApexClass`` id (``01p`` prefix) or ``.trigger`` for an
+``ApexTrigger`` id (``01q``), and the resolver maps that to the one file of
+that name in the repo. A name with no known id prefix stays bare and the
+resolver tries both extensions.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from .model import ContextCoverageReport, CoverageReport, TestCoverage, file_coverage
+
+#: Salesforce key prefixes of the two Apex metadata types coverage names.
+_EXT_BY_ID_PREFIX = {"01p": ".cls", "01q": ".trigger"}
+
+_BOM = chr(0xFEFF)
+
+
+def _dicts(value: Any) -> list[dict]:
+ return [v for v in value if isinstance(v, dict)] if isinstance(value, list) else []
+
+
+def _load(text: str) -> tuple[list[dict], list[dict]]:
+ """``(entries, records)`` from any of the CLI's JSON shapes, empty when unreadable."""
+ try:
+ data = json.loads(text.lstrip(_BOM))
+ except (ValueError, TypeError):
+ return [], []
+ if isinstance(data, list):
+ return _dicts(data), []
+ result = data.get("result", data) if isinstance(data, dict) else None
+ coverage = result.get("coverage") if isinstance(result, dict) else None
+ if not isinstance(coverage, dict):
+ return [], []
+ return _dicts(coverage.get("coverage")), _dicts(coverage.get("records"))
+
+
+def _apex_path(name: Any, sf_id: Any) -> str | None:
+ """``Name.cls`` / ``Name.trigger`` by the id's key prefix, bare ``Name`` when unknown."""
+ if not isinstance(name, str) or not name.strip():
+ return None
+ ext = _EXT_BY_ID_PREFIX.get(sf_id[:3], "") if isinstance(sf_id, str) else ""
+ return name.strip() + ext
+
+
+def _lines(raw: Any) -> list[int]:
+ if not isinstance(raw, list):
+ return []
+ return [n for n in raw if isinstance(n, int) and not isinstance(n, bool) and n > 0]
+
+
+def parse_apex(text: str) -> CoverageReport:
+ """Per-class aggregate coverage from Salesforce CLI JSON."""
+ entries, _ = _load(text)
+ files = []
+ for entry in entries:
+ path = _apex_path(entry.get("name"), entry.get("id"))
+ lines = entry.get("lines")
+ if path is None or not isinstance(lines, dict):
+ continue
+ coverable: list[int] = []
+ covered: list[int] = []
+ for line, hits in lines.items():
+ try:
+ n = int(line)
+ except (TypeError, ValueError):
+ continue
+ if n <= 0:
+ continue
+ coverable.append(n)
+ if isinstance(hits, (int, float)) and hits > 0:
+ covered.append(n)
+ # A class with no executable lines (an interface) has nothing to measure.
+ if coverable:
+ files.append(file_coverage(path, covered, coverable))
+ return CoverageReport(source_format="apex", files=files)
+
+
+def parse_apex_contexts(text: str) -> ContextCoverageReport:
+ """Per-test records (one per test method and class or trigger) from Salesforce CLI JSON.
+
+ ``test_id`` is ``TestClass.method``, the name ``sf apex run test --tests``
+ takes; ``test_file`` is the test class's ``.cls`` name, for the resolver to
+ map like the covered file.
+ """
+ _, raw_records = _load(text)
+ records: list[TestCoverage] = []
+ for rec in raw_records:
+ target = rec.get("ApexClassOrTrigger")
+ test_class = rec.get("ApexTestClass")
+ method = rec.get("TestMethodName")
+ coverage = rec.get("Coverage")
+ if not (isinstance(target, dict) and isinstance(test_class, dict)):
+ continue
+ path = _apex_path(target.get("Name"), target.get("Id"))
+ class_name = test_class.get("Name")
+ covered = _lines(coverage.get("coveredLines")) if isinstance(coverage, dict) else []
+ if path is None or not isinstance(class_name, str) or not class_name or not covered:
+ continue
+ test_id = f"{class_name}.{method}" if isinstance(method, str) and method else class_name
+ records.append(
+ TestCoverage(
+ test_id=test_id,
+ file_path=path,
+ covered_lines=sorted(set(covered)),
+ source_format="apex",
+ test_file=f"{class_name}.cls",
+ )
+ )
+ return ContextCoverageReport(source_format="apex", records=records, has_contexts=bool(records))
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/contexts.py b/packages/core/src/repowise/core/analysis/health/coverage/contexts.py
index 075c98506..f09c427cd 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/contexts.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/contexts.py
@@ -5,13 +5,15 @@ test into one hit-wins aggregate per file - they know a file is covered,
never by *which* test. These readers keep the test dimension instead,
emitting one :class:`TestCoverage` per ``(test, file)`` pair.
-Two sources carry per-test data today:
+Three sources carry per-test data today:
- **coverage.py ``.coverage`` sqlite** with per-test contexts (static or
dynamic). The ``context`` table names each test; the
``line_bits`` / ``arc`` rows are keyed by ``(file_id, context_id)``.
- **lcov ``TN:`` records** - the test-name line, blank in most merged lcov
but populated by per-test lcov output.
+- **Salesforce Apex JSON** (``sf apex run test --code-coverage``): its
+ ``ApexCodeCoverage`` records, one per test method and class (:mod:`.apex`).
Both degrade loudly: a report produced *without* contexts (a plain lcov, or
a ``.coverage`` without contexts) yields ``records=[]`` and
@@ -25,9 +27,12 @@ index, and any downstream feature live above this layer.
from __future__ import annotations
+import codecs
import sqlite3
from pathlib import Path
+from .apex import parse_apex_contexts
+from .detector import detect_format
from .lcov import _normalize_path
from .model import ContextCoverageReport, TestCoverage
@@ -56,6 +61,17 @@ def is_coverage_data_file(path: str | Path) -> bool:
return False
+def read_report_text(path: str | Path) -> str:
+ """A text report's contents: UTF-8, or UTF-16 when it opens with a UTF-16 BOM.
+
+ Windows PowerShell 5.1 ``>`` redirection writes UTF-16. Raises like ``read_text``.
+ """
+ data = Path(path).read_bytes()
+ if data.startswith((codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)):
+ return data.decode("utf-16")
+ return data.decode("utf-8")
+
+
def parse_lcov_contexts(text: str) -> ContextCoverageReport:
"""Parse per-test records from an lcov report's ``TN:`` names.
@@ -213,16 +229,20 @@ def _has_table(conn: sqlite3.Connection, name: str) -> bool:
def parse_contexts_file(path: str | Path) -> ContextCoverageReport:
- """Parse a per-test report, sniffing coverage.py sqlite vs lcov text.
+ """Parse a per-test report: coverage.py sqlite, Salesforce Apex JSON, or lcov text.
- coverage.py ``.coverage`` files are sqlite (binary magic header);
- everything else is read as lcov text. Unreadable files degrade to an
- empty aggregate-only report rather than raising.
+ coverage.py ``.coverage`` files are sqlite (binary magic header); text the
+ format sniffer calls Apex JSON is read for its per-test records; everything
+ else is read as lcov text. Unreadable files degrade to an empty
+ aggregate-only report rather than raising.
"""
p = Path(path)
if is_coverage_data_file(p):
return parse_coverage_sqlite(p)
try:
- return parse_lcov_contexts(p.read_text(encoding="utf-8"))
+ text = read_report_text(p)
except (OSError, UnicodeDecodeError):
return ContextCoverageReport(source_format="unknown", has_contexts=False)
+ if detect_format(text) == "apex":
+ return parse_apex_contexts(text)
+ return parse_lcov_contexts(text)
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/detector.py b/packages/core/src/repowise/core/analysis/health/coverage/detector.py
index 15f88b93f..34150a62a 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/detector.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/detector.py
@@ -20,6 +20,9 @@ Sniffing rules (cheap, deterministic), after stripping a UTF-8 BOM:
- Go cover profiles start with ``mode:`` on the first non-blank line.
- JaCoCo XML declares the ``-//JACOCO//DTD`` doctype or has a ``<report``
root (and no ``<coverage`` element).
+- Salesforce Apex JSON is a ``{`` result naming ``orgWideCoverage``,
+ ``testRunCoverage`` or ``ApexClassOrTrigger``, or a ``[`` list of entries
+ with ``totalLines`` and ``lines`` (``test-result-codecoverage.json``).
If detection is ambiguous, callers can pass ``coverage add --format`` to
override.
@@ -32,6 +35,7 @@ from collections.abc import Callable
from typing import TYPE_CHECKING
from ....test_paths import is_test_related_path
+from .apex import parse_apex
from .clover import parse_clover
from .cobertura import parse_cobertura
from .goprofile import parse_go_coverprofile
@@ -69,6 +73,7 @@ PARSERS: dict[str, Callable[[str], CoverageReport]] = {
"repowise-json": parse_repowise_json,
"go-coverprofile": parse_go_coverprofile,
"jacoco": parse_jacoco,
+ "apex": parse_apex,
}
#: Accepted spellings that are not canonical format names.
@@ -93,6 +98,16 @@ def _is_repowise_json(sample: str) -> bool:
)
+def _is_apex(sample: str) -> bool:
+ # The CLI's result opens with a summary naming the coverage percentages; the
+ # bare entry list opens with the first class's ``totalLines`` and ``lines``.
+ if sample.startswith("{"):
+ return any(
+ k in sample for k in ('"orgWideCoverage"', '"testRunCoverage"', '"ApexClassOrTrigger"')
+ )
+ return sample.startswith("[") and '"totalLines"' in sample and '"lines"' in sample
+
+
def _is_lcov(sample: str) -> bool:
return sample.startswith(("TN:", "SF:")) or _LCOV_LINE_RE.match(sample) is not None
@@ -124,6 +139,7 @@ def _is_jacoco_report(sample: str) -> bool:
#: ``(format, sniffer)`` in priority order; the first match wins.
_SNIFFERS: tuple[tuple[str, Callable[[str], bool]], ...] = (
("repowise-json", _is_repowise_json),
+ ("apex", _is_apex),
("lcov", _is_lcov),
("go-coverprofile", _is_go_coverprofile),
("jacoco", _is_jacoco_doctype),
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py b/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
index 8edbaed5b..0ee11e802 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
@@ -36,7 +36,7 @@ import pathspec
from repowise.core.fs_walk import PRUNED_DIRS, WalkSnapshot, iter_glob
-from .contexts import COVERAGE_DATA_FILE_NOTE, is_coverage_data_file
+from .contexts import COVERAGE_DATA_FILE_NOTE, is_coverage_data_file, read_report_text
from .detector import parse as parse_coverage
from .model import (
ContextCoverageReport,
@@ -71,6 +71,10 @@ DEFAULT_DISCOVERY_GLOBS: tuple[str, ...] = (
# Root module only: ``build`` is pruned under ``**``, so a nested
# module's report is passed explicitly.
"build/reports/jacoco/**/*.xml",
+ # Salesforce: the VS Code extension's results dir, and any
+ # ``sf apex run test --code-coverage --output-dir``.
+ ".sfdx/tools/testresults/apex/test-result-codecoverage.json",
+ "**/test-result-codecoverage.json",
)
# Directories we never descend into when expanding ``**`` patterns — heavy,
@@ -704,19 +708,47 @@ def normalize_report_path(
return p
+#: Apex source extensions. Apex names are case-insensitive, so these files are
+#: indexed and looked up by their case-folded basename.
+_APEX_EXTS = (".cls", ".trigger")
+
+
+def _index_name(base: str) -> str:
+ folded = base.casefold()
+ return folded if folded.endswith(_APEX_EXTS) else base
+
+
def _build_suffix_index(repo_keys: set[str]) -> dict[str, list[str]]:
"""Map each basename -> repo keys ending in that basename.
Basename is the cheap first filter; trailing-segment overlap then
disambiguates among same-named files (``mod.rs`` is everywhere in Rust).
+ Apex files are keyed case-folded (:func:`_index_name`).
"""
index: dict[str, list[str]] = defaultdict(list)
for key in repo_keys:
base = key.rsplit("/", 1)[-1]
- index[base].append(key)
+ index[_index_name(base)].append(key)
return index
+def _apex_names(norm_path: str) -> tuple[str, ...]:
+ """The Apex file basenames a Salesforce coverage entry can mean, case-folded.
+
+ ``Foo.cls`` / ``Foo.trigger`` from the Apex JSON parser, or a bare ``Foo``
+ (optionally under the CLI's ``no-map/``) meaning either. Empty otherwise.
+ """
+ segs = norm_path.split("/")
+ if len(segs) == 2 and segs[0] == "no-map":
+ segs = segs[1:]
+ name = segs[0].casefold() if len(segs) == 1 else ""
+ if name.endswith(_APEX_EXTS):
+ return (name,)
+ if not name or "." in name:
+ return ()
+ return tuple(name + ext for ext in _APEX_EXTS)
+
+
def _match_key(
norm_path: str,
repo_keys: set[str],
@@ -742,8 +774,13 @@ def _match_key(
if norm_path in repo_keys:
return norm_path, False
+ # An Apex name is unique in an org, so two files of that name are copies: refuse.
+ hits = [k for name in _apex_names(norm_path) for k in suffix_index.get(name, ())]
+ if hits:
+ return (hits[0], False) if len(hits) == 1 else (None, True)
+
base = norm_path.rsplit("/", 1)[-1]
- candidates = suffix_index.get(base)
+ candidates = suffix_index.get(_index_name(base))
if not candidates:
return None, False
@@ -1101,7 +1138,7 @@ def suggest_prefixes(
for norm in sample:
segs = norm.split("/")
rewrites: set[tuple[str, str]] = set()
- for key in suffix_index.get(segs[-1], ()):
+ for key in suffix_index.get(_index_name(segs[-1]), ()):
key_segs = key.split("/")
tail = _common_run(reversed(segs), reversed(key_segs))
rewrites.add(("/".join(segs[:-tail]), "/".join(key_segs[:-tail])))
@@ -1233,7 +1270,7 @@ def resolve_test_reports(
out.matched_suffix += 1
test_key: str | None = None
- head = _extract_test_file(rec.test_id)
+ head = rec.test_file or _extract_test_file(rec.test_id)
if head:
tkey, _, _ = _resolve_path(head, repo_keys, suffix_index, **resolve_kw)
if tkey is not None:
@@ -1287,7 +1324,7 @@ def build_coverage_map(
errors.append((path, COVERAGE_DATA_FILE_NOTE))
continue
try:
- text = path.read_text(encoding="utf-8")
+ text = read_report_text(path)
except OSError as exc:
errors.append((path, f"could not read: {exc}"))
continue
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/model.py b/packages/core/src/repowise/core/analysis/health/coverage/model.py
index 1eb24423b..95a2fa9cd 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/model.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/model.py
@@ -141,7 +141,9 @@ class TestCoverage:
raw source path from the report until :func:`resolve_test_reports`
rewrites it to a canonical repo key. ``test_file`` is the canonical key
of the test's *own* source file, filled in best-effort by the resolver
- (``None`` when the test id is not path-shaped or does not resolve).
+ (``None`` when the test id is not path-shaped or does not resolve). A
+ parser that knows the test's file by name (Apex: ``FooTest.cls``) sets
+ it raw, for the resolver to map like ``file_path``.
"""
# Tell pytest this ``Test``-prefixed class is not a test to collect.
diff --git a/plugins/claude-code/commands/coverage.md b/plugins/claude-code/commands/coverage.md
index 62c5213ef..8de15a38a 100644
--- a/plugins/claude-code/commands/coverage.md
+++ b/plugins/claude-code/commands/coverage.md
@@ -1,5 +1,5 @@
---
-description: Ingest or inspect test-coverage reports (LCOV, Cobertura, Clover, Go cover profiles, JaCoCo, or repowise JSON; a coverage.py .coverage builds the per-test map only), or gate a change on its patch coverage in CI.
+description: Ingest or inspect test-coverage reports (LCOV, Cobertura, Clover, Go cover profiles, JaCoCo, Salesforce Apex JSON, or repowise JSON; a coverage.py .coverage builds the per-test map only), or gate a change on its patch coverage in CI.
allowed-tools: Bash(repowise coverage:*), Read
---
@@ -26,7 +26,7 @@ repowise coverage status
Handle `$ARGUMENTS`:
- "status" / "show" → `repowise coverage status`
- A report path (`coverage.lcov`, `lcov.info`, `coverage.xml`, `coverage.out`,
- `jacoco.xml`, `.coverage`, …) → `repowise coverage add <path>`
+ `jacoco.xml`, `test-result-codecoverage.json`, `.coverage`, …) → `repowise coverage add <path>`
- "add" with no path → `repowise coverage add` (auto-discover common report paths)
- Multiple paths → `repowise coverage add <a> <b>` (merged; hit wins)
- "check" / "gate" / "patch coverage" → `repowise coverage check [REVSPEC]`
@@ -57,6 +57,7 @@ repowise coverage check origin/main...HEAD --report coverage/lcov.info --fail-un
- The **per-test map** (needed by `/repowise:impacted-tests`) is built only
when the report carries per-test contexts — e.g. a coverage.py `.coverage`
recorded with `pytest --cov=<package> --cov-context=test` (needs
- pytest-cov), or a per-test lcov. Reports
+ pytest-cov), a per-test lcov, or a Salesforce `test-result-<run id>.json`
+ from `sf apex run test --code-coverage --output-dir <dir>`. Reports
without contexts ingest aggregates only; say so plainly.
- After ingesting, suggest `repowise health --recompute` so untested-hotspot markers update.
diff --git a/plugins/shared/commands/coverage.md b/plugins/shared/commands/coverage.md
index c023ed78e..98509fc04 100644
--- a/plugins/shared/commands/coverage.md
+++ b/plugins/shared/commands/coverage.md
@@ -1,6 +1,6 @@
---
frontmatter: |
- description: Ingest or inspect test-coverage reports (LCOV, Cobertura, Clover, Go cover profiles, JaCoCo, or repowise JSON; a coverage.py .coverage builds the per-test map only), or gate a change on its patch coverage in CI.
+ description: Ingest or inspect test-coverage reports (LCOV, Cobertura, Clover, Go cover profiles, JaCoCo, Salesforce Apex JSON, or repowise JSON; a coverage.py .coverage builds the per-test map only), or gate a change on its patch coverage in CI.
allowed-tools: Bash(repowise coverage:*), Read
---
@@ -27,7 +27,7 @@ repowise coverage status
Handle `$ARGUMENTS`:
- "status" / "show" → `repowise coverage status`
- A report path (`coverage.lcov`, `lcov.info`, `coverage.xml`, `coverage.out`,
- `jacoco.xml`, `.coverage`, …) → `repowise coverage add <path>`
+ `jacoco.xml`, `test-result-codecoverage.json`, `.coverage`, …) → `repowise coverage add <path>`
- "add" with no path → `repowise coverage add` (auto-discover common report paths)
- Multiple paths → `repowise coverage add <a> <b>` (merged; hit wins)
- "check" / "gate" / "patch coverage" → `repowise coverage check [REVSPEC]`
@@ -58,6 +58,7 @@ repowise coverage check origin/main...HEAD --report coverage/lcov.info --fail-un
- The **per-test map** (needed by `{{cmd:impacted-tests}}`) is built only
when the report carries per-test contexts — e.g. a coverage.py `.coverage`
recorded with `pytest --cov=<package> --cov-context=test` (needs
- pytest-cov), or a per-test lcov. Reports
+ pytest-cov), a per-test lcov, or a Salesforce `test-result-<run id>.json`
+ from `sf apex run test --code-coverage --output-dir <dir>`. Reports
without contexts ingest aggregates only; say so plainly.
- After ingesting, suggest `repowise health --recompute` so untested-hotspot markers update.
diff --git a/tests/fixtures/coverage/sample.apex-codecoverage.json b/tests/fixtures/coverage/sample.apex-codecoverage.json
new file mode 100644
index 000000000..402ba03da
--- /dev/null
+++ b/tests/fixtures/coverage/sample.apex-codecoverage.json
@@ -0,0 +1,18 @@
+[
+ {
+ "id": "01p000000000001AAA",
+ "name": "AccountTriggerHandler",
+ "totalLines": 6,
+ "lines": {"4": 1, "5": 1, "8": 1, "9": 0, "12": 1, "13": 0},
+ "totalCovered": 4,
+ "coveredPercent": 67
+ },
+ {
+ "id": "01q000000000001AAA",
+ "name": "AccountTrigger",
+ "totalLines": 2,
+ "lines": {"2": 1, "3": 1},
+ "totalCovered": 2,
+ "coveredPercent": 100
+ }
+]
diff --git a/tests/fixtures/coverage/sample.apex.json b/tests/fixtures/coverage/sample.apex.json
new file mode 100644
index 000000000..6174a03a9
--- /dev/null
+++ b/tests/fixtures/coverage/sample.apex.json
@@ -0,0 +1,95 @@
+{
+ "status": 100,
+ "result": {
+ "summary": {
+ "outcome": "Failed",
+ "testsRan": 3,
+ "passing": 2,
+ "failing": 1,
+ "skipped": 0,
+ "passRate": "67%",
+ "failRate": "33%",
+ "testStartTime": "2026-10-20T09:41:58.000Z",
+ "testExecutionTime": "2609 ms",
+ "testTotalTime": "2609 ms",
+ "commandTime": "366 ms",
+ "hostname": "https://example.my.salesforce.com",
+ "orgId": "00D000000000001AAA",
+ "username": "[email protected]",
+ "testRunId": "7070000000ABCDE",
+ "userId": "005000000000001AAA",
+ "testRunCoverage": "73%",
+ "orgWideCoverage": "69%"
+ },
+ "tests": [
+ {
+ "Id": "07M000000000001AAA",
+ "QueueItemId": "709000000000001AAA",
+ "StackTrace": null,
+ "Message": null,
+ "AsyncApexJobId": "7070000000ABCDEAAA",
+ "MethodName": "testInsertsAccount",
+ "Outcome": "Pass",
+ "ApexClass": {"Id": "01p000000000003AAA", "Name": "AccountTriggerHandler_Tests", "NamespacePrefix": null},
+ "RunTime": 246,
+ "FullName": "AccountTriggerHandler_Tests.testInsertsAccount"
+ }
+ ],
+ "coverage": {
+ "coverage": [
+ {
+ "id": "01p000000000001AAA",
+ "name": "AccountTriggerHandler",
+ "totalLines": 6,
+ "lines": {"4": 1, "5": 1, "8": 1, "9": 0, "12": 1, "13": 0},
+ "totalCovered": 4,
+ "coveredPercent": 67
+ },
+ {
+ "id": "01q000000000001AAA",
+ "name": "AccountTrigger",
+ "totalLines": 2,
+ "lines": {"2": 1, "3": 1},
+ "totalCovered": 2,
+ "coveredPercent": 100
+ },
+ {
+ "id": "01p000000000002AAA",
+ "name": "IAccountService",
+ "totalLines": 0,
+ "lines": {},
+ "totalCovered": 0,
+ "coveredPercent": 0
+ }
+ ],
+ "records": [
+ {
+ "ApexTestClass": {"Id": "01p000000000003AAA", "Name": "AccountTriggerHandler_Tests"},
+ "Coverage": {"coveredLines": [4, 5, 8], "uncoveredLines": [9, 12, 13]},
+ "TestMethodName": "testInsertsAccount",
+ "NumLinesCovered": 3,
+ "ApexClassOrTrigger": {"Id": "01p000000000001AAA", "Name": "AccountTriggerHandler"},
+ "NumLinesUncovered": 3
+ },
+ {
+ "ApexTestClass": {"Id": "01p000000000003AAA", "Name": "AccountTriggerHandler_Tests"},
+ "Coverage": {"coveredLines": [2, 3], "uncoveredLines": []},
+ "TestMethodName": "testInsertsAccount",
+ "NumLinesCovered": 2,
+ "ApexClassOrTrigger": {"Id": "01q000000000001AAA", "Name": "AccountTrigger"},
+ "NumLinesUncovered": 0
+ },
+ {
+ "ApexTestClass": {"Id": "01p000000000003AAA", "Name": "AccountTriggerHandler_Tests"},
+ "Coverage": {"coveredLines": [], "uncoveredLines": [4, 5, 8, 9, 12, 13]},
+ "TestMethodName": "testFailsUpdate",
+ "NumLinesCovered": 0,
+ "ApexClassOrTrigger": {"Id": "01p000000000001AAA", "Name": "AccountTriggerHandler"},
+ "NumLinesUncovered": 6
+ }
+ ],
+ "summary": {"totalLines": 8, "coveredLines": 6, "orgWideCoverage": "69%", "testRunCoverage": "73%"}
+ }
+ },
+ "warnings": []
+}
diff --git a/tests/unit/health/test_coverage_apex.py b/tests/unit/health/test_coverage_apex.py
new file mode 100644
index 000000000..011db8908
--- /dev/null
+++ b/tests/unit/health/test_coverage_apex.py
@@ -0,0 +1,204 @@
+"""Salesforce Apex coverage: CLI JSON parsing and class-name to file resolution."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from repowise.core.analysis.health.coverage import (
+ build_coverage_map,
+ detect_format,
+ discover_artifacts,
+ parse,
+ parse_apex,
+ parse_apex_contexts,
+ parse_contexts_file,
+ resolve_reports,
+ resolve_test_reports,
+)
+from repowise.core.analysis.health.coverage.model import CoverageReport, FileCoverage
+
+FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "coverage"
+CLASSES = "force-app/main/default/classes"
+TRIGGER = "force-app/main/default/triggers/AccountTrigger.trigger"
+
+KEYS = {
+ "force-app/main/default/classes/Trigger Recipes/AccountTriggerHandler.cls",
+ "force-app/main/default/classes/Trigger Recipes/AccountTriggerHandler_Tests.cls",
+ "force-app/main/default/triggers/AccountTrigger.trigger",
+ "force-app/main/default/classes/AccountTrigger.cls",
+ "force-app/main/default/classes/Dup.cls",
+ "unpackaged/classes/Dup.cls",
+ "src/classes/Legacy.cls",
+ "tools/Makefile",
+}
+
+
+def _read(name: str) -> str:
+ return (FIXTURES / name).read_text(encoding="utf-8")
+
+
+def test_parses_cli_result_classes_and_triggers() -> None:
+ report = parse_apex(_read("sample.apex.json"))
+ assert report.source_format == "apex"
+ by_path = {f.file_path: f for f in report.files}
+ # An interface with no executable lines is left out, not stored as 0%.
+ assert set(by_path) == {"AccountTriggerHandler.cls", "AccountTrigger.trigger"}
+ handler = by_path["AccountTriggerHandler.cls"]
+ assert handler.coverable_lines == [4, 5, 8, 9, 12, 13]
+ assert handler.covered_lines == [4, 5, 8, 12]
+ assert handler.line_coverage_pct == pytest.approx(66.67)
+ assert handler.branch_coverage_pct is None
+
+
+def test_codecoverage_file_matches_cli_result() -> None:
+ bare = parse_apex(_read("sample.apex-codecoverage.json"))
+ full = parse_apex(_read("sample.apex.json"))
+ assert [(f.file_path, f.covered_lines) for f in bare.files] == [
+ (f.file_path, f.covered_lines) for f in full.files
+ ]
+
+
+def test_unknown_id_prefix_keeps_bare_name_and_bad_input_is_empty() -> None:
+ report = parse_apex(
+ '[{"name": "Foo", "lines": {"1": 1, "0": 1, "x": 1}}, {"id": "01p", "lines": {}}]'
+ )
+ assert [(f.file_path, f.coverable_lines) for f in report.files] == [("Foo", [1])]
+ assert parse_apex("not json").files == []
+ assert parse_apex('{"result": {"tests": []}}').files == []
+
+
+def test_per_test_records() -> None:
+ report = parse_apex_contexts(_read("sample.apex.json"))
+ assert report.has_contexts
+ # A record with no covered line says nothing about what the test ran.
+ assert [(r.test_id, r.file_path, r.covered_lines, r.test_file) for r in report.records] == [
+ (
+ "AccountTriggerHandler_Tests.testInsertsAccount",
+ "AccountTriggerHandler.cls",
+ [4, 5, 8],
+ "AccountTriggerHandler_Tests.cls",
+ ),
+ (
+ "AccountTriggerHandler_Tests.testInsertsAccount",
+ "AccountTrigger.trigger",
+ [2, 3],
+ "AccountTriggerHandler_Tests.cls",
+ ),
+ ]
+ assert not parse_apex_contexts(_read("sample.apex-codecoverage.json")).has_contexts
+
+
[email protected]("name", ["sample.apex.json", "sample.apex-codecoverage.json"])
+def test_detect_and_dispatch(name: str) -> None:
+ assert detect_format(_read(name)) == "apex"
+ assert detect_format("" + _read(name)) == "apex"
+ assert parse("" + _read(name)).source_format == "apex"
+
+
+def test_detect_needs_the_cli_markers() -> None:
+ assert detect_format('{"result": {"summary": {"outcome": "Passed"}}}') is None
+ assert detect_format('[{"name": "x", "lines": {}}]') is None
+
+
+def test_parse_contexts_file_reads_apex(tmp_path: Path) -> None:
+ path = tmp_path / "test-result-7070000000ABCDE.json"
+ path.write_text("" + _read("sample.apex.json"), encoding="utf-8")
+ report = parse_contexts_file(path)
+ assert report.source_format == "apex"
+ assert len(report.records) == 2
+
+
+def test_names_resolve_to_the_one_file_by_type() -> None:
+ res = resolve_reports([parse_apex(_read("sample.apex.json"))], KEYS)
+ # The trigger id picks AccountTrigger.trigger over the AccountTrigger.cls class.
+ assert set(res.coverage_map) == {
+ "force-app/main/default/classes/Trigger Recipes/AccountTriggerHandler.cls",
+ "force-app/main/default/triggers/AccountTrigger.trigger",
+ }
+ assert res.unmatched == [] and res.ambiguous == []
+
+
+def _report(*paths: str) -> CoverageReport:
+ files = [FileCoverage(p, 100.0, None, [1], 1, [1]) for p in paths]
+ return CoverageReport(source_format="apex", files=files)
+
+
+ "raw, expected",
+ [
+ # Apex names are case-insensitive.
+ ("accounttriggerhandler.cls", f"{CLASSES}/Trigger Recipes/AccountTriggerHandler.cls"),
+ ("LEGACY.cls", "src/classes/Legacy.cls"),
+ # The CLI's lcov / Cobertura fallback when it found no source file.
+ ("no-map/Legacy", "src/classes/Legacy.cls"),
+ ("Legacy", "src/classes/Legacy.cls"),
+ # A path the CLI did find resolves as any other report path.
+ (TRIGGER, TRIGGER),
+ # A bare name with no Apex file of that name keeps the ordinary suffix match.
+ ("Makefile", "tools/Makefile"),
+ ],
+)
+def test_resolution_matches(raw: str, expected: str) -> None:
+ res = resolve_reports([_report(raw)], KEYS)
+ assert list(res.coverage_map) == [expected]
+
+
+ "raw, ambiguous",
+ [
+ # Two files of one name, or a class and a trigger behind a bare name: never guessed.
+ ("Dup.cls", True),
+ ("no-map/AccountTrigger", True),
+ # No such file; a dotted or namespaced name is not a file name.
+ ("Missing.cls", False),
+ ("Outer.Inner", False),
+ ("ns__Legacy.cls", False),
+ ],
+)
+def test_resolution_refuses(raw: str, ambiguous: bool) -> None:
+ res = resolve_reports([_report(raw)], KEYS)
+ assert res.coverage_map == {}
+ assert (res.ambiguous if ambiguous else res.unmatched) == [raw]
+
+
+def test_per_test_records_resolve_source_and_test_file() -> None:
+ res = resolve_test_reports(parse_apex_contexts(_read("sample.apex.json")), KEYS)
+ test_file = "force-app/main/default/classes/Trigger Recipes/AccountTriggerHandler_Tests.cls"
+ assert [(r.file_path, r.test_file) for r in res.records] == [
+ ("force-app/main/default/classes/Trigger Recipes/AccountTriggerHandler.cls", test_file),
+ ("force-app/main/default/triggers/AccountTrigger.trigger", test_file),
+ ]
+ assert res.test_files_resolved == 2
+
+
+def test_discovers_cli_output(tmp_path: Path) -> None:
+ for rel in (
+ ".sfdx/tools/testresults/apex/test-result-codecoverage.json",
+ "tests/apex/test-result-codecoverage.json",
+ ):
+ (tmp_path / rel).parent.mkdir(parents=True)
+ (tmp_path / rel).write_text("[]", encoding="utf-8")
+ found = {p.relative_to(tmp_path).as_posix() for p in discover_artifacts(tmp_path)}
+ assert found == {
+ ".sfdx/tools/testresults/apex/test-result-codecoverage.json",
+ "tests/apex/test-result-codecoverage.json",
+ }
+
+
+def test_utf16_report_from_powershell_redirect_is_read(tmp_path: Path) -> None:
+ # Windows PowerShell 5.1 writes `sf ... --json > result.json` as UTF-16.
+ path = tmp_path / "result.json"
+ path.write_bytes(_read("sample.apex.json").encode("utf-16"))
+ assert len(parse_contexts_file(path).records) == 2
+ resolved, errors = build_coverage_map(tmp_path, [path], KEYS)
+ assert errors == []
+ assert len(resolved.coverage_map) == 2
+
+
+def test_test_file_stays_unset_when_the_test_class_does_not_resolve() -> None:
+ text = _read("sample.apex.json").replace("AccountTriggerHandler_Tests", "Dup")
+ res = resolve_test_reports(parse_apex_contexts(text), KEYS)
+ assert [r.test_file for r in res.records] == [None, None]
+ assert res.test_files_resolved == 0