forked from peteromallet/desloppify
-
Notifications
You must be signed in to change notification settings - Fork 0
fix(js): add test coverage detection for JavaScript modules #29
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| """JavaScript-specific test coverage heuristics. | ||
|
|
||
| Supports Jest/Vitest/Mocha test naming conventions (.test.js, .spec.js) and | ||
| Node.js built-in assert module patterns. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import os | ||
| import re | ||
|
|
||
| _IMPORT_RE = re.compile( | ||
| r"""(?:\bfrom\s+|\bimport\s*\(\s*|\bimport\s+)(?:type\s+)?['"]([^'"]+)['"]|""" | ||
| r"""(?:\brequire\s*\(\s*)['"]([^'"]+)['"]""", | ||
| re.MULTILINE, | ||
| ) | ||
|
|
||
| # Patterns for detecting assertion calls in JS test files | ||
| ASSERT_PATTERNS = [ | ||
| re.compile(p) | ||
| for p in [ | ||
| r"expect\(", | ||
| r"assert\.", | ||
| r"\.should\.", | ||
| r"\b(?:getBy|findBy|getAllBy|findAllBy)\w+\(", | ||
| r"\.toBeInTheDocument\(", | ||
| r"\.toBeVisible\(", | ||
| r"\.toHaveTextContent\(", | ||
| r"\.toHaveAttribute\(", | ||
| ] | ||
| ] | ||
|
|
||
| MOCK_PATTERNS = [ | ||
| re.compile(p) | ||
| for p in [ | ||
| r"jest\.mock\(", | ||
| r"jest\.spyOn\(", | ||
| r"vi\.mock\(", | ||
| r"vi\.spyOn\(", | ||
| r"sinon\.", | ||
| ] | ||
| ] | ||
|
|
||
| SNAPSHOT_PATTERNS: list[re.Pattern[str]] = [] | ||
|
|
||
| # Detects test('name', ...) or it('name', ...) call patterns | ||
| TEST_FUNCTION_RE = re.compile(r"""(?:it|test)\s*\(\s*['"]""") | ||
|
|
||
|
|
||
| def parse_test_import_specs(content: str) -> set[str]: | ||
| """Extract import/require specs from a JavaScript test file.""" | ||
| return { | ||
| spec | ||
| for m in _IMPORT_RE.finditer(content) | ||
| if (spec := m.group(1) or m.group(2)) | ||
| } | ||
|
|
||
|
|
||
| def map_test_to_source(test_path: str, production_set: set[str]) -> str | None: | ||
| """Map a JavaScript test file to a production file by naming convention.""" | ||
| basename = os.path.basename(test_path) | ||
| dirname = os.path.dirname(test_path) | ||
| parent = os.path.dirname(dirname) | ||
|
|
||
| candidates: list[str] = [] | ||
|
|
||
| for pattern in (".test.", ".spec."): | ||
| if pattern in basename: | ||
| src = basename.replace(pattern, ".") | ||
| candidates.append(os.path.join(dirname, src)) | ||
| if parent: | ||
| candidates.append(os.path.join(parent, src)) | ||
|
|
||
| dir_basename = os.path.basename(dirname) | ||
| if dir_basename == "__tests__" and parent: | ||
| candidates.append(os.path.join(parent, basename)) | ||
|
|
||
| # Exact path match takes priority. | ||
| for c in candidates: | ||
| if c in production_set: | ||
| return c | ||
|
|
||
| # Deterministic basename fallback: build a sorted basename → path mapping, | ||
| # then return the first match across sorted candidates to avoid non-determinism | ||
| # when multiple production files share the same basename. | ||
| prod_base_map: dict[str, list[str]] = {} | ||
| for prod in sorted(production_set): | ||
| prod_base_map.setdefault(os.path.basename(prod), []).append(prod) | ||
|
|
||
| for c in sorted(candidates): | ||
| matches = prod_base_map.get(os.path.basename(c), []) | ||
| if matches: | ||
| return matches[0] | ||
|
|
||
| return None | ||
|
|
||
|
|
||
| def strip_test_markers(basename: str) -> str | None: | ||
| """Strip JavaScript test naming markers to derive a source basename.""" | ||
| for marker in (".test.", ".spec."): | ||
| if marker in basename: | ||
| return basename.replace(marker, ".") | ||
| return None | ||
|
|
||
|
|
||
| def resolve_import_spec( | ||
| spec: str, test_path: str, production_files: set[str] | ||
| ) -> str | None: | ||
| """Resolve a JS import spec to a production file path.""" | ||
| if not spec.startswith("."): | ||
| return None | ||
|
|
||
| base = os.path.dirname(test_path) | ||
| candidate = os.path.normpath(os.path.join(base, spec)) | ||
| for ext in ("", ".js", ".jsx", ".mjs", ".cjs", "/index.js", "/index.jsx"): | ||
| path = candidate + ext | ||
| if path in production_files: | ||
| return path | ||
|
|
||
| return None |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
79 changes: 79 additions & 0 deletions
79
desloppify/tests/lang/javascript/test_javascript_test_coverage.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| """Tests for JavaScript-specific test coverage detection hooks.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import os | ||
|
|
||
| from desloppify.languages.javascript import test_coverage as js_cov | ||
|
|
||
|
|
||
| def test_parse_test_import_specs_handles_esm_and_cjs() -> None: | ||
| content = ( | ||
| "import { foo } from './foo.js';\n" | ||
| "import './side-effect.js';\n" | ||
| "const bar = require('./bar');\n" | ||
| "import('./lazy.js');\n" | ||
| ) | ||
| specs = js_cov.parse_test_import_specs(content) | ||
| assert isinstance(specs, set) | ||
| assert "./foo.js" in specs | ||
| assert "./side-effect.js" in specs | ||
| assert "./bar" in specs | ||
| assert "./lazy.js" in specs | ||
|
|
||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| def test_parse_test_import_specs_deduplicates() -> None: | ||
| content = "require('./util');\nrequire('./util');\n" | ||
| specs = js_cov.parse_test_import_specs(content) | ||
| assert specs == {"./util"} | ||
|
|
||
|
|
||
| def test_parse_test_import_specs_returns_empty_set_for_no_imports() -> None: | ||
| assert js_cov.parse_test_import_specs("const x = 1;") == set() | ||
|
|
||
|
|
||
| def test_strip_test_markers_removes_test_suffix() -> None: | ||
| assert js_cov.strip_test_markers("server.test.js") == "server.js" | ||
| assert js_cov.strip_test_markers("util.spec.js") == "util.js" | ||
| assert js_cov.strip_test_markers("app.js") is None | ||
|
|
||
|
|
||
| def test_map_test_to_source_finds_sibling_file() -> None: | ||
| production_set = {"_ui/server.js", "_ui/github.js", "_ui/public/app.js"} | ||
| result = js_cov.map_test_to_source("_ui/server.test.js", production_set) | ||
| assert result == "_ui/server.js" | ||
|
|
||
|
|
||
| def test_map_test_to_source_returns_none_when_no_match() -> None: | ||
| production_set = {"_ui/server.js"} | ||
| result = js_cov.map_test_to_source("_ui/missing.test.js", production_set) | ||
| assert result is None | ||
|
|
||
|
|
||
| def test_resolve_import_spec_resolves_relative_js_path() -> None: | ||
| production = {"_ui/server.js", "_ui/github.js"} | ||
| result = js_cov.resolve_import_spec("./server.js", "_ui/server.test.js", production) | ||
| assert result == "_ui/server.js" | ||
|
|
||
|
|
||
| def test_resolve_import_spec_adds_js_extension() -> None: | ||
| production = {"_ui/server.js"} | ||
| result = js_cov.resolve_import_spec("./server", "_ui/server.test.js", production) | ||
| assert result == "_ui/server.js" | ||
|
|
||
|
|
||
| def test_resolve_import_spec_skips_node_modules() -> None: | ||
| production = {"_ui/server.js"} | ||
| result = js_cov.resolve_import_spec("express", "_ui/server.test.js", production) | ||
| assert result is None | ||
|
|
||
|
|
||
| def test_map_test_to_source_is_deterministic_on_basename_collision() -> None: | ||
| # Two production files with the same basename in different directories. | ||
| production = {"a/util.js", "b/util.js"} | ||
| result1 = js_cov.map_test_to_source("test/util.test.js", production) | ||
| # Call twice — result must be stable (no randomness from set iteration). | ||
| result2 = js_cov.map_test_to_source("test/util.test.js", production) | ||
| assert result1 == result2 | ||
| # Sorted basename fallback must pick the lexicographically first path. | ||
| assert result1 == "a/util.js" | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.