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
fix(health): report a duplicated assertion block only when it holds five real checks (#2906)
Raghav Chamadiya9f8f0af07b45
diff --git a/packages/core/src/repowise/core/analysis/health/asserts/lexicon.py b/packages/core/src/repowise/core/analysis/health/asserts/lexicon.pyindex 49b9312ea..22a4ddbd2 100644--- a/packages/core/src/repowise/core/analysis/health/asserts/lexicon.py+++ b/packages/core/src/repowise/core/analysis/health/asserts/lexicon.py@@ -45,6 +45,7 @@ behaviour.from __future__ import annotations+import refrom dataclasses import dataclass, field#: Callee-name prefixes of the narrow tier. Matched case-insensitively against@@ -220,3 +221,66 @@ def assert_dialect(receiver_methods=dialect.receiver_methods,verify_names=dialect.verify_names,)+++# -- Flag checks (``duplicated_assertion_block``) ---------------------------+#+# A *flag check* asserts only that one plain name is set, unset, true or false:+# ``assertNotNull(x)``, ``Assert.IsTrue(ok)``, ``expect(x).toBeDefined()``,+# ``assert x is not None``. It is counted like any assertion; the duplicated+# block marker just does not count it toward a block's real checks, because two+# tests of one fixture repeat those lines without sharing logic worth a helper.+# Matched per language against a whole, whitespace-collapsed line, so a check+# spread over several lines is never one. A value check (``assertEquals(5,+# count())``) or a check on an expression (``assertNull(x.getY())``) is not a+# flag check in any row. A language without a row discounts nothing.++# An optional message argument, before (JUnit 4, MSTest) or after the name.+_MSG = r'(?:"[^"]*"|\'[^\']*\')'+_NAME = r"!?\s*\w+"+_CALL_ON_NAME = rf"\(\s*(?:{_MSG}\s*,\s*)?{_NAME}\s*(?:,\s*{_MSG})?\s*\)"+_END = r"\s*;?$"++_JVM_FLAG_CHECKS = (+ # JUnit / TestNG+ rf"^(?:\w+\.)?assert(?:Not)?Null{_CALL_ON_NAME}{_END}",+ rf"^(?:\w+\.)?assert(?:True|False){_CALL_ON_NAME}{_END}",+ # Hamcrest and AssertJ+ rf"^assertThat\(\s*\w+\s*,\s*(?:is\()?(?:notNullValue|nullValue)\(\)\)?\s*\){_END}",+ rf"^assertThat\(\s*\w+\s*,\s*is\((?:true|false)\)\s*\){_END}",+ rf"^assertThat\(\s*\w+\s*\)\.is(?:Not)?(?:Null|True|False)\(\){_END}",+)++FLAG_CHECK_PATTERNS: dict[str, tuple[str, ...]] = {+ "java": _JVM_FLAG_CHECKS,+ "kotlin": _JVM_FLAG_CHECKS,+ # MSTest / NUnit / xUnit, and FluentAssertions.+ "csharp": (+ rf"^Assert\.(?:Is)?(?:Not)?(?:Null|True|False){_CALL_ON_NAME}{_END}",+ rf"^\w+\.Should\(\)\.(?:Not)?Be(?:Null|True|False)\(\){_END}",+ ),+ "python": (+ r"^assert\s+(?:not\s+)?\w+(?:\s+is\s+(?:not\s+)?None)?(?:\s*,\s*.+)?$",+ rf"^self\.assert(?:Is)?(?:Not)?(?:None|True|False){_CALL_ON_NAME}$",+ ),+ "typescript": (+ r"^expect\(\s*\w+\s*\)\.(?:not\.)?(?:toBeDefined|toBeUndefined|toBeNull|toBeTruthy"+ rf"|toBeFalsy)\(\){_END}",+ rf"^expect\(\s*\w+\s*\)\.(?:not\.)?toBe\((?:true|false|null|undefined)\){_END}",+ rf"^assert(?:\.ok)?{_CALL_ON_NAME}{_END}",+ ),+ "rust": (rf"^assert!{_CALL_ON_NAME}{_END}",),+ "go": (r"^(?:assert|require)\.(?:Not)?(?:Nil|True|False)\(\s*\w+\s*,\s*!?\w+\s*\)$",),+}+for _alias, _base in (("tsx", "typescript"), ("javascript", "typescript"), ("jsx", "typescript")):+ FLAG_CHECK_PATTERNS[_alias] = FLAG_CHECK_PATTERNS[_base]++_FLAG_CHECK_RES = {+ language: re.compile("|".join(patterns)) for language, patterns in FLAG_CHECK_PATTERNS.items()+}+++def is_flag_check(language: str, line: str) -> bool:+ """Whether *line*, whitespace collapsed, is one flag check in *language*."""+ pattern = _FLAG_CHECK_RES.get(language)+ return pattern is not None and pattern.match(" ".join(line.split())) is not Nonediff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/duplicated_assertion_block.py b/packages/core/src/repowise/core/analysis/health/biomarkers/duplicated_assertion_block.pyindex 09a575ef2..7846e009e 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/duplicated_assertion_block.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/duplicated_assertion_block.py@@ -8,6 +8,18 @@ overlap an assertion block on a **test file**, and only when the block'stext, whitespace aside, really appears in the partner region. Clones matchon token shape, so without that check two asserts on different values pair up.+A block must hold at least ``_MIN_CHECKS`` assertions, not counting flag+checks (a bare null or boolean check on a plain name, per language in+``asserts/lexicon.py``). Shorter copies, like+``assertFalse(plugin.isEnabled()); assertNull(plugin.extender());`` or the+three-line "found it, it has this name, it has N buckets" check, are how two+tests of one fixture read, not a helper waiting to be extracted. The floor was+set on elasticsearch (Java), where such copies were nine in ten of what the+marker reported; from five real checks up a verbatim copy is a response-shape+check worth one helper. A copy inside one file still counts: the same five+checks repeated in two tests of one class are as much a missing helper as+copies across files.+It complements ``dry_violation`` (which flags clones anywhere, weighted byco-change): this one is scoped to test assertions and lands in the milder``test_quality`` category so a duplicated test never tanks a file's score.@@ -15,10 +27,20 @@ co-change): this one is scoped to test assertions and lands in the milderfrom __future__ import annotations+from ..asserts.lexicon import is_flag_checkfrom ..coverage import is_test_filefrom ..models import Severityfrom .base import BiomarkerResult, FileContext+_MIN_CHECKS = 5+++def _real_checks(language: str, lines: list[str], block: tuple[int, int, int]) -> int:+ """A block's assertions, less the flag checks (``asserts/lexicon.py``)."""+ start, end, count = block+ flags = sum(1 for line in lines[max(start, 1) - 1 : end] if is_flag_check(language, line))+ return count - flags+def _overlaps(a_start: int, a_end: int, b_start: int, b_end: int) -> bool:return a_start <= b_end and b_start <= a_end@@ -59,10 +81,12 @@ class DuplicatedAssertionBlockDetector:def detect(self, ctx: FileContext) -> list[BiomarkerResult]:if not is_test_file(ctx.file_path) or not ctx.clones:return []+ own_lines = ctx.clone_sources.get(ctx.file_path) or []blocks = [(start, end)for fn in ctx.all_functions- for start, end, _count in fn.assertion_blocks+ for start, end, count in fn.assertion_blocks+ if _real_checks(ctx.language, own_lines, (start, end, count)) >= _MIN_CHECKS]if not blocks:return []diff --git a/tests/unit/health/test_duplicated_assertion_dialects.py b/tests/unit/health/test_duplicated_assertion_dialects.pynew file mode 100644index 000000000..51bc5d94e--- /dev/null+++ b/tests/unit/health/test_duplicated_assertion_dialects.py@@ -0,0 +1,139 @@+"""``duplicated_assertion_block`` per language: real checks against flag checks.++Each case walks a real test file, pairs it with an identical partner, and asks+whether the copied block clears the five-real-check floor.+"""++from __future__ import annotations++import pytest++from repowise.core.analysis.health.asserts.lexicon import is_flag_check+from repowise.core.analysis.health.biomarkers import FileContext+from repowise.core.analysis.health.biomarkers.duplicated_assertion_block import (+ DuplicatedAssertionBlockDetector,+)+from repowise.core.analysis.health.complexity import walk_file+from repowise.core.analysis.health.duplication import ClonePair++# language -> (path, template, five real checks (the last spread over lines), flag checks)+_CASES = {+ "java": (+ "src/test/java/FooTest.java",+ "class FooTest {{\n @Test void t() {{\n{body}\n }}\n}}\n",+ [+ "assertEquals(5, getCount());",+ "assertEquals(expected, compute());",+ 'assertEquals("a", r.name());',+ "assertThat(r.size(), equalTo(2));",+ "assertThat(\n r.first(),\n equalTo(1));",+ ],+ [+ "assertNotNull(r);",+ "assertThat(r, notNullValue());",+ 'assertTrue("ok", done);',+ "assertThat(r).isNotNull();",+ ],+ ),+ "csharp": (+ "tests/FooTests.cs",+ "class FooTests {{\n [Fact] public void T() {{\n{body}\n }}\n}}\n",+ [+ "Assert.Equal(5, r.Count);",+ 'Assert.Equal("a", r.Name);',+ "Assert.Equal(2, r.Size());",+ 'Assert.Contains("x", r.Tags);',+ "Assert.Equal(\n 1,\n r.First());",+ ],+ ["Assert.IsNotNull(r);", "Assert.True(done);", "r.Should().NotBeNull();", "Assert.Null(err);"],+ ),+ "typescript": (+ "tests/foo.test.ts",+ "it('t', () => {{\n{body}\n}});\n",+ [+ "expect(r.count).toBe(5);",+ "expect(r.name).toEqual('a');",+ "expect(r.size()).toBe(2);",+ "expect(r.tags).toContain('x');",+ "expect(\n r.first(),\n ).toBe(1);",+ ],+ [+ "expect(r).toBeDefined();",+ "expect(done).toBe(true);",+ "expect(err).not.toBeNull();",+ "assert(done);",+ ],+ ),+ "python": (+ "tests/test_foo.py",+ "def test_t():\n{body}\n",+ [+ "assert r.count == 5",+ "assert r.name == 'a'",+ "assert r.size() == 2",+ "assert 'x' in r.tags",+ "assert r.first() == (\n 1\n )",+ ],+ ["assert r is not None", "assert done", "assert not err", "assert ok, 'message'"],+ ),+}+++def _detect(language: str, lines: list[str]):+ path, template, _, _ = _CASES[language]+ source = template.format(body="\n".join(" " + line for line in lines))+ text = source.splitlines()+ partner = path.replace("oo", "ee")+ clone = ClonePair(path, partner, 1, len(text), 1, len(text), token_count=80)+ return DuplicatedAssertionBlockDetector().detect(+ FileContext(+ file_path=path,+ language=language,+ nloc=200,+ has_test_file=False,+ module=None,+ all_functions=tuple(walk_file(path, language, source.encode()).functions),+ clones=[clone],+ clone_sources={path: text, partner: text},+ )+ )++[email protected]("language", sorted(_CASES))+def test_five_real_checks_are_reported_four_are_not(language: str):+ _, _, real, flags = _CASES[language]+ assert len(_detect(language, real)) == 1+ assert _detect(language, real[:4]) == []+ # Flag checks pad the block without making it five real checks.+ assert _detect(language, [*flags, *real[:4]]) == []+++ ("language", "line"),+ [+ ("java", "assertEquals(5, getCount());"),+ ("java", "assertEquals(expected, compute());"),+ ("java", "assertNull(x.getY());"),+ ("csharp", "Assert.Equal(expected, Compute());"),+ ("python", "assert x == compute()"),+ ("typescript", "expect(x).toBe(5);"),+ ],+)+def test_a_value_check_is_not_a_flag_check(language: str, line: str):+ assert not is_flag_check(language, line)+++ ("language", "line"),+ [+ ("java", " assertNull(err, \"message\");"),+ ("kotlin", "assertTrue(done)"),+ ("csharp", "Assert.IsFalse(failed);"),+ ("python", "self.assertIsNone(err)"),+ ("javascript", "assert.ok(done);"),+ ("rust", "assert!(ok);"),+ ("go", "require.NotNil(t, err)"),+ ],+)+def test_flag_checks_per_language(language: str, line: str):+ assert is_flag_check(language, line)diff --git a/tests/unit/health/test_test_quality_biomarkers.py b/tests/unit/health/test_test_quality_biomarkers.pyindex dd8ab8abc..56a67cc58 100644--- a/tests/unit/health/test_test_quality_biomarkers.py+++ b/tests/unit/health/test_test_quality_biomarkers.py@@ -116,17 +116,23 @@ def _lines(block: list[str], at: int, total: int = 40) -> list[str]:return out-_BLOCK = ["assert result.exit_code == 0", "assert result.output == 'ok'"]+_BLOCK = [+ "assert result.exit_code == 0",+ "assert result.output == 'ok'",+ "assert result.stderr == ''",+ "assert len(result.files) == 2",+ "assert result.files[0].name == 'a.txt'",+]def test_duplicated_assertion_block_fires_when_clone_overlaps_block():- fn = _fn("test_x", assertion_blocks=[(12, 13, 2)])+ fn = _fn("test_x", assertion_blocks=[(12, 16, 5)])clone = _clone("tests/test_x.py", (10, 16), "tests/test_y.py", (5, 11))sources = {"tests/test_x.py": _lines(_BLOCK, 12),# Same statements, different indentation and spacing."tests/test_y.py": _lines(- [" assert result.exit_code == 0", "\tassert result.output == 'ok'"], 7+ [" assert result.exit_code == 0", "\tassert result.output == 'ok'", *_BLOCK[2:]], 7),}out = DuplicatedAssertionBlockDetector().detect(@@ -138,13 +144,13 @@ def test_duplicated_assertion_block_fires_when_clone_overlaps_block():def test_duplicated_assertion_block_needs_the_same_text_not_just_shape():- fn = _fn("test_x", assertion_blocks=[(12, 13, 2)])+ fn = _fn("test_x", assertion_blocks=[(12, 16, 5)])clone = _clone("tests/test_x.py", (10, 16), "tests/test_y.py", (5, 11))sources = {"tests/test_x.py": _lines(_BLOCK, 12),# Token-for-token the same shape, different values."tests/test_y.py": _lines(- ["assert result.exit_code == 2", "assert result.output == 'usage'"], 7+ ["assert result.exit_code == 2", "assert result.output == 'usage'", *_BLOCK[2:]], 7),}out = DuplicatedAssertionBlockDetector().detect(@@ -154,7 +160,7 @@ def test_duplicated_assertion_block_needs_the_same_text_not_just_shape():def test_duplicated_assertion_block_silent_without_partner_source():- fn = _fn("test_x", assertion_blocks=[(12, 13, 2)])+ fn = _fn("test_x", assertion_blocks=[(12, 16, 5)])clone = _clone("tests/test_x.py", (10, 16), "tests/test_y.py", (5, 11))sources = {"tests/test_x.py": _lines(_BLOCK, 12)}out = DuplicatedAssertionBlockDetector().detect(@@ -164,7 +170,7 @@ def test_duplicated_assertion_block_silent_without_partner_source():def test_duplicated_assertion_block_ignores_an_intra_file_clone_overlapping_itself():- fn = _fn("test_x", assertion_blocks=[(12, 13, 2)])+ fn = _fn("test_x", assertion_blocks=[(12, 16, 5)])clone = _clone("tests/test_x.py", (10, 16), "tests/test_x.py", (11, 17))sources = {"tests/test_x.py": _lines(_BLOCK, 12)}out = DuplicatedAssertionBlockDetector().detect(@@ -173,6 +179,38 @@ def test_duplicated_assertion_block_ignores_an_intra_file_clone_overlapping_itseassert out == []+def test_duplicated_assertion_block_needs_five_real_checks():+ clone = _clone("tests/test_x.py", (10, 16), "tests/test_y.py", (5, 11))+ d = DuplicatedAssertionBlockDetector()+ short = _BLOCK[:4]+ sources = {"tests/test_x.py": _lines(short, 12), "tests/test_y.py": _lines(short, 7)}+ fn = _fn("test_x", assertion_blocks=[(12, 15, 4)])+ ctx = _ctx(file_path="tests/test_x.py", functions=[fn], clones=[clone], clone_sources=sources)+ assert d.detect(ctx) == []+ # Five assertions, but a bare null / flag check does not count as one.+ flagged = ["assert result is not None", *short]+ sources = {"tests/test_x.py": _lines(flagged, 12), "tests/test_y.py": _lines(flagged, 7)}+ fn = _fn("test_x", assertion_blocks=[(12, 16, 5)])+ ctx = _ctx(file_path="tests/test_x.py", functions=[fn], clones=[clone], clone_sources=sources)+ assert d.detect(ctx) == []+++def test_duplicated_assertion_block_reports_a_copy_inside_one_file():+ fn = _fn("test_x", assertion_blocks=[(12, 16, 5)])+ clone = _clone("tests/test_x.py", (11, 17), "tests/test_x.py", (29, 35))+ lines = _lines(_BLOCK, 12)+ lines[29:34] = _BLOCK+ out = DuplicatedAssertionBlockDetector().detect(+ _ctx(+ file_path="tests/test_x.py",+ functions=[fn],+ clones=[clone],+ clone_sources={"tests/test_x.py": lines},+ )+ )+ assert [r.details["partner_file"] for r in out] == ["tests/test_x.py"]++def test_duplicated_assertion_block_ignores_clone_outside_block():fn = _fn("test_x", assertion_blocks=[(10, 20, 6)])clone = _clone("tests/test_x.py", (40, 48), "tests/test_y.py", (5, 12))