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(test_reach): JS/TS mock masking accepts configured vi.fn() and vi.hoisted values (#4348) (#4392)
Amanf06e533423ca
diff --git a/packages/core/src/repowise/core/analysis/health/mocks/lexicon.py b/packages/core/src/repowise/core/analysis/health/mocks/lexicon.pyindex 5c0f1b740..28e86ecc7 100644--- a/packages/core/src/repowise/core/analysis/health/mocks/lexicon.py+++ b/packages/core/src/repowise/core/analysis/health/mocks/lexicon.py@@ -93,6 +93,15 @@ class MockDialect:#: Runner methods that return a bare double (``vi.fn()``).double_callees: frozenset[str] = frozenset()+ #: Double methods that configure what the double returns or runs+ #: (``vi.fn().mockReturnValue(1)``). Chained on a bare double they keep it+ #: free of the original, provided every argument is closed too.+ double_configurers: frozenset[str] = frozenset()++ #: Runner methods whose factory runs before the file's imports and hands+ #: its value to a binding (``const { f } = vi.hoisted(() => ...)``).+ hoist_callees: frozenset[str] = frozenset()+_PYTHON = MockDialect(# ``unittest.mock`` members with no mock token in their names.@@ -190,6 +199,19 @@ _JS_TS = MockDialect(runner_modules={"vi": frozenset({"vitest"}), "jest": frozenset({"@jest/globals"})},runner_globals=frozenset({"jest"}),double_callees=frozenset({"fn"}),+ double_configurers=frozenset(+ {+ "mockReturnValue",+ "mockReturnValueOnce",+ "mockResolvedValue",+ "mockResolvedValueOnce",+ "mockRejectedValue",+ "mockRejectedValueOnce",+ "mockImplementation",+ "mockImplementationOnce",+ }+ ),+ hoist_callees=frozenset({"hoisted"}),)diff --git a/packages/core/src/repowise/core/analysis/test_reach/mocks_js.py b/packages/core/src/repowise/core/analysis/test_reach/mocks_js.pyindex d2a459c7e..04c984aa3 100644--- a/packages/core/src/repowise/core/analysis/test_reach/mocks_js.py+++ b/packages/core/src/repowise/core/analysis/test_reach/mocks_js.py@@ -4,11 +4,14 @@*spec* for whatever *factory* returns, for every import in the test. The swapmasks the module only when the stand-in provably holds nothing of the original:a closed factory, with zero parameters (a parameter can receive the original-module) and a body of literals, objects, arrays and bare runner doubles-(``vi.fn()``). Any other call, a free identifier, a dynamic ``import()``, an-``await``, a spread or a ``new`` abstains, and so does every way of reaching the-original (``importActual``, ``requireActual``, ``importOriginal``) since none is-a bare double. The vocabulary is the mock lexicon's+module) and a body of literals, objects, arrays and runner doubles: a bare+``vi.fn()``, or one configured by a chained ``mockReturnValue`` /+``mockResolvedValue`` / ``mockRejectedValue`` / ``mockImplementation`` (or their+``Once`` forms) whose every argument is closed. A name bound exactly once, by+``vi.hoisted(<closed factory>)``, is closed too. Any other call, a free+identifier, a dynamic ``import()``, an ``await``, a spread or a ``new`` abstains,+and so does every way of reaching the original (``importActual``,+``requireActual``, ``importOriginal``) since none is a double. The vocabulary is the mock lexicon's(:attr:`~repowise.core.analysis.health.mocks.lexicon.MockDialect.binding_patches`).Never masks: an automock (no factory), ``doMock`` (later dynamic imports only),@@ -73,6 +76,7 @@ def replaced_specifiers(path: str, text: str | bytes) -> frozenset[str]:if not runners and not namespaces:return frozenset()proof = _Proof(dialect, runners, namespaces)+ proof.hoisted = _hoisted_names(root, proof)masked: set[str] = set()for call in _calls(root):form = dialect.binding_patches.get(proof.callee(call.child_by_field_name("function")) or "")@@ -187,6 +191,109 @@ def _text(node: Any) -> str:return node.text.decode("utf-8", "replace") if node is not None else ""+# Where a name is bound or written, keyed by the parent node type and the field+# of that parent the name must occupy (the other children are uses).+_BINDING_FIELD = {+ "variable_declarator": "name",+ "function_declaration": "name",+ "generator_function_declaration": "name",+ "function_expression": "name",+ "generator_function": "name",+ "class_declaration": "name",+ "class": "name",+ "assignment_expression": "left",+ "augmented_assignment_expression": "left",+ "for_in_statement": "left",+ "arrow_function": "parameter",+ "assignment_pattern": "left",+ "pair_pattern": "value",+ "catch_clause": "parameter",+ "required_parameter": "pattern",+ "optional_parameter": "pattern",+ "update_expression": "argument",+}+# Parents whose every name child is a binding.+_BINDING_CONTAINERS = frozenset(+ {+ "formal_parameters",+ "array_pattern",+ "object_pattern",+ "rest_pattern",+ "import_specifier",+ "import_clause",+ "namespace_import",+ }+)+++def _binds(node: Any) -> bool:+ """Whether *node* binds or writes its name, rather than reading it."""+ if node.type == "shorthand_property_identifier_pattern":+ return True+ parent = node.parent+ if parent is None or node.type != "identifier":+ return False+ if parent.type in _BINDING_CONTAINERS:+ return True+ field = _BINDING_FIELD.get(parent.type)+ return field is not None and parent.child_by_field_name(field) == node+++def _hoisted_names(root: Any, proof: _Proof) -> frozenset[str]:+ """Names bound once, by ``vi.hoisted(<closed factory>)``, and never rebound.++ A binding of the same name anywhere else in the file (a second declaration,+ a parameter, an assignment, an import) abstains: the proof is by name, so+ any other binding could be what a reference reads.+ """+ bound: dict[str, int] = {}+ candidates: list[str] = []+ stack = [root]+ while stack:+ node = stack.pop()+ stack.extend(node.named_children)+ if _binds(node):+ name = _text(node)+ bound[name] = bound.get(name, 0) + 1+ if node.type == "variable_declarator" and _is_hoisted_call(+ node.child_by_field_name("value"), proof+ ):+ candidates.extend(_declared_names(node.child_by_field_name("name")))+ return frozenset(name for name in candidates if bound.get(name) == 1)+++def _is_hoisted_call(node: Any, proof: _Proof) -> bool:+ if node is None or node.type != "call_expression":+ return False+ callee = proof.callee(node.child_by_field_name("function"))+ if callee is None or callee.rsplit(".", 1)[-1] not in proof.dialect.hoist_callees:+ return False+ args = node.child_by_field_name("arguments")+ named = [a for a in args.named_children if a.type != "comment"] if args is not None else []+ return len(named) == 1 and proof.closed_factory(named[0])+++def _declared_names(target: Any) -> list[str]:+ """The names a declarator target binds: a plain name, or the properties of a+ flat object pattern (``{ f }``, ``{ f: g }``). Defaults, rests and nested+ patterns bind nothing here."""+ if target is None:+ return []+ if target.type == "identifier":+ return [_text(target)]+ if target.type != "object_pattern":+ return []+ names: list[str] = []+ for child in target.named_children:+ if child.type == "shorthand_property_identifier_pattern":+ names.append(_text(child))+ elif child.type == "pair_pattern":+ value = child.child_by_field_name("value")+ if value is not None and value.type == "identifier":+ names.append(_text(value))+ return names++class _Proof:"""Reads callees against the runner bindings one file proves."""@@ -196,6 +303,7 @@ class _Proof:self.dialect = dialectself.runners = runnersself.namespaces = namespaces+ self.hoisted: frozenset[str] = frozenset()def runner(self, node: Any) -> str | None:"""``vi`` / ``jest`` when *node* is a proven runner object, else ``None``."""@@ -233,7 +341,9 @@ class _Proof:c.type == "template_substitution" for c in node.named_children)if kind == "identifier":- return _text(node) == "undefined"+ return _text(node) == "undefined" or _text(node) in self.hoisted+ if kind == "shorthand_property_identifier":+ return _text(node) in self.hoistedif kind in ("undefined", "property_identifier", "string_fragment", "escape_sequence"):return Trueif kind in _CONTAINERS:@@ -247,9 +357,23 @@ class _Proof:body = node.child_by_field_name("body")return body is not None and self._closed(body)if kind == "call_expression":- callee = self.callee(node.child_by_field_name("function"))- if callee is None or callee.rsplit(".", 1)[-1] not in self.dialect.double_callees:- return False- args = node.child_by_field_name("arguments")- return args is not None and all(self._closed(c) for c in args.named_children)+ return self._double(node)return False++ def _double(self, node: Any) -> bool:+ """A bare runner double (``vi.fn()``), or one configured by chained+ ``mockReturnValue(...)``-style verbs, with every argument closed."""+ if node is None or node.type != "call_expression":+ return False+ args = node.child_by_field_name("arguments")+ if args is None or not all(self._closed(c) for c in args.named_children):+ return False+ func = node.child_by_field_name("function")+ if (+ func is not None+ and func.type == "member_expression"+ and _text(func.child_by_field_name("property")) in self.dialect.double_configurers+ ):+ return self._double(func.child_by_field_name("object"))+ callee = self.callee(func)+ return callee is not None and callee.rsplit(".", 1)[-1] in self.dialect.double_calleesdiff --git a/tests/unit/analysis/test_test_reach_mocks_js.py b/tests/unit/analysis/test_test_reach_mocks_js.pyindex 091bb4bcb..8e91979b6 100644--- a/tests/unit/analysis/test_test_reach_mocks_js.py+++ b/tests/unit/analysis/test_test_reach_mocks_js.py@@ -20,6 +20,24 @@ _VI = 'import { vi } from "vitest"\n''import { jest } from "@jest/globals"\njest.mock("./a", () => ({ a: jest.fn() }))\n',# ``jest`` is also the runner's global, when the file binds no other.'jest.mock("./a", function () { return { a: jest.fn(), C: () => null } })\n',+ # A double configured with closed arguments, one or several verbs deep.+ _VI + 'vi.mock("./a", () => ({ a: vi.fn().mockReturnValue(1) }))\n',+ _VI + 'vi.mock("./a", () => ({ a: vi.fn().mockReturnValueOnce(1).mockReturnValue(2) }))\n',+ _VI + 'vi.mock("./a", () => ({ a: vi.fn().mockResolvedValue({ ok: true }) }))\n',+ _VI + 'vi.mock("./a", () => ({ a: vi.fn().mockResolvedValueOnce([1]) }))\n',+ _VI + 'vi.mock("./a", () => ({ a: vi.fn().mockRejectedValue("no") }))\n',+ _VI + 'vi.mock("./a", () => ({ a: vi.fn().mockRejectedValueOnce(null) }))\n',+ _VI + 'vi.mock("./a", () => ({ a: vi.fn().mockImplementation(() => 2) }))\n',+ _VI + 'vi.mock("./a", () => ({ a: vi.fn().mockImplementationOnce(() => ({ b: vi.fn() })) }))\n',+ 'jest.mock("./a", () => ({ a: jest.fn().mockReturnValue(1) }))\n',+ 'import { jest } from "@jest/globals"\n'+ 'jest.mock("./a", () => ({ a: jest.fn().mockResolvedValue({ ok: true }) }))\n',+ # A name bound once by a closed ``vi.hoisted``.+ _VI + 'const { f } = vi.hoisted(() => ({ f: vi.fn() }))\nvi.mock("./a", () => ({ f }))\n',+ _VI + 'const { f: g } = vi.hoisted(() => ({ f: vi.fn() }))\nvi.mock("./a", () => ({ a: g }))\n',+ _VI + 'const f = vi.hoisted(() => vi.fn().mockReturnValue(1))\nvi.mock("./a", () => ({ f }))\n',+ _VI + 'const { f } = vi.hoisted(() => ({ f: vi.fn() }))\nf.mockReturnValue(1)\n'+ 'vi.mock("./a", () => ({ a: f }))\n',],)def test_a_closed_factory_swaps_the_module(source: str) -> None:@@ -40,8 +58,28 @@ def test_a_closed_factory_swaps_the_module(source: str) -> None:# The original, in any form._VI + 'vi.mock("./a", async () => ({ ...(await vi.importActual("./a")), b: vi.fn() }))\n','jest.mock("./a", () => { const real = jest.requireActual("./a"); return { ...real } })\n',+ # A configured double abstains when an argument is not closed.+ _VI + 'vi.mock("./a", () => ({ a: vi.fn().mockImplementation(realFn) }))\n',+ _VI + 'vi.mock("./a", () => ({ a: vi.fn().mockReturnValue(real) }))\n',+ _VI + 'vi.mock("./a", () => ({ a: vi.fn().mockReturnValue(real()) }))\n',+ _VI + 'vi.mock("./a", () => ({ a: vi.fn().mockImplementation((x) => x) }))\n',+ _VI + 'vi.mock("./a", () => ({ a: vi.fn().mockResolvedValue(await vi.importActual("./a")) }))\n',+ # A configuring verb on anything but a proven bare double.+ _VI + 'vi.mock("./a", () => ({ a: other.mockReturnValue(1) }))\n',+ _VI + 'vi.mock("./a", () => ({ a: make().mockReturnValue(1) }))\n',+ _VI + 'vi.mock("./a", () => ({ a: vi.mockReturnValue(1) }))\n',+ 'const vi = make()\nvi.mock("./a", () => ({ a: vi.fn().mockReturnValue(1) }))\n',+ # A hoisted name that is not provably closed or not bound once.+ _VI + 'const { f } = vi.hoisted(() => ({ f: real() }))\nvi.mock("./a", () => ({ f }))\n',+ _VI + 'const { f } = vi.hoisted((x) => ({ f: vi.fn() }))\nvi.mock("./a", () => ({ f }))\n',+ _VI + 'const { f } = other.hoisted(() => ({ f: vi.fn() }))\nvi.mock("./a", () => ({ f }))\n',+ _VI + 'const { f } = vi.hoisted(() => ({ f: vi.fn() }))\nf = real\nvi.mock("./a", () => ({ f }))\n',+ _VI + 'let { f } = vi.hoisted(() => ({ f: vi.fn() }))\n({ f } = real)\nvi.mock("./a", () => ({ f }))\n',+ _VI + 'const { f } = vi.hoisted(() => ({ f: vi.fn() }))\nvar f = 1\nvi.mock("./a", () => ({ f }))\n',+ _VI + 'const { f } = vi.hoisted(() => ({ f: vi.fn() }))\nfunction t(f) {}\nvi.mock("./a", () => ({ f }))\n',+ _VI + 'const { f } = vi.hoisted(() => ({ f: vi.fn() }))\nvi.mock("./a", () => ({ g: f, h }))\n',+ _VI + 'const f = vi.hoisted(() => 1)\nconst f2 = f\nvi.mock("./a", () => ({ f: f2 }))\n',# Any other call, a free identifier, a dynamic import, a ``new``.- _VI + 'vi.mock("./a", () => ({ a: vi.fn().mockReturnValue(1) }))\n',_VI + 'const m = vi.fn()\nvi.mock("./a", () => ({ a: m }))\n',_VI + 'vi.mock("./a", () => ({ m }))\n',_VI + 'vi.mock("./a", () => import("./b"))\n',