Skip to content

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

feat(tests): a JS or TS test that mocks a module with a closed factory does not reach it (#4341)

Raghav Chamadiya43021a6e984c
diff --git a/docs/architecture/test-intelligence.md b/docs/architecture/test-intelligence.md
index a8c30746e..eba0c7b21 100644
--- a/docs/architecture/test-intelligence.md
+++ b/docs/architecture/test-intelligence.md
@@ -145,7 +145,10 @@ A Python test that swaps a module object out (`patch("pkg.helpers")`,
does not reach that module through the swap. A file only such tests reach is
`mocked_only`, read from the test files' text at walk time, never stored.
Patching a name inside a module, a run-time target, or a patch with `wraps`,
-`side_effect` or `autospec` keeps the reach.
+`side_effect` or `autospec` keeps the reach. In JavaScript and TypeScript,
+`vi.mock` / `jest.mock` swaps a module out when its factory takes no parameter
+and returns only literals and `vi.fn()` / `jest.fn()`; an automock, `doMock`, a
+factory that reads the original, or a non-relative specifier keeps the reach.
## Measured map internals
diff --git a/packages/core/src/repowise/core/analysis/health/mocks/lexicon.py b/packages/core/src/repowise/core/analysis/health/mocks/lexicon.py
index 283edd334..5c0f1b740 100644
--- a/packages/core/src/repowise/core/analysis/health/mocks/lexicon.py
+++ b/packages/core/src/repowise/core/analysis/health/mocks/lexicon.py
@@ -73,14 +73,26 @@ class MockDialect:
#: Callee -> how it names the binding it replaces: ``dotted`` as one
#: ``"pkg.mod.name"`` string, ``object`` as ``(obj, "name")``,
- #: ``dotted_or_object`` either way, ``modules`` as ``sys.modules`` keys.
- #: Callees are spelled with any :attr:`guard_roots` prefix dropped.
+ #: ``dotted_or_object`` either way, ``modules`` as ``sys.modules`` keys,
+ #: ``factory`` as a module specifier plus a factory for its stand-in,
+ #: ``restore`` as a specifier whose stand-in it removes. Callees are
+ #: spelled with any :attr:`guard_roots` prefix dropped.
binding_patches: dict[str, str] = field(default_factory=dict)
#: Keywords that leave the original reachable through the double, or may:
#: a patch carrying one never counts as replacing the binding.
passthrough_keywords: frozenset[str] = frozenset()
+ #: Test-runner object -> the modules that export it under that name
+ #: (``vi`` from ``vitest``), for proving a receiver is the runner's.
+ runner_modules: dict[str, frozenset[str]] = field(default_factory=dict)
+
+ #: Runner objects the runner also installs as globals (``jest``).
+ runner_globals: frozenset[str] = frozenset()
+
+ #: Runner methods that return a bare double (``vi.fn()``).
+ double_callees: frozenset[str] = frozenset()
+
_PYTHON = MockDialect(
# ``unittest.mock`` members with no mock token in their names.
@@ -166,6 +178,18 @@ _JS_TS = MockDialect(
# ``vi.fn()`` / ``jest.fn()`` carry no test-double token anywhere in the
# call, so without these a file that mocks only through them is skipped.
file_markers=frozenset({"vi.fn", "jest.fn", "sinon", "jasmine"}),
+ # ``doMock`` is left out: it applies only to later dynamic imports.
+ binding_patches={
+ "vi.mock": "factory",
+ "jest.mock": "factory",
+ "vi.unmock": "restore",
+ "jest.unmock": "restore",
+ "vi.doUnmock": "restore",
+ "jest.doUnmock": "restore",
+ },
+ runner_modules={"vi": frozenset({"vitest"}), "jest": frozenset({"@jest/globals"})},
+ runner_globals=frozenset({"jest"}),
+ double_callees=frozenset({"fn"}),
)
diff --git a/packages/core/src/repowise/core/analysis/test_reach/db.py b/packages/core/src/repowise/core/analysis/test_reach/db.py
index 329ed3f15..876f5de76 100644
--- a/packages/core/src/repowise/core/analysis/test_reach/db.py
+++ b/packages/core/src/repowise/core/analysis/test_reach/db.py
@@ -26,7 +26,7 @@ from repowise.core.persistence.models import GraphNode, Repository
from .forward import CallGraphView, files_reached_by_tests
from .hubs import call_hub_files
from .maps import LEGACY_CONFTEST_HINT, ImportGraph, Need, Walk
-from .mocks import replaced_files
+from .mocks import MASKABLE_SUFFIXES, replaced_files
from .model import (
DEFAULT_CALL_DEPTH,
DEFAULT_MAX_DEPTH,
@@ -194,7 +194,7 @@ async def cached_test_masks(session: AsyncSession, repo_id: str) -> dict[str, fr
root = (
await session.execute(select(Repository.local_path).where(Repository.id == repo_id))
).scalar_one_or_none()
- tests = [t for t in await cached_test_files(session, repo_id) if t.endswith(".py")]
+ tests = [t for t in await cached_test_files(session, repo_id) if t.endswith(MASKABLE_SUFFIXES)]
texts = await asyncio.to_thread(_read_texts, root, tests) if root else {}
files = await _file_paths(session, repo_id) if texts else set()
return _cache.remember(key, replaced_files(texts, files))
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 0b1f85f2b..c1d0d5e1f 100644
--- a/packages/core/src/repowise/core/analysis/test_reach/mocks.py
+++ b/packages/core/src/repowise/core/analysis/test_reach/mocks.py
@@ -1,8 +1,9 @@
"""Which repository modules a test replaces outright, read from the test's own text.
A test that swaps a module object for a double runs the double, not the module,
-so its route into that module is no evidence that a test exercises it. Python
-only: the patch forms come from the mock lexicon
+so its route into that module is no evidence that a test exercises it. This
+module reads Python (:mod:`.mocks_js` reads JavaScript); the patch forms come
+from the mock lexicon
(:attr:`~repowise.core.analysis.health.mocks.lexicon.MockDialect.binding_patches`).
A patch replaces one binding. Only a binding that *is* a module masks it:
@@ -32,6 +33,10 @@ from collections.abc import Collection, Mapping
from repowise.core.analysis.health.mocks.lexicon import MockDialect, mock_dialect
from repowise.core.ingestion.languages.python_modules import build_python_module_index
+from repowise.core.ingestion.resolvers.context import ResolverContext
+from repowise.core.ingestion.resolvers.typescript import resolve_ts_js_import
+
+from .mocks_js import JS_SUFFIXES, replaced_specifiers
def replaced_modules(path: str, text: str | bytes) -> frozenset[str]:
@@ -59,18 +64,37 @@ def replaced_modules(path: str, text: str | bytes) -> frozenset[str]:
return frozenset(found - _imported_modules(tree))
+# Test files :func:`replaced_files` reads; a caller need not read any other.
+MASKABLE_SUFFIXES = (".py", *JS_SUFFIXES)
+
+
def replaced_files(
texts: Mapping[str, str | bytes], files: Collection[str]
) -> dict[str, frozenset[str]]:
"""``{test: the repository files it replaces outright}``, for the tests in *texts*.
- *files* are the repository's paths; a replaced name masks a file only when
- it is exactly that file's dotted module name. Tests replacing none are absent.
+ *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.
"""
index = build_python_module_index({f for f in files if f.endswith(".py")})
+ ctx = ResolverContext(path_set=set(files), stem_map={}, graph=None)
out: dict[str, frozenset[str]] = {}
for test, text in texts.items():
- hits = {index[name] for name in replaced_modules(test, text) if name in index}
+ if test.endswith(".py"):
+ hits = {index[name] for name in replaced_modules(test, text) if name in index}
+ else:
+ specs = replaced_specifiers(test, text)
+ hits = {
+ hit
+ for spec in specs
+ if spec.startswith(".")
+ and (hit := resolve_ts_js_import(spec, test, ctx)) in ctx.path_set
+ }
hits.discard(test)
if hits:
out[test] = frozenset(hits)
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.py
new file mode 100644
index 000000000..d2a459c7e
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/test_reach/mocks_js.py
@@ -0,0 +1,255 @@
+"""Which modules a JavaScript or TypeScript test replaces outright, read from its text.
+
+``vi.mock(spec, factory)`` and ``jest.mock(spec, factory)`` swap the module at
+*spec* for whatever *factory* returns, for every import in the test. The swap
+masks 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
+(:attr:`~repowise.core.analysis.health.mocks.lexicon.MockDialect.binding_patches`).
+
+Never masks: an automock (no factory), ``doMock`` (later dynamic imports only),
+any mock in a file that also calls ``unmock`` / ``doUnmock``, and a receiver not
+proven to be the runner's: ``vi`` must be imported from ``vitest``; ``jest`` may
+also be the global, when the file imports none. A name used other than as
+``name.method`` anywhere in the file abstains, since it may be rebound.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from repowise.core.analysis.health.mocks.lexicon import MockDialect, mock_dialect
+
+JS_SUFFIXES = (".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs")
+
+# Nodes a closed factory may hold beyond calls, functions and ``undefined``:
+# literals and the containers that only arrange them.
+_LITERALS = frozenset(
+ {"string", "number", "true", "false", "null", "template_string", "regex"}
+)
+_CONTAINERS = frozenset(
+ {
+ "object",
+ "pair",
+ "array",
+ "parenthesized_expression",
+ "statement_block",
+ "return_statement",
+ "expression_statement",
+ "unary_expression",
+ "comment",
+ }
+)
+_FUNCTIONS = frozenset({"arrow_function", "function_expression", "function"})
+
+# Nodes that name a binding or a use of one.
+_NAME_NODES = frozenset(
+ {
+ "identifier",
+ "shorthand_property_identifier",
+ "shorthand_property_identifier_pattern",
+ "type_identifier",
+ }
+)
+
+
+def replaced_specifiers(path: str, text: str | bytes) -> frozenset[str]:
+ """The module specifiers the test at *path* swaps for a closed factory's stand-in."""
+ dialect = mock_dialect("typescript")
+ if dialect is None or not path.lower().endswith(JS_SUFFIXES):
+ return frozenset()
+ data = text.encode("utf-8", "replace") if isinstance(text, str) else text
+ methods = {callee.rsplit(".", 1)[-1] for callee in dialect.binding_patches}
+ if not any(f".{m}(".encode() in data for m in methods):
+ return frozenset()
+ root = _parse(path, data)
+ if root is None:
+ return frozenset()
+ runners, namespaces = _runner_bindings(root, dialect)
+ if not runners and not namespaces:
+ return frozenset()
+ proof = _Proof(dialect, runners, namespaces)
+ masked: set[str] = set()
+ for call in _calls(root):
+ form = dialect.binding_patches.get(proof.callee(call.child_by_field_name("function")) or "")
+ if form == "restore":
+ # An unmock may name the module by another specifier; any one abstains.
+ return frozenset()
+ if form != "factory":
+ continue
+ args = [a for a in call.child_by_field_name("arguments").named_children if a.type != "comment"]
+ spec = _literal(args[0]) if args else None
+ if spec is not None and len(args) == 2 and proof.closed_factory(args[1]):
+ masked.add(spec)
+ return frozenset(masked)
+
+
+def _parse(path: str, data: bytes) -> Any:
+ from tree_sitter import Parser
+
+ from repowise.core.ingestion.parser import _get_language
+ from repowise.core.ingestion.parser.grammars import grammar_tag_for
+
+ tag = "typescript" if path.lower().endswith((".ts", ".tsx", ".mts", ".cts")) else "javascript"
+ language = _get_language(grammar_tag_for(tag, path))
+ if language is None:
+ return None
+ try:
+ return Parser(language).parse(data).root_node
+ except (ValueError, RecursionError, MemoryError):
+ return None
+
+
+def _calls(root: Any) -> list[Any]:
+ out: list[Any] = []
+ stack = [root]
+ while stack:
+ node = stack.pop()
+ if node.type == "call_expression":
+ out.append(node)
+ stack.extend(node.named_children)
+ return out
+
+
+def _literal(node: Any) -> str | None:
+ """The text of a plain string literal; ``None`` for anything built or escaped."""
+ if node is None or node.type != "string":
+ return None
+ parts = node.named_children
+ if len(parts) != 1 or parts[0].type != "string_fragment":
+ return None
+ return parts[0].text.decode("utf-8", "replace")
+
+
+def _runner_bindings(root: Any, dialect: MockDialect) -> tuple[dict[str, str], dict[str, str]]:
+ """``({local name: runner}, {namespace name: runner module})`` the file proves.
+
+ A name is proven only when every other use of it is the object of a member
+ access (``vi.mock``): a declaration, parameter, pattern or argument of the
+ same name could rebind it, so it abstains.
+ """
+ runners: dict[str, str] = {}
+ namespaces: dict[str, str] = {}
+ imported: set[str] = set()
+ owner = {m: r for r, mods in dialect.runner_modules.items() for m in mods}
+ other: set[str] = set()
+ stack = [root]
+ while stack:
+ node = stack.pop()
+ if node.type == "import_statement":
+ source = _literal(node.child_by_field_name("source"))
+ for ident in _descendants(node, "identifier"):
+ imported.add(_text(ident))
+ for spec in _descendants(node, "import_specifier"):
+ local = spec.child_by_field_name("alias") or spec.child_by_field_name("name")
+ name = _text(spec.child_by_field_name("name"))
+ if source in owner and name == owner[source]:
+ runners[_text(local)] = name
+ for ns in _descendants(node, "namespace_import"):
+ for ident in ns.named_children:
+ if source in owner:
+ namespaces[_text(ident)] = owner[source]
+ continue
+ stack.extend(node.named_children)
+ if node.type in _NAME_NODES:
+ parent = node.parent
+ used = (
+ parent is not None
+ and parent.type == "member_expression"
+ and parent.child_by_field_name("object") == node
+ )
+ if not used:
+ other.add(_text(node))
+ for runner in dialect.runner_globals:
+ if runner not in imported:
+ runners[runner] = runner
+ runners = {name: r for name, r in runners.items() if name not in other}
+ namespaces = {name: r for name, r in namespaces.items() if name not in other}
+ return runners, namespaces
+
+
+def _descendants(node: Any, kind: str) -> list[Any]:
+ out: list[Any] = []
+ stack = list(node.named_children)
+ while stack:
+ n = stack.pop()
+ if n.type == kind:
+ out.append(n)
+ stack.extend(n.named_children)
+ return out
+
+
+def _text(node: Any) -> str:
+ return node.text.decode("utf-8", "replace") if node is not None else ""
+
+
+class _Proof:
+ """Reads callees against the runner bindings one file proves."""
+
+ def __init__(
+ self, dialect: MockDialect, runners: dict[str, str], namespaces: dict[str, str]
+ ):
+ self.dialect = dialect
+ self.runners = runners
+ self.namespaces = namespaces
+
+ def runner(self, node: Any) -> str | None:
+ """``vi`` / ``jest`` when *node* is a proven runner object, else ``None``."""
+ if node is None:
+ return None
+ if node.type == "identifier":
+ return self.runners.get(_text(node))
+ if node.type == "member_expression":
+ obj = node.child_by_field_name("object")
+ prop = _text(node.child_by_field_name("property"))
+ if obj is not None and obj.type == "identifier":
+ return prop if self.namespaces.get(_text(obj)) == prop else None
+ return None
+
+ def callee(self, node: Any) -> str | None:
+ """``vi.mock`` for a proven ``<runner>.mock``; ``None`` for anything else."""
+ if node is None or node.type != "member_expression":
+ return None
+ runner = self.runner(node.child_by_field_name("object"))
+ if runner is None:
+ return None
+ return f"{runner}.{_text(node.child_by_field_name('property'))}"
+
+ def closed_factory(self, node: Any) -> bool:
+ """A zero-parameter function whose stand-in holds only literals and bare doubles."""
+ try:
+ return node.type in _FUNCTIONS and self._closed(node)
+ except RecursionError:
+ return False
+
+ def _closed(self, node: Any) -> bool:
+ kind = node.type
+ if kind in _LITERALS:
+ return kind != "template_string" or not any(
+ c.type == "template_substitution" for c in node.named_children
+ )
+ if kind == "identifier":
+ return _text(node) == "undefined"
+ if kind in ("undefined", "property_identifier", "string_fragment", "escape_sequence"):
+ return True
+ if kind in _CONTAINERS:
+ return all(self._closed(c) for c in node.named_children)
+ if kind in _FUNCTIONS:
+ params = node.child_by_field_name("parameters")
+ if node.child_by_field_name("parameter") is not None:
+ return False
+ if params is not None and any(c.type != "comment" for c in params.named_children):
+ return False
+ 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 False
diff --git a/tests/unit/analysis/test_test_reach_mocks_js.py b/tests/unit/analysis/test_test_reach_mocks_js.py
new file mode 100644
index 000000000..091bb4bcb
--- /dev/null
+++ b/tests/unit/analysis/test_test_reach_mocks_js.py
@@ -0,0 +1,89 @@
+"""Which modules a JavaScript or TypeScript test swaps for a closed factory's stand-in."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.test_reach import replaced_files
+from repowise.core.analysis.test_reach.mocks_js import replaced_specifiers
+
+_T = "src/x.test.ts"
+_VI = 'import { vi } from "vitest"\n'
+
+
+ "source",
+ [
+ _VI + 'vi.mock("./a", () => ({ run: vi.fn(), n: 1, s: "x", l: [null, undefined], o: { b: true } }))\n',
+ 'import { vi as v } from "vitest"\nv.mock("./a", async () => { return { default: v.fn(() => 1) } })\n',
+ 'import * as vt from "vitest"\nvt.vi.mock("./a", () => ({ a: vt.vi.fn() }))\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',
+ ],
+)
+def test_a_closed_factory_swaps_the_module(source: str) -> None:
+ assert replaced_specifiers(_T, source) == {"./a"}
+
+
+ "source",
+ [
+ # Automock, ``doMock``, and a mock the file undoes.
+ _VI + 'vi.mock("./a")\n',
+ _VI + 'vi.doMock("./a", () => ({}))\n',
+ _VI + 'vi.mock("./a", () => ({}))\nvi.unmock("./a")\n',
+ 'jest.mock("./a", () => ({}))\njest.doUnmock("./a")\n',
+ # A parameter can receive the original module.
+ _VI + 'vi.mock("./a", (importOriginal) => ({ a: vi.fn() }))\n',
+ _VI + 'vi.mock("./a", async (orig) => ({ ...(await orig()), a: vi.fn() }))\n',
+ # 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',
+ # 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',
+ _VI + 'vi.mock("./a", () => ({ a: new Map() }))\n',
+ _VI + 'vi.mock("./a", () => ({ [key]: 1 }))\n',
+ # A receiver not proven to be the runner's.
+ 'vi.mock("./a", () => ({ a: vi.fn() }))\n',
+ 'const jest = require("x")\njest.mock("./a", () => ({}))\n',
+ 'import jest from "jest-mock"\njest.mock("./a", () => ({}))\n',
+ 'const { jest } = require("./shim")\njest.mock("./a", () => ({}))\n',
+ 'function jest() {}\njest.mock("./a", () => ({}))\n',
+ 'try {} catch (jest) {}\njest.mock("./a", () => ({}))\n',
+ 'const f = jest => 1\njest.mock("./a", () => ({}))\n',
+ _VI + 'setup(vi)\nvi.mock("./a", () => ({}))\n',
+ 'import * as vt from "vitest"\nvt.jest.mock("./a", () => ({}))\n',
+ # Any unmock may name the same module by another specifier.
+ _VI + 'vi.mock("./a", () => ({}))\nvi.unmock("./a.ts")\n',
+ # A specifier built at run time, or a third argument.
+ _VI + 'vi.mock(`./${name}`, () => ({}))\n',
+ _VI + 'vi.mock(path, () => ({}))\n',
+ 'jest.mock("./a", () => ({}), { virtual: true })\n',
+ ],
+)
+def test_anything_unproven_swaps_nothing(source: str) -> None:
+ assert replaced_specifiers(_T, source) == frozenset()
+
+
+def test_a_dynamic_unmock_abstains_for_the_whole_file() -> None:
+ source = _VI + 'vi.mock("./a", () => ({}))\nvi.unmock(name)\n'
+ assert replaced_specifiers(_T, source) == frozenset()
+
+
+def test_only_a_relative_specifier_resolving_to_a_repo_file_masks() -> None:
+ files = {"src/a.ts", "lib/b/index.ts", "src/c.js", _T, "src/y.test.js"}
+ texts = {
+ _T: _VI + 'vi.mock("./a", () => ({}))\nvi.mock("lodash", () => ({}))\n',
+ "src/y.test.js": (
+ 'jest.mock("../lib/b", () => ({}))\njest.mock("./c", () => ({}))\n'
+ 'jest.mock("./missing", () => ({}))\njest.mock("@app/c", () => ({}))\n'
+ ),
+ }
+ assert replaced_files(texts, files) == {
+ _T: frozenset({"src/a.ts"}),
+ "src/y.test.js": frozenset({"lib/b/index.ts", "src/c.js"}),
+ }
diff --git a/tests/unit/persistence/test_test_reachability_walk.py b/tests/unit/persistence/test_test_reachability_walk.py
index 1f364b0ec..677c4c620 100644
--- a/tests/unit/persistence/test_test_reachability_walk.py
+++ b/tests/unit/persistence/test_test_reachability_walk.py
@@ -737,6 +737,8 @@ _SWAPPED = {
'@patch("app.util")\ndef test_run(m):\n assert run()\n'
),
"tests/test_util.py": "from app.util import helper\n\ndef test_helper():\n assert helper()\n",
+ "web/a.ts": "export const a = 1;\n",
+ "web/a.test.ts": 'import {vi} from "vitest";\nvi.mock("./a", () => ({a: 2}));\n',
}
@@ -762,7 +764,8 @@ async def test_any_reach_reads_which_tests_replace_a_module_from_the_checkout(
clear_test_map_cache()
assert await cached_test_masks(async_session, repo.id) == {
- "tests/test_core.py": frozenset({"app/util.py"})
+ "tests/test_core.py": frozenset({"app/util.py"}),
+ "web/a.test.ts": frozenset({"web/a.ts"}),
}
found = await any_tests_reaching(async_session, repo.id, ["app/core.py", "app/util.py"])
assert found["app/core.py"].reached.tests == ["tests/test_core.py"]
@@ -986,15 +989,22 @@ async def test_the_stored_walk_and_the_in_memory_walk_return_the_same_rows(tmp_p
assert in_memory["app/types.py"].state == "type_only"
assert {in_memory[p].state for p in in_memory} >= {"reached", "unreached", "new"}
- # Both tests swap ``app.util`` out, so only replacing tests reach it.
+ # Both Python tests swap ``app.util`` out and the TS test swaps ``retry.ts``,
+ # so only replacing tests reach either.
swap = 'from unittest.mock import patch\n\n@patch("app.util")\ndef test_swapped(m): ...\n'
- masks = replaced_files(dict.fromkeys(["tests/test_core.py", "tests/test_pkg.py"], swap), _PARITY)
- assert masks == {t: {"app/util.py"} for t in ("tests/test_core.py", "tests/test_pkg.py")}
+ texts = dict.fromkeys(["tests/test_core.py", "tests/test_pkg.py"], swap)
+ texts["test/x.test.ts"] = 'import {vi} from "vitest";\nvi.mock("../src/retry", () => ({retry: 1}));\n'
+ masks = replaced_files(texts, _PARITY)
+ assert masks == {
+ **{t: {"app/util.py"} for t in ("tests/test_core.py", "tests/test_pkg.py")},
+ "test/x.test.ts": {"src/retry.ts"},
+ }
in_memory = reach_states(maps, asked, masks=masks, **evidence)
assert await reach_states_from_db(async_session, repo.id, asked, masks=masks, **evidence) == (
in_memory
)
assert in_memory["app/util.py"].state == "mocked_only"
+ assert in_memory["src/retry.ts"].state == "mocked_only"
assert in_memory["app/core.py"].state == "reached"