mo3ta-coverage 1.0.8 → 1.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.test.js CHANGED
@@ -1,79 +1,113 @@
1
- import { main } from './cli';
2
- import * as child_process from 'child_process';
3
- import * as fs from 'fs';
4
- import * as path from 'path';
5
-
6
-
7
- jest.mock('child_process');
8
- jest.mock('fs');
9
- jest.mock('path');
10
-
11
- describe('main', () => {
12
- let originalExit;
13
- let exitMock;
14
- let consoleLogSpy;
15
- let consoleErrorSpy;
16
-
17
- beforeEach(() => {
18
- // Mock process.exit
19
- originalExit = process.exit;
20
- exitMock = jest.fn();
21
- process.exit = exitMock;
22
-
23
- // Mock console
24
- consoleLogSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
25
- consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
26
-
27
- // Reset mocks
28
- jest.clearAllMocks();
29
- });
30
-
31
- afterEach(() => {
32
- process.exit = originalExit;
33
- consoleLogSpy.mockRestore();
34
- consoleErrorSpy.mockRestore();
35
- });
36
-
37
- it('should log options and call getChangedFiles, runRelatedTests, and reportUncoveredChangedLines', () => {
38
- // Mock git check
39
- child_process.execSync.mockImplementationOnce(() => 'true');
40
- // Mock getChangedFiles
41
- const fakeFiles = ['src/foo.js', 'src/bar.ts'];
42
- // Mock execSync for getChangedFiles
43
- child_process.execSync.mockImplementationOnce(() => fakeFiles.join('\n'));
44
- // Mock execSync for runRelatedTests (jest run)
45
- child_process.execSync.mockImplementationOnce(() => {});
46
- // Mock fs.existsSync for lcov
47
- fs.existsSync.mockReturnValue(true);
48
- // Mock fs.readFileSync for lcov parsing
49
- fs.readFileSync.mockReturnValue(
50
- 'SF:/abs/path/src/foo.js\nDA:1,0\nDA:2,1\nend_of_record\nSF:/abs/path/src/bar.ts\nDA:3,0\nend_of_record\n'
51
- );
52
- // Mock path.resolve to identity for simplicity
53
- path.resolve.mockImplementation(x => '/abs/path/' + x);
54
-
55
- // Mock getChangedLines to return some lines
56
- jest.spyOn(child_process, 'execSync').mockImplementation((cmd) => {
57
- if (cmd.includes('git diff')) {
58
- return Buffer.from('@@ -0,0 +1,2 @@\n+foo\n+bar\n');
59
- }
60
- if (cmd.includes('git rev-parse')) {
61
- return Buffer.from('true');
62
- }
63
- if (cmd.includes('git log') || cmd.includes('git diff --name-only')) {
64
- return Buffer.from(fakeFiles.join('\n'));
65
- }
66
- return Buffer.from('');
67
- });
68
-
69
- main({ base: 'main', lcov: 'lcov.info', limit: '80', showCovered: true });
70
-
71
- expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('Options:'));
72
- // expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('Base Branch: main'));
73
- // expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('LCOV Path: lcov.info'));
74
- // expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('Coverage Limit: 80'));
75
- // expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('Show Covered Lines: true'));
76
- // expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('Files with changed lines:'));
77
- // expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('Overall coverage for all changed lines:'));
78
- });
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import {
5
+ classifyChangedLineCoverage,
6
+ formatMissedLinesSummary,
7
+ parseLcov,
8
+ summarizeCoverageResult
9
+ } from './cli.js';
10
+
11
+ function writeLcovFixture(records) {
12
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mo3ta-coverage-'));
13
+ const sourceFile = path.join(tempDir, 'src/example.js');
14
+ const lcovFile = path.join(tempDir, 'lcov.info');
15
+
16
+ fs.mkdirSync(path.dirname(sourceFile), { recursive: true });
17
+ fs.writeFileSync(sourceFile, 'const x = 1;\nconst y = 2;\n');
18
+ fs.writeFileSync(
19
+ lcovFile,
20
+ [
21
+ 'TN:',
22
+ `SF:${sourceFile}`,
23
+ ...records,
24
+ 'end_of_record'
25
+ ].join('\n')
26
+ );
27
+
28
+ return { sourceFile, lcovFile };
29
+ }
30
+
31
+ describe('parseLcov', () => {
32
+ it('records both coverableLines and uncoveredLines', () => {
33
+ const { sourceFile, lcovFile } = writeLcovFixture(['DA:10,1', 'DA:11,0']);
34
+
35
+ const result = parseLcov(lcovFile);
36
+
37
+ expect(result[sourceFile].coverableLines.has(10)).toBe(true);
38
+ expect(result[sourceFile].coverableLines.has(11)).toBe(true);
39
+ expect(result[sourceFile].uncoveredLines.has(10)).toBe(false);
40
+ expect(result[sourceFile].uncoveredLines.has(11)).toBe(true);
41
+ });
42
+ });
43
+
44
+ describe('classifyChangedLineCoverage', () => {
45
+ it('filters out changed lines not in LCOV (like imports)', () => {
46
+ const { sourceFile, lcovFile } = writeLcovFixture(['DA:10,1']);
47
+ const coverage = parseLcov(lcovFile)[sourceFile];
48
+
49
+ const result = classifyChangedLineCoverage([11, 12, 13, 14], coverage);
50
+
51
+ expect(result.coveredLines).toEqual([]);
52
+ expect(result.uncoveredLines).toEqual([]);
53
+ });
54
+
55
+ it('ignores changed lines with no LCOV entry and classifies rest as covered or uncovered', () => {
56
+ const { sourceFile, lcovFile } = writeLcovFixture(['DA:10,3', 'DA:11,0']);
57
+ const coverage = parseLcov(lcovFile)[sourceFile];
58
+
59
+ const result = classifyChangedLineCoverage([10, 11, 12, 13], coverage);
60
+
61
+ expect(result.coveredLines).toEqual([10]);
62
+ expect(result.uncoveredLines).toEqual([11]);
63
+ });
64
+
65
+ it('keeps existing behavior for normal covered and uncovered LCOV lines', () => {
66
+ const { sourceFile, lcovFile } = writeLcovFixture(['DA:20,5', 'DA:21,0']);
67
+ const coverage = parseLcov(lcovFile)[sourceFile];
68
+
69
+ const result = classifyChangedLineCoverage([20, 21], coverage);
70
+
71
+ expect(result.coveredLines).toEqual([20]);
72
+ expect(result.uncoveredLines).toEqual([21]);
73
+ });
74
+ });
75
+
76
+ describe('summarizeCoverageResult', () => {
77
+ it('passes when overall coverage equals the configured limit', () => {
78
+ const result = summarizeCoverageResult(5, 1, 80);
79
+
80
+ expect(result.overallCoverage).toBe(80);
81
+ expect(result.passed).toBe(true);
82
+ expect(result.icon).toBe('✅');
83
+ });
84
+
85
+ it('fails when overall coverage is below the configured limit', () => {
86
+ const result = summarizeCoverageResult(5, 2, 80);
87
+
88
+ expect(result.overallCoverage).toBe(60);
89
+ expect(result.passed).toBe(false);
90
+ expect(result.icon).toBe('🚨');
91
+ });
79
92
  });
93
+
94
+ describe('formatMissedLinesSummary', () => {
95
+ it('formats uncovered files and lines for the final summary', () => {
96
+ const result = formatMissedLinesSummary([
97
+ { filePath: 'src/a.js', lines: [10, 11] },
98
+ { filePath: 'src/b.js', lines: [7] }
99
+ ]);
100
+
101
+ expect(result).toEqual([
102
+ '',
103
+ 'Missed changed lines by file:',
104
+ ` - ${path.resolve('src/a.js')}:10`,
105
+ ` - ${path.resolve('src/a.js')}:11`,
106
+ ` - ${path.resolve('src/b.js')}:7`
107
+ ]);
108
+ });
109
+
110
+ it('returns no summary lines when no files have missed lines', () => {
111
+ expect(formatMissedLinesSummary([])).toEqual([]);
112
+ });
113
+ });
@@ -0,0 +1,92 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+
4
+ export function getJsOnlyFiles(files, runTestsOnly) {
5
+ // Only include source code files, exclude test, config, and json files
6
+ return files.filter(f => {
7
+ // Exclude test files
8
+ if (f.match(/(\.test|\.spec)\.(js|ts|jsx|tsx)$/)) return false || runTestsOnly;
9
+ // skip non test files when running only test files
10
+ if (runTestsOnly) return false;
11
+ // Exclude config files and files with .config. in their name
12
+ if (f.match(/(jest|babel|webpack|tsconfig|eslint|prettier|rollup|vite|package)\.(js|ts|json)$/) || f.includes('.config.')) return false;
13
+ // Exclude json files
14
+ if (f.endsWith('.json')) return false;
15
+ // Only include code files
16
+ return f.endsWith('.js') || f.endsWith('.ts') || f.endsWith('.jsx') || f.endsWith('.tsx');
17
+ });
18
+ }
19
+
20
+ /**
21
+ * Separates files into source files and test files
22
+ * @param {string[]} files - Array of file paths
23
+ * @returns {{sourceFiles: string[], testFiles: string[]}}
24
+ */
25
+ export function separateSourceAndTestFiles(files) {
26
+ const sourceFiles = [];
27
+ const testFiles = [];
28
+
29
+ files.forEach(file => {
30
+ // Exclude config files
31
+ if (file.match(/(jest|babel|webpack|tsconfig|eslint|prettier|rollup|vite|package)\.(js|ts|json)$/) || file.includes('.config.')) {
32
+ return;
33
+ }
34
+ // Exclude json files
35
+ if (file.endsWith('.json')) {
36
+ return;
37
+ }
38
+
39
+ // Check if it's a test file
40
+ if (file.match(/(\.test|\.spec)\.(js|ts|jsx|tsx)$/)) {
41
+ testFiles.push(file);
42
+ } else if (file.match(/\.(js|ts|jsx|tsx)$/)) {
43
+ sourceFiles.push(file);
44
+ }
45
+ });
46
+
47
+ return { sourceFiles, testFiles };
48
+ }
49
+
50
+ /**
51
+ * Finds potential test files for a given source file
52
+ * Checks multiple naming conventions and locations
53
+ * @param {string} sourceFile - Path to source file
54
+ * @returns {string[]} - Array of potential test file paths
55
+ */
56
+ export function findTestFilesForSource(sourceFile) {
57
+ const testFiles = [];
58
+ const parsed = path.parse(sourceFile);
59
+ const extensions = ['.js', '.ts', '.jsx', '.tsx'];
60
+
61
+ // Pattern 1: Same directory with .test or .spec suffix
62
+ // e.g., src/utils/helper.js → src/utils/helper.test.js
63
+ extensions.forEach(ext => {
64
+ testFiles.push(path.join(parsed.dir, `${parsed.name}.test${ext}`));
65
+ testFiles.push(path.join(parsed.dir, `${parsed.name}.spec${ext}`));
66
+ });
67
+
68
+ // Pattern 2: __tests__ subdirectory
69
+ // e.g., src/utils/helper.js → src/utils/__tests__/helper.test.js
70
+ extensions.forEach(ext => {
71
+ testFiles.push(path.join(parsed.dir, '__tests__', `${parsed.name}.test${ext}`));
72
+ testFiles.push(path.join(parsed.dir, '__tests__', `${parsed.name}.spec${ext}`));
73
+ testFiles.push(path.join(parsed.dir, '__tests__', `${parsed.name}${ext}`));
74
+ });
75
+
76
+ // Pattern 3: tests directory at same level
77
+ // e.g., src/utils/helper.js → src/tests/utils/helper.test.js
78
+ const srcMatch = sourceFile.match(/^(.*?\/src)\/(.*)/);
79
+ if (srcMatch) {
80
+ const baseDir = srcMatch[1];
81
+ const relativePath = srcMatch[2];
82
+ const relParsed = path.parse(relativePath);
83
+
84
+ extensions.forEach(ext => {
85
+ testFiles.push(path.join(baseDir, 'tests', relParsed.dir, `${relParsed.name}.test${ext}`));
86
+ testFiles.push(path.join(baseDir, 'tests', relParsed.dir, `${relParsed.name}.spec${ext}`));
87
+ });
88
+ }
89
+
90
+ // Check which test files actually exist
91
+ return testFiles.filter(testFile => fs.existsSync(testFile));
92
+ }
@@ -0,0 +1,234 @@
1
+ import { getJsOnlyFiles, separateSourceAndTestFiles, findTestFilesForSource } from './fileUtils';
2
+ import fs from 'fs';
3
+
4
+ describe('getJsOnlyFiles', () => {
5
+ const files = [
6
+ 'src/app.js',
7
+ 'src/utils.ts',
8
+ 'src/component.jsx',
9
+ 'src/page.tsx',
10
+ 'src/app.test.js',
11
+ 'src/utils.spec.ts',
12
+ 'src/config/jest.config.js',
13
+ 'src/config/babel.config.js',
14
+ 'src/config/webpack.config.js',
15
+ 'src/config/tsconfig.json',
16
+ 'src/config/eslint.config.js',
17
+ 'src/config/prettier.config.js',
18
+ 'src/config/rollup.config.js',
19
+ 'src/config/vite.config.js',
20
+ 'src/package.json',
21
+ 'src/data.json',
22
+ 'README.md',
23
+ 'src/styles.css'
24
+ ];
25
+
26
+ it('should include only source code files and exclude test, config, and json files', () => {
27
+ const result = getJsOnlyFiles(files, false);
28
+ expect(result).toEqual([
29
+ 'src/app.js',
30
+ 'src/utils.ts',
31
+ 'src/component.jsx',
32
+ 'src/page.tsx'
33
+ ]);
34
+ });
35
+
36
+ it('should exclude all files except test files when runTestsOnly is true', () => {
37
+ const result = getJsOnlyFiles(files, true);
38
+ expect(result).toEqual([
39
+ 'src/app.test.js',
40
+ 'src/utils.spec.ts',
41
+ ]);
42
+ });
43
+
44
+ it('should return empty array if no files match', () => {
45
+ const result = getJsOnlyFiles(['README.md', 'src/styles.css'], false);
46
+ expect(result).toEqual([]);
47
+ });
48
+
49
+ it('should exclude .json files', () => {
50
+ const result = getJsOnlyFiles(['src/data.json', 'src/app.js'], false);
51
+ expect(result).toEqual(['src/app.js']);
52
+ });
53
+
54
+ it('should exclude config files', () => {
55
+ const configFiles = [
56
+ 'jest.config.js',
57
+ 'babel.config.js',
58
+ 'webpack.config.js',
59
+ 'tsconfig.json',
60
+ 'eslint.config.js',
61
+ 'prettier.config.js',
62
+ 'rollup.config.js',
63
+ 'vite.config.js',
64
+ 'package.json'
65
+ ];
66
+ const result = getJsOnlyFiles(configFiles, false);
67
+ expect(result).toEqual([]);
68
+ });
69
+
70
+ it('should include only .js, .ts, .jsx, .tsx files', () => {
71
+ const result = getJsOnlyFiles([
72
+ 'src/app.js',
73
+ 'src/utils.ts',
74
+ 'src/component.jsx',
75
+ 'src/page.tsx',
76
+ 'src/other.txt'
77
+ ], false);
78
+ expect(result).toEqual([
79
+ 'src/app.js',
80
+ 'src/utils.ts',
81
+ 'src/component.jsx',
82
+ 'src/page.tsx'
83
+ ]);
84
+ });
85
+ });
86
+
87
+ describe('separateSourceAndTestFiles', () => {
88
+ it('should separate source and test files correctly', () => {
89
+ const files = [
90
+ 'src/app.js',
91
+ 'src/utils.ts',
92
+ 'src/app.test.js',
93
+ 'src/utils.spec.ts',
94
+ 'src/component.jsx',
95
+ 'src/component.test.jsx'
96
+ ];
97
+
98
+ const result = separateSourceAndTestFiles(files);
99
+
100
+ expect(result.sourceFiles).toEqual([
101
+ 'src/app.js',
102
+ 'src/utils.ts',
103
+ 'src/component.jsx'
104
+ ]);
105
+ expect(result.testFiles).toEqual([
106
+ 'src/app.test.js',
107
+ 'src/utils.spec.ts',
108
+ 'src/component.test.jsx'
109
+ ]);
110
+ });
111
+
112
+ it('should exclude config and json files', () => {
113
+ const files = [
114
+ 'src/app.js',
115
+ 'jest.config.js',
116
+ 'package.json',
117
+ 'src/data.json'
118
+ ];
119
+
120
+ const result = separateSourceAndTestFiles(files);
121
+
122
+ expect(result.sourceFiles).toEqual(['src/app.js']);
123
+ expect(result.testFiles).toEqual([]);
124
+ });
125
+
126
+ it('should handle empty array', () => {
127
+ const result = separateSourceAndTestFiles([]);
128
+
129
+ expect(result.sourceFiles).toEqual([]);
130
+ expect(result.testFiles).toEqual([]);
131
+ });
132
+
133
+ it('should handle all test files', () => {
134
+ const files = [
135
+ 'src/app.test.js',
136
+ 'src/utils.spec.ts'
137
+ ];
138
+
139
+ const result = separateSourceAndTestFiles(files);
140
+
141
+ expect(result.sourceFiles).toEqual([]);
142
+ expect(result.testFiles).toEqual([
143
+ 'src/app.test.js',
144
+ 'src/utils.spec.ts'
145
+ ]);
146
+ });
147
+ });
148
+
149
+ describe('findTestFilesForSource', () => {
150
+ // Mock fs.existsSync for testing
151
+ const originalExistsSync = fs.existsSync;
152
+
153
+ beforeEach(() => {
154
+ // Reset mock before each test
155
+ fs.existsSync = jest.fn();
156
+ });
157
+
158
+ afterEach(() => {
159
+ // Restore original function
160
+ fs.existsSync = originalExistsSync;
161
+ });
162
+
163
+ it('should find test file in same directory with .test.js pattern', () => {
164
+ fs.existsSync.mockImplementation((path) => {
165
+ return path === 'src/utils/helper.test.js';
166
+ });
167
+
168
+ const result = findTestFilesForSource('src/utils/helper.js');
169
+
170
+ expect(result).toContain('src/utils/helper.test.js');
171
+ });
172
+
173
+ it('should find test file in __tests__ subdirectory', () => {
174
+ fs.existsSync.mockImplementation((path) => {
175
+ return path === 'src/utils/__tests__/helper.test.js';
176
+ });
177
+
178
+ const result = findTestFilesForSource('src/utils/helper.js');
179
+
180
+ expect(result).toContain('src/utils/__tests__/helper.test.js');
181
+ });
182
+
183
+ it('should find multiple test files if they exist', () => {
184
+ fs.existsSync.mockImplementation((path) => {
185
+ return path === 'src/utils/helper.test.js' ||
186
+ path === 'src/utils/helper.spec.js';
187
+ });
188
+
189
+ const result = findTestFilesForSource('src/utils/helper.js');
190
+
191
+ expect(result).toContain('src/utils/helper.test.js');
192
+ expect(result).toContain('src/utils/helper.spec.js');
193
+ expect(result.length).toBe(2);
194
+ });
195
+
196
+ it('should return empty array if no test files exist', () => {
197
+ fs.existsSync.mockReturnValue(false);
198
+
199
+ const result = findTestFilesForSource('src/utils/helper.js');
200
+
201
+ expect(result).toEqual([]);
202
+ });
203
+
204
+ it('should find test files in parallel tests directory structure', () => {
205
+ fs.existsSync.mockImplementation((path) => {
206
+ // path.join normalizes paths, removing leading './'
207
+ return path === 'src/tests/utils/helper.test.js';
208
+ });
209
+
210
+ const result = findTestFilesForSource('./src/utils/helper.js');
211
+
212
+ expect(result).toContain('src/tests/utils/helper.test.js');
213
+ });
214
+
215
+ it('should handle TypeScript files', () => {
216
+ fs.existsSync.mockImplementation((path) => {
217
+ return path === 'src/utils/helper.test.ts';
218
+ });
219
+
220
+ const result = findTestFilesForSource('src/utils/helper.ts');
221
+
222
+ expect(result).toContain('src/utils/helper.test.ts');
223
+ });
224
+
225
+ it('should handle JSX files', () => {
226
+ fs.existsSync.mockImplementation((path) => {
227
+ return path === 'src/components/Button.test.jsx';
228
+ });
229
+
230
+ const result = findTestFilesForSource('src/components/Button.jsx');
231
+
232
+ expect(result).toContain('src/components/Button.test.jsx');
233
+ });
234
+ });
@@ -0,0 +1,20 @@
1
+ import { execSync } from 'child_process';
2
+ import { exit } from 'process';
3
+
4
+ export function verifyGitRepoExists() {
5
+ try {
6
+ execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' });
7
+ } catch (err) {
8
+ console.error(`❌ Not a git repository. Please run this tool inside a git repo. ${err.message}`);
9
+ exit(1);
10
+ }
11
+ }
12
+
13
+ export function verifyBaseBranchExists(BASE_BRANCH) {
14
+ try {
15
+ execSync(`git rev-parse --verify ${BASE_BRANCH}`, { stdio: 'ignore' });
16
+ } catch (err) {
17
+ console.error(`❌ Base branch "${BASE_BRANCH}" does not exist or is invalid. try git fetch to update your local branches.`);
18
+ exit(1);
19
+ }
20
+ }
@@ -1,29 +0,0 @@
1
- name: Publish Package
2
- on:
3
- push:
4
- branches:
5
- - main
6
-
7
- jobs:
8
- publish:
9
- runs-on: ubuntu-latest
10
- steps:
11
- - name: Checkout code
12
- uses: actions/checkout@v2
13
-
14
- - name: Set up Node.js
15
- uses: actions/setup-node@v2
16
- with:
17
- node-version: '16'
18
-
19
- - name: Install dependencies
20
- run: npm install
21
-
22
- # - name: Run tests
23
- # run: npm test
24
-
25
- - name: Configure npm authentication
26
- run: echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}" > ~/.npmrc
27
-
28
- - name: Publish package
29
- run: npm publish
@@ -1,4 +0,0 @@
1
- {
2
- "shallowTests": false,
3
- "base": "origin/dev"
4
- }