Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(health): flag a test case that checks nothing (#2393)
Raghav Chamadiya7df326827cee
diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.mdindex 32553c99d..5b377da9f 100644--- a/docs/layers/CODE_HEALTH.md+++ b/docs/layers/CODE_HEALTH.md@@ -433,20 +433,41 @@ make a review verdict blocking.| Marker | Languages | What it measures ||---|---|---|+| `assertion_free_test` | Python · TypeScript / JavaScript | A test case that runs the code under test and checks nothing || `mock_saturated_test` | Python · TypeScript / JavaScript | Mock-setup statements per assertion in a test function |A marker earns weight by clearing the house precision bar (roughly 70%hand-labelled) on a real corpus. `mock_saturated_test` has not, and precision ismeasured per language because it does not transfer: **67%** on Python (32findings) and **40%** on TypeScript (30 findings), each the complete population-at the shipped gate. It stays advisory until two false-positive families are-separated: value-object builders named `Fake*` passed as input to real logic, and+at the shipped gate. Both figures predate the assertion count gaining the+oracle shapes listed in+[LANGUAGE_SUPPORT.md](LANGUAGE_SUPPORT.md#code-health-coverage), which grew this+marker's denominator on Python and TypeScript. A larger denominator lowers the+ratio, so the change can only suppress findings, never add one — but the two+numbers above were measured against the smaller denominator and are now a+ceiling rather than a current reading.++It stays advisory until two false-positive families are separated: value-object builders named `Fake*` passed as input to real logic, andboundary isolation where the assertion reads a real artifact. Both turn onwhether an assertion observes a double or production output, which is a dataflowquestion the pass does not ask — and on the TypeScript sample that one questionaccounted for every false positive.-Per-language coverage and why Go and Java are blocked:+`assertion_free_test` measures **52%** on TypeScript and **53%** on Python, and+does not report on Go or Java at all; the per-language reasoning is in+[LANGUAGE_SUPPORT.md](LANGUAGE_SUPPORT.md#code-health-coverage). It also declines+`.tsx` files, whose assertions the walk cannot currently see.++It asks a question with a yes-or-no answer rather than a+threshold, which is why it can be stated plainly: a test case whose assertion+count and verification count are both zero. A **mock verification counts as an+assertion here**, the opposite of the marker above it, because a test whose only+oracle is `verify(...)` does check something. The two markers read the same call+for two different questions; the tiers that keep them apart are in+`complexity/assertions.py`.++Per-language coverage, and why Go and Java are blocked for each marker:[LANGUAGE_SUPPORT.md](LANGUAGE_SUPPORT.md#code-health-coverage).## Performance riskdiff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.mdindex a0641577c..5b28a0d93 100644--- a/docs/layers/LANGUAGE_SUPPORT.md+++ b/docs/layers/LANGUAGE_SUPPORT.md@@ -355,23 +355,23 @@ Health markers run off a per-language walker map that is **independent** of`.scm` parsing: a language can parse perfectly for the graph and still need thismap before markers fire. This table is why a language is Full rather than Good.-| Language | Complexity / nesting | Class metrics | Assertion smells | Mock saturation | Extract Method | Performance risk |-|----------|:---:|:---:|:---:|:---:|:---:|:---:|-| Python | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |-| TypeScript / JavaScript | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |-| Svelte · Vue | ✅ | ✅ | ✅ | later | ✅ | ✅ |-| Java | ✅ | ✅ | ✅ | blocked | ✅ | ✅ |-| Go | ✅ | n/a | ✅ | blocked | ✅ | ✅ |-| Rust | ✅ | ✅ | ✅ | later | ✅ | ✅ |-| C++ | ✅ | ✅ | ✅ | later | ✅ | ✅ |-| C# | ✅ | ✅ | ✅ | later | later | ✅ |-| Kotlin | ✅ | ✅ | ✅ | later | blocked | ✅ |-| Scala | ✅ | ✅ | ✅ | later | later | ✅ |-| Ruby | ✅ | ✅ | ✅ | later | later | ✅ |-| Dart | ✅ | n/a | ✅ | later | later | ✅ |-| Object Pascal | ✅ | n/a | later | n/a | later | n/a |-| Razor | ✅ | n/a | n/a | n/a | later | ✅ |-| Shell | ✅ | n/a | n/a | n/a | n/a | n/a |+| Language | Complexity / nesting | Class metrics | Assertion smells | Mock saturation | Assertion-free test | Extract Method | Performance risk |+|----------|:---:|:---:|:---:|:---:|:---:|:---:|:---:|+| Python | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |+| TypeScript / JavaScript | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |+| Svelte · Vue | ✅ | ✅ | ✅ | later | later | ✅ | ✅ |+| Java | ✅ | ✅ | ✅ | blocked | blocked | ✅ | ✅ |+| Go | ✅ | n/a | ✅ | blocked | blocked | ✅ | ✅ |+| Rust | ✅ | ✅ | ✅ | later | later | ✅ | ✅ |+| C++ | ✅ | ✅ | ✅ | later | later | ✅ | ✅ |+| C# | ✅ | ✅ | ✅ | later | later | later | ✅ |+| Kotlin | ✅ | ✅ | ✅ | later | later | blocked | ✅ |+| Scala | ✅ | ✅ | ✅ | later | later | later | ✅ |+| Ruby | ✅ | ✅ | ✅ | later | later | later | ✅ |+| Dart | ✅ | n/a | ✅ | later | later | later | ✅ |+| Object Pascal | ✅ | n/a | later | n/a | n/a | later | n/a |+| Razor | ✅ | n/a | n/a | n/a | n/a | later | ✅ |+| Shell | ✅ | n/a | n/a | n/a | n/a | n/a | n/a |Every cell is a deliberate call, not an oversight: a language reaches a dialector it stays silent, and an `n/a` records a metric the language cannot carry@@ -423,12 +423,76 @@ honestly cannot carry the marker at all:marker looks for). An over-mocked Java test therefore arrives with one vacuous`assertDoesNotThrow` as its whole denominator, so the marker misses the testsit is for and the ratio peaks instead on large controller tests whose setup is- irreducible fixture. Java needs a verification vocabulary of its own first.- Measured at 20% precision over 30 hand-labelled findings, flat across every- threshold tried — but the mechanism above, not that number, is why it is- blocked, and why Java has no assertion row either: Mockito verification is- 1,080 lines over 299 test files, 16 of which hold no `assert*` at all, and- counting them here would blind the marker where it is meant to fire.+ irreducible fixture. Measured at 20% precision over 30 hand-labelled findings,+ flat across every threshold tried — but the mechanism above, not that number,+ is why it is blocked. Java now **does** carry a verification vocabulary, added+ for `assertion_free_test`, and it deliberately does not help here: Mockito+ verification is 1,087 calls over those 299 test files, and it reaches+ `verification_count` rather than `assertion_count` precisely so that this+ marker keeps dividing by state assertions alone.++**Assertion-free test** asks whether a test case checks anything at all, so it+needs two things the other markers do not: a per-function "is this a test case"+rule, and an assertion count that misses nothing. The rules live in+`analysis/health/complexity/test_case.py`, one data row per language — a name+prefix for Python, `go test`'s own case-sensitive `TestXxx` rule for Go, the+`it(...)` / `test(...)` callback for JS/TS, and `@Test` and its JUnit siblings+for Java. A language with no row classifies nothing. Go and Java are classified+and counted, which is how their precision below was measured, but the marker+does not report on them — the shipping set is a constant in the detector.++Measured precision, hand-labelled: **52%** on TypeScript (52 findings, the+complete population of two corpora) and **53%** on Python (30, a systematic+sample of 194). Both are below the 70% house bar and above the 40% at which+`mock_saturated_test` shipped TypeScript, and they ship on the same line: the+false positives are one family the marker declares, described below.++A **mock verification counts as an assertion for this marker and not for the one+above**, which is the deliberate inversion described in CODE_HEALTH.md. It+matters only for Java: Python's `assert_called_once`, jest's+`expect(m).toHaveBeenCalled()` and Go's `t.Error` already reach the narrow tier,+so Mockito is the one dialect where verification is invisible. On a 299-test-file+Java corpus it is 1,087 verifications, and counting them takes the marker from+146 findings to 28 — 118 tests that each had a real oracle — while introducing+none.++Counting a test's oracle turned out to be where the work was. Four forms reached+no tier at all before this. Each was found by reading findings that named an+oracle the counter had not seen, and each is answered at the broad tier so that+no calibrated run moves:++| Form | Example | Why it was missed |+|---|---|---|+| Context-manager oracle | `with pytest.raises(ValueError):` | The call is in the `with` header, not a statement |+| Split call shape | `Helpers.assertRejected(...)` | Java states a call as `object` + `name` and exposes no callee node |+| Property-terminated chain | `expect(x).to.be.null` | chai ends in a property, so the statement is not a call |+| Expression-bodied lambda | `it("x", () => expect(a).toBe(b))` | The body is the expression, so there is no statement to classify |++A private helper (`_assert_no_leak(msg)`) was a fifth: the narrow prefixes anchor+at the start of a name and a leading underscore breaks the anchor.++Firing rate fell as they landed — on a 794-test-file Python corpus from 13.0% of+its test cases to 3.7%, and on a 521-test-file TypeScript corpus from 1.6% to+0.4%. A rate is not a precision measurement; what these five changes are measured+to have done is stop the counter missing an oracle that was written down.++**Go and Java are blocked, and for the same structural reason rather than a+threshold.** Both languages conventionally delegate the oracle to a helper, and+the assertion count is per function, so the helper's assertions are invisible+from the test that calls it:++- **Go** — the idiom is to hand `*testing.T` to a helper that asserts, as in+ `parsertest.RunFileCases(t, ...)`. Measured on the findings themselves: **81 of+ 87** on one corpus and **119 of 121** on another pass the test handle to a+ call. That is not a false-positive family a marker can declare and live with,+ it is nearly the whole population, and suppressing on it would leave the marker+ firing a handful of times per repository.+- **Java** — the same shape without the handle, a helper on the test class that+ asserts on the test's behalf. Hand-labelled at **33%** over 18 findings, and 10+ of its 12 false positives were this family.++Separating them needs the assertions of a called function to reach its caller,+which is a cross-function question this pass does not ask.Svelte and Vue stay `later` rather than following TypeScript: an SFC is walked asa TypeScript buffer, but a single-file component is essentially never a testdiff --git a/packages/core/src/repowise/core/analysis/health/asserts/lexicon.py b/packages/core/src/repowise/core/analysis/health/asserts/lexicon.pyindex 395efc506..9ff391992 100644--- a/packages/core/src/repowise/core/analysis/health/asserts/lexicon.py+++ b/packages/core/src/repowise/core/analysis/health/asserts/lexicon.py@@ -9,8 +9,13 @@ walk, and they are deliberately not the same count:``large_assertion_block`` / ``duplicated_assertion_block`` read. It takesnothing from this file and nothing from user config.* the **broad** tier — narrow, plus the rows below and any name the repository- configures. It feeds ``assertion_count``, whose only reader is the advisory- ``mock_saturated_test``.+ configures. It feeds ``assertion_count``, read by the advisory+ ``mock_saturated_test`` and ``assertion_free_test``.+* the **verification** tier — :attr:`AssertDialect.verify_names`, counted apart+ into ``verification_count`` and never added to either count above. A mock+ verification is an oracle, so it answers "does this test check anything"; it+ is also the thing ``mock_saturated_test`` measures, so it must never enter+ that marker's denominator. Same call, opposite treatment, two questions.That split is the reason a row here can never move a score, and it is the onlyreason this file is safe to edit freely.@@ -80,6 +85,13 @@ class AssertDialect:#: and ``t.Log`` do not.receiver_methods: dict[str, frozenset[str]] = field(default_factory=dict)+ #: Exact lowercase names that make a call a *verification* — an assertion+ #: about a recorded call on a double rather than about state. Matched the+ #: same two ways as :attr:`assert_names`. Counted into ``verification_count``+ #: alone; see the tier list in the module docstring for why it is separate.+ #: Repository config never reaches this field, so it cannot be widened.+ verify_names: frozenset[str] = frozenset()+# ``testing.TB``'s failure reporters, keyed by the conventional receiver names.# Matched by receiver name and not by type, which the walker cannot resolve; in@@ -98,10 +110,31 @@ _GO = AssertDialect()-# Java has no row, and the omission is a result rather than a gap: its only real-# gap is Mockito verification, and a verification must not enter the count-# ``mock_saturated_test`` divides by, since a test built of mocks and verifies-# is the thing that marker measures. See LANGUAGE_SUPPORT.md#code-health-coverage.+# Java's whole gap is Mockito verification, which is why this row sets only+# ``verify_names``: its narrow tier already takes ``assertEquals`` / ``assertThat``.+# ``verifyZeroInteractions`` was removed in Mockito 4 and is still widespread.+# BDDMockito's ``then(mock).should()`` is taken on ``should``, which reaches this+# row as a receiver root.+_JAVA = AssertDialect(+ verify_names=frozenset(+ {+ "verify",+ "verifynointeractions",+ "verifynomoreinteractions",+ "verifyzerointeractions",+ "should",+ }+ ),+)+++# pytest's oracles that are context managers rather than calls. Receiver-scoped+# to ``pytest`` because ``raises`` / ``warns`` are ordinary English on anything+# else. ``unittest``'s equivalents need no row: ``assertRaises`` is already+# narrow, it was only ever the ``with`` header that hid it.+_PY = AssertDialect(+ receiver_methods={"pytest": frozenset({"raises", "warns", "deprecated_call", "fail"})},+)_JS_TS = AssertDialect(@@ -113,12 +146,13 @@ _JS_TS = AssertDialect(# Keyed by ``LanguageTag`` (``ingestion/models.py``), as ``LANGUAGE_MAPS`` and-# ``MOCK_DIALECTS`` are. Python has no row on purpose: the same survey found no-# gap in its narrow tier, and an unmeasured row is a guess.+# ``MOCK_DIALECTS`` are.ASSERT_DIALECTS: dict[str, AssertDialect] = {"go": _GO,+ "java": _JAVA,"javascript": _JS_TS,"jsx": _JS_TS,+ "python": _PY,"typescript": _JS_TS,"tsx": _JS_TS,}@@ -141,4 +175,5 @@ def assert_dialect(return AssertDialect(assert_names=dialect.assert_names | extra_names,receiver_methods=dialect.receiver_methods,+ verify_names=dialect.verify_names,)diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/assertion_free_test.py b/packages/core/src/repowise/core/analysis/health/biomarkers/assertion_free_test.pynew file mode 100644index 000000000..014449934--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/assertion_free_test.py@@ -0,0 +1,94 @@+"""Assertion Free Test: a test case that checks nothing.++A test that runs the code under test and then asserts nothing passes whatever+that code does. It reports coverage, it goes green on a broken build, and it+never fails the refactor it was written to protect. Meszaros names the smell+**Unknown Test**; TestLint and its descendants call it **Assertionless Test**.++It is the one marker in this family that is objectively decidable. The others+ask a question of degree and need a threshold nobody has calibrated; this one+asks whether a count is zero.++**A mock verification counts as an assertion here, and this is deliberately the+opposite of ``mock_saturated_test``.** Zhu et al. (FSE 2025,+doi:10.1145/3715741) measured that mock assertions catch faults state assertions+miss -- 782 of 1,557, at a Jaccard similarity of 32% -- and that verification+concentrates where state assertion is impossible, on external resources, state+mutators and callbacks. So a test whose only oracle is ``verify(...)`` does+check something, and calling it assertion-free would be wrong. The neighbouring+marker measures verification itself and so must exclude it from its denominator.+Same call, opposite treatment, two different questions. The tiers that keep them+apart are in ``complexity/assertions.py``.++**This marker is advisory and never deducts.** See ``ADVISORY_DIMENSION`` in+``scoring.py``, and LANGUAGE_SUPPORT.md#code-health-coverage for the measured+per-language precision and the false positives it does not separate.+"""++from __future__ import annotations++from ..coverage import is_test_file+from ..models import Severity+from .base import BiomarkerResult, FileContext++#: Languages the marker reports on. Go and Java are classified by+#: ``complexity/test_case.py`` and counted like any other, and are deliberately+#: absent here: both conventionally hand the oracle to a helper the test calls,+#: and the assertion count is per function, so the helper's assertions are+#: invisible from its caller. On Go that is not a false-positive family the+#: marker could declare and live with, it is nearly the whole population.+#: Figures and the reasoning: LANGUAGE_SUPPORT.md#code-health-coverage.+SHIPPING_LANGUAGES = frozenset({"javascript", "python", "tsx", "typescript"})+++class AssertionFreeTestDetector:+ name = "assertion_free_test"+ category = "test_quality"++ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:+ if ctx.language not in SHIPPING_LANGUAGES:+ return []+ if not is_test_file(ctx.file_path) or _jsx_parsed_without_jsx(ctx):+ return []+ out: list[BiomarkerResult] = []+ # ``all_functions``, not ``function_metrics``: name-keying collapses a+ # file's anonymous ``it`` callbacks into one row. See ``FileContext``.+ for fn in ctx.all_functions:+ # ``is_test_case`` is the whole gate. Every other test-quality+ # marker can lean on "it has assertions, so it is a test"; this one+ # is asking precisely the functions that have none.+ if not fn.is_test_case:+ continue+ if fn.assertion_count or fn.verification_count:+ continue+ out.append(+ BiomarkerResult(+ biomarker_type=self.name,+ severity=Severity.LOW,+ function_name=fn.name,+ line_start=fn.start_line,+ line_end=fn.end_line,+ details={"function": fn.name, "nloc": fn.nloc},+ reason=f"{fn.name} is a test case that asserts nothing",+ )+ )+ return out+++def _jsx_parsed_without_jsx(ctx: FileContext) -> bool:+ """Is this a ``.tsx`` file the walk parsed with the non-JSX grammar?++ ``walker.py`` passes the language tag straight to ``_get_language``, so a+ ``.tsx`` file — which arrives tagged ``typescript`` — is parsed by the+ grammar that cannot read JSX, and every assertion after the first element is+ lost. The root cause is that one call, which ``ingestion/parser.py`` already+ gets right; fixing it there also moves the calibrated block markers, which+ read low on these files today, so it is a change of its own. Until then this+ marker declines to call a test assertion-free on evidence it knows is+ missing. ``.jsx`` needs no guard: there is no jsx grammar, so those files are+ walked by tree-sitter-javascript, which reads JSX natively.+ """+ return ctx.file_path.endswith(".tsx") and ctx.language == "typescript"+++BIOMARKER = AssertionFreeTestDetector()diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py b/packages/core/src/repowise/core/analysis/health/biomarkers/base.pyindex 913f5e6fa..b8a56fee0 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/base.py@@ -31,7 +31,7 @@ class FileContext:function_metrics: dict[str, FunctionComplexity] = field(default_factory=dict)# Every walked function, in document order and NOT keyed by name, because# name-keying drops all but one of a file's anonymous ``it`` callbacks.- # Read only by ``mock_saturated_test``, which is advisory: re-keying+ # Read by the advisory test-quality markers only: re-keying# ``function_metrics`` is the real fix and would change what every# calibrated marker sees, so it needs its own defect-corpus evidence.all_functions: tuple[FunctionComplexity, ...] = ()diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/mock_saturated_test.py b/packages/core/src/repowise/core/analysis/health/biomarkers/mock_saturated_test.pyindex 9f972067c..35727a6ab 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/mock_saturated_test.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/mock_saturated_test.py@@ -52,8 +52,9 @@ class MockSaturatedTestDetector:for fn in ctx.all_functions:mocks = fn.mock_setup_countasserts = fn.assertion_count- # No assertion at all means a fixture or a helper, not a saturated- # test. A mock factory with no assertions is correct code.+ # No assertion at all is a different finding, not this one: it is+ # usually a fixture or a helper, and where it is a real test+ # ``assertion_free_test`` is the marker that says so.if mocks < self._MIN_MOCK_SETUP or asserts < 1:continueif prefixes and not fn.name.lower().startswith(prefixes):diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.pyindex 5fd173d98..e104456f5 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py@@ -12,6 +12,7 @@ from __future__ import annotationsfrom collections.abc import Sequencefrom .array_spread_in_reduce import ArraySpreadInReduceDetector+from .assertion_free_test import AssertionFreeTestDetectorfrom .base import Biomarker, BiomarkerResult, FileContextfrom .blocking_io_under_lock import BlockingIoUnderLockDetectorfrom .blocking_sync_in_async import BlockingSyncInAsyncDetector@@ -91,6 +92,7 @@ _DETECTOR_FACTORIES: list[type[Biomarker]] = [DuplicatedAssertionBlockDetector, # type: ignore[list-item]ErrorHandlingDetector, # type: ignore[list-item]# Advisory dimension - measured, never deducts (scoring.ADVISORY_DIMENSION).+ AssertionFreeTestDetector, # type: ignore[list-item]MockSaturatedTestDetector, # type: ignore[list-item]# Performance dimension (advisory weight; bounded by the perf cap).IoInLoopDetector, # type: ignore[list-item]diff --git a/packages/core/src/repowise/core/analysis/health/complexity/assertions.py b/packages/core/src/repowise/core/analysis/health/complexity/assertions.pyindex 6735e871a..8e093d0b8 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/assertions.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/assertions.py@@ -15,8 +15,15 @@ design (``asserts/lexicon.py`` carries the vocabulary and the evidence):or the language's own ``assert`` statement. The two block markers arecalibrated on it, so it takes no per-language and no user vocabulary, and abroad-only statement breaks a run exactly as a non-assertion always has.-* ``total`` counts the **broad** tier, which is narrow plus the language's- dialect. Its only reader is the advisory ``mock_saturated_test``.+* ``total`` counts the **broad** tier: narrow, plus the language's dialect,+ plus the assertion shapes the narrow tier structurally cannot see (a ``with``+ header, a property-terminated chain, a split call, a private helper). Its+ readers are the advisory ``mock_saturated_test`` and ``assertion_free_test``.+* ``verifications`` counts mock verifications, which are in neither count+ above. ``assertion_free_test`` asks whether a test checks anything, and a+ verification is an oracle, so it counts there; ``mock_saturated_test``+ measures verification itself, so counting it in that marker's denominator+ would blind it. The same call is read two ways on purpose."""from __future__ import annotations@@ -33,10 +40,13 @@ if TYPE_CHECKING:_EXPRESSION_STATEMENT = "expression_statement"_AWAIT_WRAPPER_KINDS = ("await_expression", "await", "parenthesized_expression")-# Assertion tiers. Narrow implies broad, so a statement carries one of three.+# Assertion tiers. Narrow implies broad. Verification is a fourth label rather+# than a stronger tier: these are names, not a rank, and nothing compares them+# by order._NOT_ASSERTION = 0_BROAD = 1_NARROW = 2+_VERIFICATION = 3def _callee_matches_assert(call_node: Node) -> bool:@@ -62,8 +72,70 @@ def _callee_matches_assert(call_node: Node) -> bool:return False-def _callee_matches_dialect(call_node: Node, dialect: AssertDialect) -> bool:- """True if *call_node* asserts in this language's broad vocabulary.+def _find_property_chain_call(stmt: Node, lmap: LanguageNodeMap) -> Node | None:+ """The call at the foot of a property-terminated chain, if any.++ chai and should.js end an assertion in a property rather than a call:+ ``expect(x).to.be.null`` is a member expression whose innermost object is+ the ``expect(x)`` call, so the statement is not a call node and every+ lookup above it declines. Descending the ``object`` field finds it, and a+ language whose grammar has no such field simply gets nothing.+ """+ return _descend_to_call(next((c for c in stmt.children if c.is_named), None), lmap)+++def _descend_to_call(node: Node | None, lmap: LanguageNodeMap) -> Node | None:+ """Unwrap ``await`` and walk a property chain down to the call at its foot."""+ while node is not None:+ if node.type in lmap.assert_call_kinds:+ return node+ if node.type in _AWAIT_WRAPPER_KINDS:+ node = next((c for c in node.children if c.is_named), None)+ continue+ node = node.child_by_field_name("object")+ return None+++def _split_callee_matches_assert(call_node: Node) -> bool:+ """An assert-ish name in a split call's ``name`` field.++ Java states a call as ``object`` + ``name`` and exposes no single callee+ node, so :func:`_callee_matches_assert` reaches only the receiver and misses+ ``TestUtils.assertStatusException(...)``. It is answered at the BROAD tier+ rather than in the narrow one on purpose: the narrow tier is what the+ calibrated block markers count, and admitting these names there was measured+ to move assertion runs. Promoting it is a calibrated change needing its own+ before/after. LANGUAGE_SUPPORT.md#code-health-coverage.+ """+ if call_node.child_by_field_name("function") is not None:+ return False+ name = call_node.child_by_field_name("name")+ if name is None or name.text is None:+ return False+ text = name.text.decode("utf-8", errors="replace").lower()+ return any(text.startswith(p) for p in NARROW_PREFIXES)+++def _private_callee_matches_assert(call_node: Node) -> bool:+ """An assert-ish callee behind a leading underscore.++ ``_assert_no_secret_leak(msg)`` is an assertion helper by any reading, but+ the narrow prefixes anchor at the start of the name and the underscore+ breaks the anchor, so the call went uncounted and the tests calling it read+ as assertion-free. Python marks a helper private this way constantly.+ Demoted to broad like the other shapes the narrow tier cannot see.+ """+ names = _callee_names(call_node)+ if names is None:+ return False+ called, roots = names+ return any(+ name.lstrip("_").startswith(NARROW_PREFIXES) for name in (called, *roots) if name+ )+++def _dialect_tier(call_node: Node, dialect: AssertDialect) -> int:+ """Broad-tier verdict: assertion, verification, or neither.Names are exact and read from both ends of the call, because a verificationreads either way round: ``verify(mock)`` is the callee, and in@@ -71,12 +143,18 @@ def _callee_matches_dialect(call_node: Node, dialect: AssertDialect) -> bool:"""names = _callee_names(call_node)if names is None:- return False+ return _NOT_ASSERTIONcalled, roots = namesverdict = _receiver_method_verdict(called, roots, dialect.receiver_methods)if verdict is not None:- return verdict- return called in dialect.assert_names or bool(roots & dialect.assert_names)+ # A listed receiver settles the call; it is exhaustive about its own+ # methods, so a decline here must not fall through to the name lists.+ return _BROAD if verdict else _NOT_ASSERTION+ if called in dialect.assert_names or roots & dialect.assert_names:+ return _BROAD+ if called in dialect.verify_names or roots & dialect.verify_names:+ return _VERIFICATION+ return _NOT_ASSERTIONdef _find_assert_call(stmt: Node, kinds: frozenset[str]) -> Node | None:@@ -99,8 +177,19 @@ def _find_assert_call(stmt: Node, kinds: frozenset[str]) -> Node | None:return None+def _find_context_manager_call(stmt: Node, lmap: LanguageNodeMap) -> Node | None:+ """An assertion-shaped call in a ``with`` header, body excluded."""+ stack = [c for c in stmt.children if c.is_named and c.type not in lmap.block_kinds]+ while stack:+ node = stack.pop()+ if node.type in lmap.assert_call_kinds:+ return node+ stack.extend(c for c in node.children if c.is_named and c.type not in lmap.block_kinds)+ return None++def _assertion_tier(stmt: Node, lmap: LanguageNodeMap, dialect: AssertDialect | None) -> int:- """The tier *stmt* asserts at: ``_NARROW``, ``_BROAD`` or ``_NOT_ASSERTION``.+ """The tier *stmt* asserts at, one of the four module constants.The broad tier is consulted only once the narrow one has declined, which iswhat keeps a language with no dialect classifying exactly as narrow alone.@@ -118,28 +207,64 @@ def _assertion_tier(stmt: Node, lmap: LanguageNodeMap, dialect: AssertDialect |call: Node | None = stmtelif stmt.type == _EXPRESSION_STATEMENT:call = _find_assert_call(stmt, lmap.assert_call_kinds)+ if call is None:+ # A property-terminated assertion is capped at broad for the same+ # reason as the split shape: the narrow tier is what the calibrated+ # block markers count.+ chained = _find_property_chain_call(stmt, lmap)+ if chained is not None:+ return _tier_without_narrow(chained, dialect)+ elif stmt.type in lmap.with_kinds:+ # ``with pytest.raises(...)`` / ``with self.assertRaises(...)`` is the+ # oracle, but the call sits in the header rather than in a statement of+ # its own, so every tier above misses it.+ call = _find_context_manager_call(stmt, lmap)+ return _NOT_ASSERTION if call is None else _tier_without_narrow(call, dialect)else:return _NOT_ASSERTIONif call is None:return _NOT_ASSERTIONif _callee_matches_assert(call):return _NARROW- if dialect is not None and _callee_matches_dialect(call, dialect):+ if _split_callee_matches_assert(call) or _private_callee_matches_assert(call):return _BROAD+ if dialect is not None:+ return _dialect_tier(call, dialect)return _NOT_ASSERTION+def _tier_without_narrow(call: Node, dialect: AssertDialect | None) -> int:+ """Classify *call*, demoting a narrow verdict to ``_BROAD``.++ Used for the assertion shapes the narrow tier structurally cannot see: a+ ``with`` header and a property-terminated chain. A narrow verdict for either+ would let it join an assertion *run*, and runs are what the calibrated block+ markers read. Capping at broad keeps those byte-identical while the total+ still sees the oracle.+ """+ if _callee_matches_assert(call):+ return _BROAD+ if dialect is None:+ return _NOT_ASSERTION+ return _dialect_tier(call, dialect)++def _is_assertion_statement(stmt: Node, lmap: LanguageNodeMap, dialect: AssertDialect | None = None) -> bool:- """True if *stmt* is a test assertion at the broad tier."""- return _assertion_tier(stmt, lmap, dialect) != _NOT_ASSERTION+ """True when *stmt* is an assertion, in either assertion tier.++ A verification is deliberately excluded: ``mock_walk`` calls this to keep+ assertions out of its mock-setup count, and a verification is exactly what+ ``mock_saturated_test`` means by mock setup.+ """+ return _assertion_tier(stmt, lmap, dialect) in (_NARROW, _BROAD)def _collect_assertion_facts(body_node: Node, lmap: LanguageNodeMap, dialect: AssertDialect | None = None-) -> tuple[list[tuple[int, int, int]], int]:- """``(blocks, total)`` assertion facts for one function body.+) -> tuple[list[tuple[int, int, int]], int, int]:+ """``(blocks, total, verifications)`` assertion facts for one function body.*blocks* are runs of ≥2 consecutive **narrow-tier** assertion statements,each recorded as ``(start_line, end_line, count)``. Runs are found per@@ -156,14 +281,18 @@ def _collect_assertion_facts(double-count every assertion in a language whose ``assert_call_kinds`` isits plain call node. Block level also makes it commensurable with``mock_walk._count_body_setup``.++ *verifications* counts mock verifications, on the same block-level gate as+ *total* and in neither of the other two counts. See the module docstring."""if not lmap.assert_kinds and not lmap.assert_call_kinds:- return [], 0+ return [], 0, 0blocks: list[tuple[int, int, int]] = []total = 0+ verifications = 0def _scan_siblings(parent: Node, *, count_total: bool) -> None:- nonlocal total+ nonlocal total, verificationsrun_start = 0run_end = 0run_count = 0@@ -171,8 +300,11 @@ def _collect_assertion_facts(if not child.is_named:continuetier = _assertion_tier(child, lmap, dialect)- if count_total and tier != _NOT_ASSERTION:- total += 1+ if count_total:+ if tier == _VERIFICATION:+ verifications += 1+ elif tier != _NOT_ASSERTION:+ total += 1if tier == _NARROW:if run_count == 0:run_start = child.start_point[0] + 1@@ -186,11 +318,33 @@ def _collect_assertion_facts(blocks.append((run_start, run_end, run_count))def _visit(node: Node) -> None:- _scan_siblings(node, count_total=node is body_node or node.type in lmap.block_kinds)+ # Lambda kinds join the block kinds because an expression-bodied arrow+ # has no statement at all: ``waitFor(() => expect(x).toBe(1))`` keeps+ # its assertion directly under the arrow. Run detection below is+ # unconditional and so is untouched by this.+ counts_here = (+ node is body_node+ or node.type in lmap.block_kinds+ or node.type in lmap.lambda_kinds+ )+ _scan_siblings(node, count_total=counts_here)for child in node.children:if child.type in lmap.function_kinds:continue # nested fn, not collected as its own entry either_visit(child)_visit(body_node)- return blocks, total+ # A lambda with an expression body holds no statement: ``it("x", () =>+ # expect(a).toBe(b))`` puts the assertion where only the body node itself+ # sits, so the sibling scan above never sees it. Classified here, demoted to+ # broad like the other shapes, and it cannot form a run because a run needs+ # two siblings.+ if body_node.type not in lmap.block_kinds and lmap.assert_call_kinds:+ call = _descend_to_call(body_node, lmap)+ if call is not None:+ tier = _tier_without_narrow(call, dialect)+ if tier == _VERIFICATION:+ verifications += 1+ elif tier != _NOT_ASSERTION:+ total += 1+ return blocks, total, verificationsdiff --git a/packages/core/src/repowise/core/analysis/health/complexity/models.py b/packages/core/src/repowise/core/analysis/health/complexity/models.pyindex cae4529c1..993301a4f 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/models.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/models.py@@ -52,9 +52,15 @@ class FunctionComplexity:# Every assertion statement in the body, runs or not. Same per-language# opt-in as ``assertion_blocks``.assertion_count: int = 0+ # Mock verifications in the body, counted apart from ``assertion_count``.+ # Why they are separate: ``asserts/lexicon.py``.+ verification_count: int = 0# Mock-setup statements in the body, decorators included. 0 for a language# with no entry in ``analysis/health/mocks/lexicon.py``.mock_setup_count: int = 0+ # True when this function is a test case its framework would run, as+ # opposed to a helper or fixture beside it. ``complexity/test_case.py``.+ is_test_case: bool = Falsedef __post_init__(self) -> None:if self.complex_conditions is None:diff --git a/packages/core/src/repowise/core/analysis/health/complexity/test_case.py b/packages/core/src/repowise/core/analysis/health/complexity/test_case.pynew file mode 100644index 000000000..147bc5c16--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/complexity/test_case.py@@ -0,0 +1,151 @@+"""Is one walked function a test case its framework would run?++The walker has always known whether a *file* is a test. Nothing knew whether a+*function* was, because every marker that needed to ask could lean on something+else: ``mock_saturated_test`` skips a function with no assertions at all, and+calls that a fixture. ``assertion_free_test`` inverts exactly that predicate, so+it inherits none of that protection and needs the real question answered.++Each language answers it a different way, and a row states which way:++* a **name prefix** (Python's ``test_``, Go's ``TestXxx``),+* a **callback callee**, for a framework whose cases are anonymous functions+ passed to ``it(...)`` / ``test(...)``,+* an **annotation**, for JUnit, which puts the answer in ``@Test``.++A name-prefix or callback-callee language is one row and nothing else. An+annotation language is not: ``_annotation_names`` reads Java's ``modifiers``+subtree, so a language that spells annotations differently (C#'s+``[Fact]`` under ``attribute_list``) needs that function taught the shape as+well as a row.++Three deliberate exclusions, each of which would otherwise be a false positive+the marker could never defend:++* Go's ``BenchmarkXxx`` / ``FuzzXxx`` / ``ExampleXxx``. A benchmark has nothing+ to assert, and an ``Example``'s oracle is its ``// Output:`` comment.+* ``describe`` / ``beforeEach`` and their kin. A suite callback is already+ transparent to the walker (``ast_utils._is_test_suite_callback``); a setup+ callback is a real function entry, and it is a fixture, not a case.+* Anything with no row: a language absent from :data:`TEST_CASE_DIALECTS`+ classifies nothing, so it produces no finding rather than a guess.++The verdict depends on the function node and the language, never on the file+path — ``HealthWalkCache`` keys on language and bytes, so a path-derived field+would be served from a byte-identical file elsewhere in the tree. The test-file+gate stays in the biomarker, which sees ``ctx.file_path``.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from tree_sitter import Node++#: Suffix ``ast_utils._find_function_entry_name`` gives a callback entry, as in+#: ``"it callback"``. The text before it is the callee, arguments included.+_CALLBACK_SUFFIX = " callback"++_JAVA_MODIFIERS = "modifiers"+_JAVA_ANNOTATION_KINDS = ("marker_annotation", "annotation")+++@dataclass(frozen=True)+class TestCaseDialect:+ """How one language marks a function as a test case. Data only."""++ #: Name prefixes matched case-INSENSITIVELY, which is what pytest's default+ #: ``python_functions = test*`` does.+ name_prefixes: tuple[str, ...] = ()++ #: Name prefixes matched case-SENSITIVELY, where the character after the+ #: prefix must not be lowercase. This is ``go test``'s own rule for+ #: ``TestXxx``, and it is what separates the test ``TestParse`` from the+ #: helper ``testScanner`` sitting beside it in the same file.+ runner_prefixes: tuple[str, ...] = ()++ #: Lowercase callee names whose callback argument is a case. Matched against+ #: the first dotted segment, so ``it.each(...)`` and ``it.skip`` both count.+ callback_callees: frozenset[str] = frozenset()++ #: Lowercase annotation names, last dotted segment only, so a fully+ #: qualified ``@org.junit.jupiter.api.Test`` matches the same row.+ annotations: frozenset[str] = frozenset()++ #: Exact names a rule above would otherwise claim. Go's ``TestMain`` matches+ #: ``TestXxx`` but is the test binary's entry point, not a case.+ excluded_names: frozenset[str] = frozenset()+++_PY = TestCaseDialect(name_prefixes=("test",))++# Go's convention is the test binary's own rule, so it is exact rather than a+# guess. ``Benchmark`` / ``Fuzz`` / ``Example`` are excluded above.+_GO = TestCaseDialect(runner_prefixes=("Test",), excluded_names=frozenset({"TestMain"}))++_JS_TS = TestCaseDialect(callback_callees=frozenset({"it", "test", "specify"}))++# JUnit 5 plus JUnit 4's ``@Test``, which shares the name. ``@Disabled`` is not+# excluded: a disabled test is still a test, and whether it checks anything is+# still worth knowing.+_JAVA = TestCaseDialect(+ annotations=frozenset(+ {"test", "parameterizedtest", "repeatedtest", "testfactory", "testtemplate"}+ )+)++#: Keyed by ``LanguageTag``, as the sibling lexicons are.+TEST_CASE_DIALECTS: dict[str, TestCaseDialect] = {+ "go": _GO,+ "java": _JAVA,+ "javascript": _JS_TS,+ "python": _PY,+ "typescript": _JS_TS,+ "tsx": _JS_TS,+}+++def _annotation_names(fn_node: Node) -> set[str]:+ """Lowercase last segments of the annotations on *fn_node*."""+ modifiers = next((c for c in fn_node.children if c.type == _JAVA_MODIFIERS), None)+ if modifiers is None:+ return set()+ names: set[str] = set()+ for child in modifiers.children:+ if child.type not in _JAVA_ANNOTATION_KINDS:+ continue+ name = child.child_by_field_name("name")+ if name is None or name.text is None:+ continue+ names.add(name.text.decode("utf-8", errors="replace").rsplit(".", 1)[-1].lower())+ return names+++def _matches_runner_prefix(name: str, prefixes: tuple[str, ...]) -> bool:+ """``TestXxx`` but not ``testScanner``: exact case, no lowercase after."""+ for prefix in prefixes:+ if name.startswith(prefix) and not name[len(prefix) : len(prefix) + 1].islower():+ return True+ return False+++def is_test_case(fn_node: Node, name: str, language: str) -> bool:+ """True when *fn_node* is a test case the language's runner would collect."""+ dialect = TEST_CASE_DIALECTS.get(language)+ if dialect is None or name in dialect.excluded_names:+ return False+ lowered = name.lower()+ if lowered.endswith(_CALLBACK_SUFFIX):+ if not dialect.callback_callees:+ return False+ callee = lowered[: -len(_CALLBACK_SUFFIX)]+ # ``it.each([1,2])`` carries its arguments in the entry name; the first+ # dotted segment is the framework function in every form of it.+ return callee.split(".", 1)[0].split("(", 1)[0] in dialect.callback_callees+ if dialect.name_prefixes and lowered.startswith(dialect.name_prefixes):+ return True+ if _matches_runner_prefix(name, dialect.runner_prefixes):+ return True+ return bool(dialect.annotations) and bool(dialect.annotations & _annotation_names(fn_node))diff --git a/packages/core/src/repowise/core/analysis/health/complexity/walker.py b/packages/core/src/repowise/core/analysis/health/complexity/walker.pyindex 7b4762aac..0ba73d59c 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py@@ -26,6 +26,7 @@ drives the individual passes, each of which lives in its own sibling module:- ``nloc``: non-blank / non-comment line counting- ``cyclomatic``: the CCN / cognitive / nesting engine- ``assertions``: assertion blocks + per-function assertion totals+- ``test_case``: whether a walked function is a test case- ``mock_walk``: per-function mock-setup counting (test-quality)- ``error_handling``: error-handling anti-patterns- ``perf_walk``: the performance-risk pass@@ -51,6 +52,7 @@ from .cyclomatic import _walk_function_bodyfrom .error_handling import _collect_error_handling, _eh_rust_attr_is_testfrom .languages import get_language_mapfrom .mock_walk import _count_mock_setup, file_may_contain_mocks+from .test_case import is_test_caseif TYPE_CHECKING:from tree_sitter import Node@@ -156,9 +158,12 @@ def walk_file(for fn_node in _collect_function_nodes(tree.root_node, lmap):body = fn_node.child_by_field_name("body") or fn_nodeccn, max_nest, cognitive, bumps, conditions = _walk_function_body(body, lmap)- assertion_blocks, assertion_count = _collect_assertion_facts(body, lmap, asserts)+ assertion_blocks, assertion_count, verifications = _collect_assertion_facts(+ body, lmap, asserts+ )+ name = _find_function_entry_name(fn_node, lmap)fc = FunctionComplexity(- name=_find_function_entry_name(fn_node, lmap),+ name=name,start_line=fn_node.start_point[0] + 1,end_line=fn_node.end_point[0] + 1,ccn=ccn,@@ -170,7 +175,9 @@ def walk_file(complex_conditions=conditions,assertion_blocks=assertion_blocks,assertion_count=assertion_count,+ verification_count=verifications,mock_setup_count=_count_mock_setup(fn_node, body, lmap, mock_dialect, asserts),+ is_test_case=is_test_case(fn_node, name, language),)functions.append(fc)fc_by_node_id[fn_node.id] = fcdiff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.pyindex 3cc35fa0e..517579175 100644--- a/packages/core/src/repowise/core/analysis/health/engine.py+++ b/packages/core/src/repowise/core/analysis/health/engine.py@@ -100,7 +100,17 @@ log = structlog.get_logger(__name__)# Not a licence to move a calibrated scoring weight — those are frozen# independently of this stamp.#-# Current stamp: the assertion count gained a per-language broad tier, so a Go+# Current stamp: ``assertion_free_test`` landed, and the walker records two new+# ``FunctionComplexity`` fields for it (``verification_count``, ``is_test_case``)+# that a cached v14 walk does not carry. It also widens ``assertion_count`` in+# every language that counts assertions at all -- a ``with`` header, a+# property-terminated chain, a lambda body, a private ``_assert*`` helper and+# Java's split call shape all reach the broad tier now -- so the advisory+# ``mock_saturated_test`` divides by a different, larger denominator than a v14+# walk stored. The narrow tier the calibrated block markers read is unchanged,+# verified run-for-run against v14 on four corpora, so no score moves.+#+# v14: the assertion count gained a per-language broad tier, so a Go# or JS/TS file's ``assertion_count`` changes from what a cached v13 walk stored# for it. The narrow tier the calibrated block markers read is unchanged, so no# score moves; this stamp is what re-walks the files whose advisory denominator@@ -134,7 +144,7 @@ log = structlog.get_logger(__name__)# forms. Files that were counted untested and are not become tested, which# moves untested-hotspot findings and the scores that carry them, on every# language with a prefix or spec convention rather than Ruby alone.-HEALTH_ANALYZER_VERSION = 14+HEALTH_ANALYZER_VERSION = 15# Method-level smells that make the dataflow / Extract Method pass worthwhile.# Only files carrying one of these get a CFG + def/use + reaching pass built.diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.pyindex e6d5a6484..ef4b84f16 100644--- a/packages/core/src/repowise/core/analysis/health/scoring.py+++ b/packages/core/src/repowise/core/analysis/health/scoring.py@@ -181,6 +181,7 @@ _BIOMARKER_CATEGORY: dict[str, str] = {"duplicated_assertion_block": "test_quality",# Never reaches a deduction; mapped so category-grouped surfaces do not# file it under the ``size_and_complexity`` default.+ "assertion_free_test": "test_quality","mock_saturated_test": "test_quality","error_handling": "error_handling",# Governance biomarkers - written by the additive governance pass@@ -284,6 +285,7 @@ _BIOMARKER_DIMENSIONS: dict[str, set[str]] = {"sql_cartesian_join": {"performance"},# Advisory. Must also appear in ``_ADVISORY_HOME``: the two tables are# independent, and a marker in only one of them still deducts from defect.+ "assertion_free_test": {ADVISORY_DIMENSION},"mock_saturated_test": {ADVISORY_DIMENSION},}@@ -491,7 +493,7 @@ _PERFORMANCE_HOME: frozenset[str] = frozenset(# The display half of the pairing above; ``test_advisory_dimension.py`` locks# the two together for every registered biomarker.-_ADVISORY_HOME: frozenset[str] = frozenset({"mock_saturated_test"})+_ADVISORY_HOME: frozenset[str] = frozenset({"assertion_free_test", "mock_saturated_test"})def severity_deduction(sev: Severity) -> float:diff --git a/packages/ui/src/health/biomarker-glossary.ts b/packages/ui/src/health/biomarker-glossary.tsindex c9f89d229..cb7315e65 100644--- a/packages/ui/src/health/biomarker-glossary.ts+++ b/packages/ui/src/health/biomarker-glossary.ts@@ -202,6 +202,12 @@ export const BIOMARKER_GLOSSARY: Record<string, BiomarkerInfo> = {description:"A test function running a long unbroken run of assertions. When one fails, the rest never execute — split into focused cases.",},+ assertion_free_test: {+ label: "Assertion free test",+ category: "test_quality",+ description:+ "A test case that runs the code under test and then checks nothing, so it passes whatever that code does. A mock verification counts as a check. Advisory: it costs this file no points.",+ },mock_saturated_test: {label: "Mock saturated test",category: "test_quality",@@ -368,7 +374,10 @@ export type BiomarkerDimension = "defect" | "maintainability" | "performance" |* chip has to say so rather than borrowing the defect pillar's label. Mirror of* ``_ADVISORY_HOME`` in core's `scoring.py`.*/-export const ADVISORY_HOME_BIOMARKERS: ReadonlySet<string> = new Set(["mock_saturated_test"]);+export const ADVISORY_HOME_BIOMARKERS: ReadonlySet<string> = new Set([+ "assertion_free_test",+ "mock_saturated_test",+]);/*** The biomarkers whose "home" pillar is maintainability: the smells the defectdiff --git a/tests/unit/health/test_assertion_free_test.py b/tests/unit/health/test_assertion_free_test.pynew file mode 100644index 000000000..7f14d0abf--- /dev/null+++ b/tests/unit/health/test_assertion_free_test.py@@ -0,0 +1,442 @@+"""``assertion_free_test``: a test case that checks nothing.++Real source is driven through the walker rather than hand-built+``FunctionComplexity`` rows, as the sibling test-quality suites do: the failures+worth catching here are grammar-shaped, and a hand-built row would assert only+that the biomarker compares two integers.++The load-bearing case is the Java one. A mock verification must count as an+oracle here and must NOT count as one for ``mock_saturated_test``, so the two+suites pin the same call to opposite verdicts on purpose.+"""++from __future__ import annotations++import pytest++from repowise.core.analysis.health.biomarkers.assertion_free_test import BIOMARKER+from repowise.core.analysis.health.biomarkers.base import FileContext+from repowise.core.analysis.health.complexity import walk_file+++def _require(language: str) -> None:+ try:+ from repowise.core.ingestion.parser import _get_language+ except Exception:+ pytest.skip(f"tree-sitter language pack missing for {language}")+ if _get_language(language) is None:+ pytest.skip(f"tree-sitter language pack missing for {language}")+++def _detect(source: str, path: str = "tests/test_sample.py", language: str = "python"):+ fc = walk_file(path, language, source.encode("utf-8"))+ ctx = FileContext(+ file_path=path,+ language=language,+ nloc=fc.file_nloc,+ has_test_file=True,+ module=None,+ function_metrics={f.name: f for f in fc.functions},+ all_functions=tuple(fc.functions),+ )+ return BIOMARKER.detect(ctx)+++def _flagged(source: str, path: str = "tests/test_sample.py", language: str = "python"):+ return sorted(f.function_name for f in _detect(source, path, language))+++def _counts(source: str, path: str, language: str) -> dict[str, tuple[int, int, bool]]:+ """``{function: (assertion_count, verification_count, is_test_case)}``."""+ fc = walk_file(path, language, source.encode("utf-8"))+ return {f.name: (f.assertion_count, f.verification_count, f.is_test_case) for f in fc.functions}+++# --------------------------------------------------------------------------+# Which functions are test cases at all+# --------------------------------------------------------------------------+++def test_python_helpers_and_fixtures_are_not_test_cases() -> None:+ _require("python")+ counts = _counts(+ "def test_bare():\n"+ " do_thing()\n"+ "\n"+ "def helper():\n"+ " return 1\n"+ "\n"+ "class TestThing:\n"+ " def setUp(self):\n"+ " self.x = 1\n"+ "\n"+ " def test_method(self):\n"+ " self.assertEqual(1, 1)\n",+ "tests/test_sample.py",+ "python",+ )+ assert counts["test_bare"][2] is True+ assert counts["test_method"][2] is True+ assert counts["helper"][2] is False+ assert counts["setUp"][2] is False+++def test_go_counts_only_test_functions() -> None:+ _require("go")+ counts = _counts(+ "package p\n"+ "\n"+ "func TestBare(t *testing.T) { doThing() }\n"+ "func Test_table_driven(t *testing.T) { doThing() }\n"+ "func BenchmarkX(b *testing.B) { doThing() }\n"+ "func ExampleY() { fmt.Println(1) }\n"+ "func testScanner() Scanner { return nil }\n"+ "func TestingHelper() int { return 1 }\n"+ "func helper(t *testing.T) int { return 1 }\n",+ "pkg/thing_test.go",+ "go",+ )+ # A benchmark has nothing to assert and an Example's oracle is its output+ # comment, so neither is a case this marker can judge.+ assert counts["TestBare"][2] is True+ assert counts["Test_table_driven"][2] is True+ assert counts["BenchmarkX"][2] is False+ assert counts["ExampleY"][2] is False+ assert counts["helper"][2] is False+ # ``go test`` runs ``TestXxx`` only when Xxx does not start lowercase, so+ # these two are helpers the runner never collects. Matching them+ # case-insensitively was measurably the largest Go false positive.+ assert counts["testScanner"][2] is False+ assert counts["TestingHelper"][2] is False+++def test_js_suite_and_setup_callbacks_are_not_test_cases() -> None:+ _require("typescript")+ source = (+ 'describe("S", () => {\n'+ " beforeEach(() => { jest.resetAllMocks(); });\n"+ ' it("checks", () => { expect(s.send).toHaveBeenCalled(); });\n'+ ' it("bare", async () => { await s.send(m); });\n'+ ' it.each([1, 2])("param %i", (n) => { expect(n).toBe(n); });\n'+ ' test("bare too", () => { doThing(); });\n'+ " function localHelper() { return 1; }\n"+ "});\n"+ )+ fc = walk_file("src/x.test.ts", "typescript", source.encode("utf-8"))+ cases = {f.name for f in fc.functions if f.is_test_case}+ assert "beforeEach callback" not in cases+ assert "localHelper" not in cases+ assert "it callback" in cases+ assert "test callback" in cases+ # ``it.each([1,2])`` carries its arguments in the entry name; the first+ # dotted segment is still the framework function.+ assert "it.each([1, 2]) callback" in cases+++def test_a_language_with_no_row_classifies_nothing() -> None:+ _require("ruby")+ source = "def test_bare\n do_thing\nend\n"+ fc = walk_file("spec/thing_spec.rb", "ruby", source.encode("utf-8"))+ assert [f.is_test_case for f in fc.functions] == [False]+ assert _flagged(source, "spec/thing_spec.rb", "ruby") == []+++def test_is_test_case_does_not_read_the_path() -> None:+ _require("python")+ # ``HealthWalkCache`` keys on language and bytes with no path component, so+ # a path-derived field would be served from a byte-identical file elsewhere.+ body = b"def test_bare():\n do()\n"+ in_tests = walk_file("tests/test_a.py", "python", body)+ in_src = walk_file("src/prod.py", "python", body)+ assert [f.is_test_case for f in in_tests.functions] == [True]+ assert [f.is_test_case for f in in_src.functions] == [True]+++# --------------------------------------------------------------------------+# The detector+# --------------------------------------------------------------------------+++def test_fires_on_a_test_that_asserts_nothing() -> None:+ _require("python")+ findings = _detect("def test_bare():\n service.do_it()\n")+ assert [f.biomarker_type for f in findings] == ["assertion_free_test"]+ assert findings[0].function_name == "test_bare"+ assert findings[0].details["function"] == "test_bare"+++def test_silent_when_the_test_asserts() -> None:+ _require("python")+ assert _flagged("def test_ok():\n assert 1 == 1\n") == []+++def test_silent_on_a_production_file() -> None:+ _require("python")+ assert _flagged("def test_bare():\n do_thing()\n", "src/pkg/module.py", "python") == []+++def test_silent_on_a_helper_with_no_assertions() -> None:+ _require("python")+ assert _flagged("def build_user():\n return User()\n") == []+++def test_context_manager_oracles_count() -> None:+ _require("python")+ # The call sits in the ``with`` header rather than in a statement of its+ # own, which hid it from every tier. It is the dominant Python false+ # positive this marker would otherwise report.+ source = (+ "import pytest\n"+ "\n"+ "def test_pytest_raises():\n"+ " with pytest.raises(ValueError):\n"+ " boom()\n"+ "\n"+ "def test_unittest_raises(self):\n"+ " with self.assertRaises(ValueError):\n"+ " boom()\n"+ )+ assert _flagged(source) == []+++def test_a_with_block_never_joins_an_assertion_run() -> None:+ _require("python")+ # Runs are what the calibrated block markers read, so a ``with`` header is+ # capped at the broad tier and must break a run exactly as it always has.+ source = (+ "import pytest\n"+ "\n"+ "def test_runs():\n"+ " assert a == 1\n"+ " with pytest.raises(ValueError):\n"+ " boom()\n"+ " assert b == 2\n"+ )+ fc = walk_file("tests/test_sample.py", "python", source.encode("utf-8"))+ assert fc.functions[0].assertion_blocks == []+++# --------------------------------------------------------------------------+# Verification is an oracle here and is not one next door+# --------------------------------------------------------------------------+++def test_java_verify_only_test_is_not_assertion_free() -> None:+ _require("java")+ source = (+ "class FooTest {\n"+ " @Test void verifyOnly() { verify(sender).send(m); }\n"+ " @Test void bddVerifyOnly() { then(sender).should().send(m); }\n"+ " @Test void noMoreInteractions() { verifyNoMoreInteractions(sender); }\n"+ " @Test void bare() { service.doIt(); }\n"+ "}\n"+ )+ counts = _counts(source, "src/test/java/FooTest.java", "java")+ # Java is classified and counted but never reported (see the gate test+ # below); what must hold is that each verify-only test carries an oracle.+ assert counts["verifyOnly"][1] == 1+ assert counts["bddVerifyOnly"][1] == 1+ assert counts["noMoreInteractions"][1] == 1+ assert counts["bare"][:2] == (0, 0)+++def test_java_verification_stays_out_of_the_assertion_count() -> None:+ _require("java")+ counts = _counts(+ "class FooTest {\n"+ " @Test void verifyOnly() { verify(sender).send(m); }\n"+ " @Test void assertOnly() { assertEquals(1, 2); }\n"+ "}\n",+ "src/test/java/FooTest.java",+ "java",+ )+ # The count ``mock_saturated_test`` divides by must not gain the+ # verification, or that marker goes blind on exactly the tests it targets.+ assert counts["verifyOnly"] == (0, 1, True)+ assert counts["assertOnly"] == (1, 0, True)+++def test_java_annotation_forms_all_register() -> None:+ _require("java")+ source = (+ "class FooTest {\n"+ " @Test void plain() { doIt(); }\n"+ " @org.junit.jupiter.api.Test void qualified() { doIt(); }\n"+ " @ParameterizedTest @ValueSource(ints = {1}) void parameterized(int n) { doIt(); }\n"+ " @Disabled @Test void disabled() { doIt(); }\n"+ " private void helper() { int x = 1; }\n"+ "}\n"+ )+ counts = _counts(source, "src/test/java/FooTest.java", "java")+ assert {name for name, row in counts.items() if row[2]} == {+ "disabled",+ "parameterized",+ "plain",+ "qualified",+ }+++def test_go_subtest_assertions_belong_to_the_parent() -> None:+ _require("go")+ # A table-driven test asserts inside a ``t.Run`` closure, which is not its+ # own entry, so the parent must carry the assertion or every table test in+ # the language reads as assertion-free.+ source = (+ "package p\n"+ "\n"+ "func TestTable(t *testing.T) {\n"+ "\tfor _, tc := range cases {\n"+ "\t\tt.Run(tc.name, func(t *testing.T) {\n"+ "\t\t\tif got != tc.want {\n"+ '\t\t\t\tt.Errorf("bad")\n'+ "\t\t\t}\n"+ "\t\t})\n"+ "\t}\n"+ "}\n"+ )+ assert _flagged(source, "pkg/thing_test.go", "go") == []+++def test_a_concise_arrow_body_is_the_assertion() -> None:+ _require("typescript")+ # ``it("x", () => expect(a).toBe(b))`` holds no statement at all, so the+ # sibling scan never sees the assertion and the test read as bare.+ source = (+ 'describe("S", () => {\n'+ ' it("concise", () => expect(add(1, 2)).toBe(3));\n'+ ' it("concise chai", () => expect(x).to.be.null);\n'+ ' it("concise await", async () => await expect(p).to.be.fulfilled);\n'+ ' it("bare", () => doThing());\n'+ "});\n"+ )+ assert _flagged(source, "src/x.test.ts", "typescript") == ["it callback"]+++def test_chai_property_assertions_count() -> None:+ _require("typescript")+ # ``expect(x).to.be.null`` ends in a property, so the statement is a member+ # expression and not a call, and every lookup above it declines. It was the+ # largest TypeScript false positive.+ source = (+ 'describe("S", () => {\n'+ ' it("null", () => { expect(content).to.be.null });\n'+ ' it("true", () => { expect(ok).to.be.true });\n'+ ' it("bare", () => { doThing(); });\n'+ "});\n"+ )+ assert _flagged(source, "src/x.test.ts", "typescript") == ["it callback"]+++def test_property_assertions_never_join_an_assertion_run() -> None:+ _require("typescript")+ source = (+ 'describe("S", () => {\n'+ ' it("runs", () => {\n'+ " expect(a).toBe(1);\n"+ " expect(b).to.be.null;\n"+ " expect(c).toBe(3);\n"+ " });\n"+ "});\n"+ )+ fc = walk_file("src/x.test.ts", "typescript", source.encode("utf-8"))+ runs = [b for f in fc.functions for b in f.assertion_blocks]+ # Two narrow assertions split by a broad one, exactly as before this+ # existed: a broad statement breaks a run rather than bridging it.+ assert runs == []+++def test_an_assertion_in_a_nested_callback_belongs_to_the_test() -> None:+ _require("typescript")+ # An expression-bodied arrow holds no statement, so its assertion reached+ # no count at all until the walk counted lambda bodies. It was the largest+ # remaining TypeScript false positive.+ source = (+ 'describe("S", () => {\n'+ ' it("waits", async () => {\n'+ " await waitFor(() => expect(sent).toBe(1));\n"+ " });\n"+ ' it("each", () => {\n'+ " rows.forEach((r) => expect(r).toBe(1));\n"+ " });\n"+ ' it("bare", () => { doThing(); });\n'+ "});\n"+ )+ assert _flagged(source, "src/x.test.ts", "typescript") == ["it callback"]+++def test_a_suite_does_not_absorb_its_childrens_assertions() -> None:+ _require("typescript")+ # ``describe`` is transparent to the walker, but a nested *test case* must+ # still never count as its parent's oracle, or one asserting sibling would+ # silence the whole file.+ source = (+ 'describe("outer", () => {\n'+ ' it("checks", () => { expect(a).toBe(1); });\n'+ ' it("bare", () => { doThing(); });\n'+ "});\n"+ )+ assert _flagged(source, "src/x.test.ts", "typescript") == ["it callback"]+++def test_js_verification_counts_through_the_narrow_tier() -> None:+ _require("typescript")+ # jest spells verification with ``expect``, so it already reaches the+ # narrow tier and needs no row of its own. Pinned because it is the reason+ # ``verify_names`` is a Java-only concept today.+ source = (+ 'describe("S", () => {\n'+ ' it("verifies", () => { expect(sender.send).toHaveBeenCalled(); });\n'+ ' it("bare", () => { sender.send(m); });\n'+ "});\n"+ )+ assert _flagged(source, "src/x.test.ts", "typescript") == ["it callback"]+++def test_silent_on_a_jsx_file_walked_without_the_jsx_grammar() -> None:+ _require("typescript")+ # A ``.tsx`` file arrives tagged ``typescript`` and loses its assertions to+ # the non-JSX grammar, so every finding on one would be this bug rather+ # than a real result. The guard lapses once the tag is right.+ source = (+ 'describe("C", () => {\n'+ ' it("renders", () => {\n'+ " render(<Todo items={items} />);\n"+ ' expect(screen.getByText("x")).toBeInTheDocument();\n'+ " });\n"+ "});\n"+ )+ assert _flagged(source, "src/C.spec.tsx", "typescript") == []+ # Walked as tsx the assertion is visible, so the guard must not apply.+ assert _flagged(source, "src/C.spec.tsx", "tsx") == []+ bare = 'describe("C", () => { it("bare", () => { render(<A />); }); });\n'+ assert _flagged(bare, "src/C.spec.tsx", "tsx") == ["it callback"]+ assert _flagged(bare, "src/C.spec.tsx", "typescript") == []+++def test_a_private_assertion_helper_counts() -> None:+ _require("python")+ # ``_assert_no_secret_leak(msg)`` is an assertion helper by any reading,+ # but the narrow prefixes anchor at the start and the underscore breaks the+ # anchor. Python marks helpers private this way constantly.+ source = (+ "def test_private_helper():\n"+ " _assert_no_secret_leak(msg)\n"+ "\n"+ "def test_plain_helper():\n"+ " _build_user()\n"+ )+ assert _flagged(source) == ["test_plain_helper"]+++def test_go_and_java_are_classified_but_never_reported() -> None:+ _require("go")+ _require("java")+ # Both languages classify test cases and count assertions correctly -- that+ # is how their precision was measured -- but the marker does not report on+ # them, because each delegates its oracle to a helper this pass cannot see.+ go = "package p\n\nfunc TestBare(t *testing.T) {\n\tdoThing()\n}\n"+ java = "class FooTest {\n @Test void bare() { service.doIt(); }\n}\n"+ assert _counts(go, "pkg/thing_test.go", "go")["TestBare"][2] is True+ assert _counts(java, "src/test/java/FooTest.java", "java")["bare"][2] is True+ assert _flagged(go, "pkg/thing_test.go", "go") == []+ assert _flagged(java, "src/test/java/FooTest.java", "java") == []diff --git a/tests/unit/health/test_model_version_coupling.py b/tests/unit/health/test_model_version_coupling.pyindex 689db3a73..58ad39cf3 100644--- a/tests/unit/health/test_model_version_coupling.py+++ b/tests/unit/health/test_model_version_coupling.py@@ -22,7 +22,7 @@ from repowise.core.analysis.health.refactoring.identity import (# The three stamps as they stand together. Moving either identity model means# moving the analyzer with it, and updating this tuple in the same commit.-_STAMPS = (14, 2, 2)+_STAMPS = (15, 2, 2)def test_the_identity_models_and_the_analyzer_stamp_are_pinned_together() -> None:diff --git a/tests/unit/health/test_scoring_snapshot.py b/tests/unit/health/test_scoring_snapshot.pyindex 863377da3..a061a532a 100644--- a/tests/unit/health/test_scoring_snapshot.py+++ b/tests/unit/health/test_scoring_snapshot.py@@ -113,6 +113,7 @@ _EXPECTED_BIOMARKER_CATEGORY = {"duplicated_assertion_block": "test_quality",# Moves no score: its only dimension is ``advisory``, so ``score_file``# filters it out before any category is summed.+ "assertion_free_test": "test_quality","mock_saturated_test": "test_quality","error_handling": "error_handling",# Phase 4B governance biomarkers.