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.

fix(analysis): mask Java classes replaced by Mockito doubles (#4345) (#4579)

Rishabh Mishrac7e7675dde9d
diff --git a/packages/core/src/repowise/core/analysis/test_reach/mocks.py b/packages/core/src/repowise/core/analysis/test_reach/mocks.py
index c1d0d5e1f..cd1310ef1 100644
--- a/packages/core/src/repowise/core/analysis/test_reach/mocks.py
+++ b/packages/core/src/repowise/core/analysis/test_reach/mocks.py
@@ -36,6 +36,7 @@ from repowise.core.ingestion.languages.python_modules import build_python_module
from repowise.core.ingestion.resolvers.context import ResolverContext
from repowise.core.ingestion.resolvers.typescript import resolve_ts_js_import
+from .mocks_java import replaced_java_files
from .mocks_js import JS_SUFFIXES, replaced_specifiers
@@ -65,7 +66,7 @@ def replaced_modules(path: str, text: str | bytes) -> frozenset[str]:
# Test files :func:`replaced_files` reads; a caller need not read any other.
-MASKABLE_SUFFIXES = (".py", *JS_SUFFIXES)
+MASKABLE_SUFFIXES = (".py", ".java", *JS_SUFFIXES)
def replaced_files(
@@ -76,17 +77,22 @@ def replaced_files(
*files* are the repository's paths. A Python name masks a file only when it
is exactly that file's dotted module name; a JavaScript or TypeScript
specifier (:func:`~.mocks_js.replaced_specifiers`) only when it is relative
- and resolves to one of *files*. Ceiling: a bare or aliased specifier
- (``@/lib/x``, a workspace package) needs the repository's tsconfig and
- workspace map, so it abstains; resolving it with the indexer's full
- resolver context is the upgrade path. Tests replacing none are absent.
+ and resolves to one of *files*; a Java test's mocks
+ (:func:`~.mocks_java.replaced_java_files`) when resolved to a repository Java
+ file. Ceiling: a bare or aliased specifier (``@/lib/x``, a workspace package)
+ needs the repository's tsconfig and workspace map, so it abstains; resolving
+ it with the indexer's full resolver context is the upgrade path. Tests
+ replacing none are absent.
"""
index = build_python_module_index({f for f in files if f.endswith(".py")})
ctx = ResolverContext(path_set=set(files), stem_map={}, graph=None)
+ java_files = {f for f in files if f.endswith(".java")}
out: dict[str, frozenset[str]] = {}
for test, text in texts.items():
if test.endswith(".py"):
hits = {index[name] for name in replaced_modules(test, text) if name in index}
+ elif test.endswith(".java"):
+ hits = set(replaced_java_files(test, text, java_files))
else:
specs = replaced_specifiers(test, text)
hits = {
diff --git a/packages/core/src/repowise/core/analysis/test_reach/mocks_java.py b/packages/core/src/repowise/core/analysis/test_reach/mocks_java.py
new file mode 100644
index 000000000..1ddcac7a0
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/test_reach/mocks_java.py
@@ -0,0 +1,243 @@
+"""Which repository classes a Java test replaces outright with doubles, read from its text.
+
+In Java tests using Mockito or Spring test annotations, declaring ``@Mock Foo foo``,
+``@MockBean Foo foo``, ``@MockitoBean Foo foo``, or calling ``mock(Foo.class)``
+replaces ``Foo`` with a double. When a test only interacts with the double, its
+reach into ``Foo`` is masked.
+
+Never masks:
+- Spies: ``@Spy``, ``spy(...)``
+- Real method calls: ``CALLS_REAL_METHODS``, ``thenCallRealMethod()``, ``doCallRealMethod()``
+- Under test: ``@InjectMocks``
+- Real instantiation: ``new Foo(...)``
+- Ambiguous resolution across repository files
+"""
+
+from __future__ import annotations
+
+from collections.abc import Collection
+from typing import Any
+
+_MOCK_ANNOTATIONS = frozenset({"Mock", "MockBean", "MockitoBean"})
+_SPY_ANNOTATIONS = frozenset({"Spy", "InjectMocks"})
+
+
+def replaced_java_classes(path: str, text: str | bytes) -> frozenset[str]:
+ """The simple or qualified class names the test at *path* replaces with a mock double."""
+ if not path.endswith(".java"):
+ return frozenset()
+ data = text.encode("utf-8", "replace") if isinstance(text, str) else text
+ if b"Mock" not in data and b"mock" not in data:
+ return frozenset()
+ root = _parse(data)
+ if root is None:
+ return frozenset()
+ mocks, never, has_call_real, _, _, _ = _extract(root, data)
+ if has_call_real:
+ return frozenset()
+ never_simple = {n.rsplit(".", 1)[-1] for n in never}
+ effective = {m for m in mocks if m not in never and m.rsplit(".", 1)[-1] not in never_simple}
+ return frozenset(effective)
+
+
+def replaced_java_files(
+ path: str, text: str | bytes, java_files: Collection[str]
+) -> frozenset[str]:
+ """Repository Java files the test at *path* replaces outright."""
+ if not path.endswith(".java") or not java_files:
+ return frozenset()
+ data = text.encode("utf-8", "replace") if isinstance(text, str) else text
+ if b"Mock" not in data and b"mock" not in data:
+ return frozenset()
+ root = _parse(data)
+ if root is None:
+ return frozenset()
+ mocks, never, has_call_real, pkg, single_imports, wildcard_imports = _extract(root, data)
+ if has_call_real or not mocks:
+ return frozenset()
+
+ never_simple = {n.rsplit(".", 1)[-1] for n in never}
+ effective_mocks = {
+ m for m in mocks if m not in never and m.rsplit(".", 1)[-1] not in never_simple
+ }
+ if not effective_mocks:
+ return frozenset()
+
+ hits: set[str] = set()
+ for cand in effective_mocks:
+ matched = _resolve_class(cand, pkg, single_imports, wildcard_imports, java_files)
+ if matched is not None:
+ hits.add(matched)
+
+ return frozenset(hits)
+
+
+def _resolve_class(
+ cand: str,
+ pkg: str,
+ single_imports: dict[str, str],
+ wildcard_imports: list[str],
+ java_files: Collection[str],
+) -> str | None:
+ if "." in cand:
+ rel = cand.replace(".", "/") + ".java"
+ matches = [f for f in java_files if f == rel or f.endswith("/" + rel)]
+ return matches[0] if len(matches) == 1 else None
+
+ if cand in single_imports:
+ rel = single_imports[cand].replace(".", "/") + ".java"
+ matches = [f for f in java_files if f == rel or f.endswith("/" + rel)]
+ return matches[0] if len(matches) == 1 else None
+
+ if pkg:
+ rel = f"{pkg.replace('.', '/')}/{cand}.java"
+ matches = [f for f in java_files if f == rel or f.endswith("/" + rel)]
+ if len(matches) == 1:
+ return matches[0]
+ if len(matches) > 1:
+ return None
+ else:
+ rel = f"{cand}.java"
+ matches = [f for f in java_files if f == rel or f.endswith("/" + rel)]
+ if len(matches) == 1:
+ return matches[0]
+ if len(matches) > 1:
+ return None
+
+ wildcard_matches: set[str] = set()
+ for wild in wildcard_imports:
+ rel = f"{wild.replace('.', '/')}/{cand}.java"
+ matches = [f for f in java_files if f == rel or f.endswith("/" + rel)]
+ wildcard_matches.update(matches)
+ if len(wildcard_matches) == 1:
+ return next(iter(wildcard_matches))
+
+ return None
+
+
+def _extract(
+ root: Any, data: bytes
+) -> tuple[set[str], set[str], bool, str, dict[str, str], list[str]]:
+ pkg = ""
+ single_imports: dict[str, str] = {}
+ wildcard_imports: list[str] = []
+ mocks: set[str] = set()
+ never: set[str] = set()
+ has_call_real = False
+
+ for child in root.children:
+ if child.type == "package_declaration":
+ for sub in child.children:
+ if sub.type in ("scoped_identifier", "identifier"):
+ pkg = _text(sub, data)
+ elif child.type == "import_declaration":
+ is_static = any(sub.type == "static" for sub in child.children)
+ if not is_static:
+ has_asterisk = any(sub.type == "asterisk" for sub in child.children)
+ for sub in child.children:
+ if sub.type in ("scoped_identifier", "identifier"):
+ imp_text = _text(sub, data)
+ if has_asterisk:
+ wildcard_imports.append(imp_text)
+ else:
+ cname = imp_text.rsplit(".", 1)[-1]
+ single_imports[cname] = imp_text
+
+ stack = [root]
+ while stack:
+ node = stack.pop()
+ ntype = node.type
+
+ if ntype in ("field_declaration", "formal_parameter"):
+ anns = _annotation_names(node, data)
+ tname = _extract_type_name(node.child_by_field_name("type"), data)
+ if tname:
+ if anns & _MOCK_ANNOTATIONS:
+ mocks.add(tname)
+ if anns & _SPY_ANNOTATIONS:
+ never.add(tname)
+
+ elif ntype == "method_invocation":
+ mname_node = node.child_by_field_name("name")
+ mname = _text(mname_node, data) if mname_node else ""
+ if mname in ("thenCallRealMethod", "doCallRealMethod"):
+ has_call_real = True
+ elif mname == "mock":
+ args = node.child_by_field_name("arguments")
+ if args:
+ named = [a for a in args.children if a.type not in ("(", ")", ",", "comment")]
+ if named:
+ tname = _extract_type_name(named[0], data)
+ if tname:
+ mocks.add(tname)
+ elif mname == "spy":
+ args = node.child_by_field_name("arguments")
+ if args:
+ named = [a for a in args.children if a.type not in ("(", ")", ",", "comment")]
+ if named:
+ tname = _extract_type_name(named[0], data)
+ if tname:
+ never.add(tname)
+
+ elif ntype == "object_creation_expression":
+ tname = _extract_type_name(node.child_by_field_name("type"), data)
+ if tname:
+ never.add(tname)
+
+ elif ntype == "identifier":
+ if _text(node, data) == "CALLS_REAL_METHODS":
+ has_call_real = True
+
+ stack.extend(node.named_children)
+
+ return mocks, never, has_call_real, pkg, single_imports, wildcard_imports
+
+
+def _text(node: Any, data: bytes) -> str:
+ if node is None:
+ return ""
+ return data[node.start_byte : node.end_byte].decode("utf-8", errors="replace")
+
+
+def _annotation_names(node: Any, data: bytes) -> set[str]:
+ names: set[str] = set()
+ to_check: list[Any] = []
+ for c in node.children:
+ if c.type == "modifiers":
+ to_check.extend(c.children)
+ elif c.type in ("marker_annotation", "annotation"):
+ to_check.append(c)
+ for c in to_check:
+ if c.type in ("marker_annotation", "annotation"):
+ name_node = c.child_by_field_name("name")
+ if name_node is not None:
+ text = _text(name_node, data)
+ names.add(text.rsplit(".", 1)[-1])
+ return names
+
+
+def _extract_type_name(node: Any, data: bytes) -> str | None:
+ if node is None:
+ return None
+ if node.type in ("type_identifier", "scoped_type_identifier"):
+ return _text(node, data)
+ if node.type == "generic_type":
+ base = node.child_by_field_name("type") or (node.children[0] if node.children else None)
+ return _extract_type_name(base, data)
+ if node.type == "class_literal" and node.children:
+ return _extract_type_name(node.children[0], data)
+ return None
+
+
+def _parse(data: bytes) -> Any:
+ from tree_sitter import Parser
+
+ from repowise.core.ingestion.parser import _get_language
+
+ language = _get_language("java")
+ if language is None:
+ return None
+ try:
+ return Parser(language).parse(data).root_node
+ except (ValueError, RecursionError, MemoryError):
+ return None
diff --git a/tests/unit/analysis/test_test_reach_mocks_java.py b/tests/unit/analysis/test_test_reach_mocks_java.py
new file mode 100644
index 000000000..e62895ce7
--- /dev/null
+++ b/tests/unit/analysis/test_test_reach_mocks_java.py
@@ -0,0 +1,353 @@
+"""Which Java classes and repository files a Java test replaces outright with doubles."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.test_reach import replaced_files
+from repowise.core.analysis.test_reach.mocks_java import (
+ replaced_java_classes,
+ replaced_java_files,
+)
+
+_T = "src/test/java/com/acme/service/OrderServiceTest.java"
+
+
+ ("source", "expected"),
+ [
+ (
+ """
+ package com.acme.service;
+ import org.mockito.Mock;
+ import com.acme.client.PriceClient;
+ class OrderServiceTest {
+ @Mock
+ PriceClient prices;
+ }
+ """,
+ {"PriceClient"},
+ ),
+ (
+ """
+ package com.acme.service;
+ import org.springframework.boot.test.mock.mockito.MockBean;
+ import com.acme.client.PriceClient;
+ class OrderServiceTest {
+ @MockBean
+ PriceClient prices;
+ }
+ """,
+ {"PriceClient"},
+ ),
+ (
+ """
+ package com.acme.service;
+ import org.springframework.test.context.bean.override.mockito.MockitoBean;
+ import com.acme.client.PriceClient;
+ class OrderServiceTest {
+ @MockitoBean
+ PriceClient prices;
+ }
+ """,
+ {"PriceClient"},
+ ),
+ (
+ """
+ package com.acme.service;
+ import static org.mockito.Mockito.mock;
+ import com.acme.client.PriceClient;
+ class OrderServiceTest {
+ void test() {
+ PriceClient p = mock(PriceClient.class);
+ }
+ }
+ """,
+ {"PriceClient"},
+ ),
+ (
+ """
+ package com.acme.service;
+ import org.mockito.Mockito;
+ import com.acme.client.PriceClient;
+ class OrderServiceTest {
+ void test() {
+ PriceClient p = Mockito.mock(PriceClient.class);
+ }
+ }
+ """,
+ {"PriceClient"},
+ ),
+ (
+ """
+ package com.acme.service;
+ import com.acme.client.PriceClient;
+ class OrderServiceTest {
+ void test() {
+ PriceClient p = org.mockito.Mockito.mock(PriceClient.class);
+ }
+ }
+ """,
+ {"PriceClient"},
+ ),
+ (
+ """
+ package com.acme.service;
+ import org.mockito.Mock;
+ import com.acme.client.PriceClient;
+ class OrderServiceTest {
+ @Test
+ void testMethod(@Mock PriceClient p) {}
+ }
+ """,
+ {"PriceClient"},
+ ),
+ (
+ """
+ package com.acme.service;
+ import org.mockito.Mock;
+ import com.acme.client.PriceClient;
+ class OrderServiceTest {
+ @Mock
+ PriceClient<String> prices;
+ }
+ """,
+ {"PriceClient"},
+ ),
+ (
+ """
+ package com.acme.service;
+ import org.mockito.Mock;
+ class OrderServiceTest {
+ @Mock
+ com.acme.client.PriceClient prices;
+ }
+ """,
+ {"com.acme.client.PriceClient"},
+ ),
+ ],
+)
+def test_a_mock_replaces_the_class(source: str, expected: set[str]) -> None:
+ assert replaced_java_classes(_T, source) == expected
+
+
+ "source",
+ [
+ # @Spy
+ """
+ package com.acme.service;
+ import org.mockito.Spy;
+ import com.acme.client.PriceClient;
+ class OrderServiceTest {
+ @Spy
+ PriceClient prices;
+ }
+ """,
+ # spy(...)
+ """
+ package com.acme.service;
+ import static org.mockito.Mockito.spy;
+ import com.acme.client.PriceClient;
+ class OrderServiceTest {
+ void test() {
+ PriceClient p = spy(PriceClient.class);
+ }
+ }
+ """,
+ # @InjectMocks
+ """
+ package com.acme.service;
+ import org.mockito.InjectMocks;
+ import com.acme.client.PriceClient;
+ class OrderServiceTest {
+ @InjectMocks
+ PriceClient prices;
+ }
+ """,
+ # Instantiation via new Foo()
+ """
+ package com.acme.service;
+ import org.mockito.Mock;
+ import com.acme.client.PriceClient;
+ class OrderServiceTest {
+ @Mock
+ PriceClient prices;
+ void test() {
+ new PriceClient();
+ }
+ }
+ """,
+ # CALLS_REAL_METHODS
+ """
+ package com.acme.service;
+ import org.mockito.Mock;
+ import static org.mockito.Mockito.CALLS_REAL_METHODS;
+ import com.acme.client.PriceClient;
+ class OrderServiceTest {
+ @Mock
+ PriceClient prices;
+ void test() {
+ mock(PriceClient.class, CALLS_REAL_METHODS);
+ }
+ }
+ """,
+ # thenCallRealMethod()
+ """
+ package com.acme.service;
+ import org.mockito.Mock;
+ import com.acme.client.PriceClient;
+ class OrderServiceTest {
+ @Mock
+ PriceClient prices;
+ void test() {
+ when(prices.get()).thenCallRealMethod();
+ }
+ }
+ """,
+ # doCallRealMethod()
+ """
+ package com.acme.service;
+ import org.mockito.Mock;
+ import com.acme.client.PriceClient;
+ class OrderServiceTest {
+ @Mock
+ PriceClient prices;
+ void test() {
+ doCallRealMethod().when(prices).get();
+ }
+ }
+ """,
+ # Not a Java file
+ """
+ import org.mockito.Mock;
+ class OrderServiceTest {}
+ """,
+ ],
+)
+def test_anything_unproven_swaps_nothing(source: str) -> None:
+ if "Not a Java file" in source:
+ assert replaced_java_classes("src/OrderServiceTest.py", source) == frozenset()
+ else:
+ assert replaced_java_classes(_T, source) == frozenset()
+
+
+def test_syntax_error_abstains() -> None:
+ assert replaced_java_classes(_T, "class OrderServiceTest { @Mock PriceClient") == frozenset()
+
+
+def test_java_mock_masks_matching_repo_file() -> None:
+ files = {
+ "src/main/java/com/acme/client/PriceClient.java",
+ "src/main/java/com/acme/service/OrderService.java",
+ "src/main/java/com/acme/model/ItemModel.java",
+ _T,
+ }
+ texts = {
+ _T: """
+ package com.acme.service;
+ import com.acme.client.PriceClient;
+ import com.acme.model.*;
+ import org.mockito.Mock;
+ import org.mockito.Spy;
+ import org.mockito.InjectMocks;
+ import org.springframework.boot.test.mock.mockito.MockBean;
+
+ class OrderServiceTest {
+ @Mock
+ PriceClient prices;
+
+ @MockBean
+ ItemModel items;
+
+ @Mock
+ OrderService helper;
+
+ @InjectMocks
+ OrderService service;
+
+ @Spy
+ PriceClient spyPrices;
+ }
+ """,
+ }
+ # PriceClient has @Spy, so excluded.
+ # OrderService has @InjectMocks, so excluded.
+ # ItemModel is matched via wildcard com.acme.model.*.
+ assert replaced_java_files(_T, texts[_T], files) == {
+ "src/main/java/com/acme/model/ItemModel.java"
+ }
+
+
+def test_same_package_mock_masks_file() -> None:
+ files = {
+ "src/main/java/com/acme/service/OrderValidator.java",
+ _T,
+ }
+ text = """
+ package com.acme.service;
+ import org.mockito.Mock;
+
+ class OrderServiceTest {
+ @Mock
+ OrderValidator validator;
+ }
+ """
+ assert replaced_java_files(_T, text, files) == {
+ "src/main/java/com/acme/service/OrderValidator.java"
+ }
+
+
+def test_ambiguous_matches_abstain() -> None:
+ files = {
+ "mod-a/src/main/java/com/acme/service/OrderValidator.java",
+ "mod-b/src/main/java/com/acme/service/OrderValidator.java",
+ _T,
+ }
+ text = """
+ package com.acme.service;
+ import org.mockito.Mock;
+
+ class OrderServiceTest {
+ @Mock
+ OrderValidator validator;
+ }
+ """
+ assert replaced_java_files(_T, text, files) == frozenset()
+
+
+def test_third_party_class_masks_nothing() -> None:
+ files = {_T}
+ text = """
+ package com.acme.service;
+ import org.mockito.Mock;
+ import java.util.List;
+
+ class OrderServiceTest {
+ @Mock
+ List<String> list;
+ }
+ """
+ assert replaced_java_files(_T, text, files) == frozenset()
+
+
+def test_replaced_files_integration() -> None:
+ files = {
+ "src/main/java/com/acme/client/PriceClient.java",
+ _T,
+ }
+ texts = {
+ _T: """
+ package com.acme.service;
+ import com.acme.client.PriceClient;
+ import org.mockito.Mock;
+
+ class OrderServiceTest {
+ @Mock
+ PriceClient prices;
+ }
+ """
+ }
+ assert replaced_files(texts, files) == {
+ _T: frozenset({"src/main/java/com/acme/client/PriceClient.java"}),
+ }