@aiready/testability 0.4.18 → 0.5.0

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.
@@ -0,0 +1,210 @@
1
+ /* eslint-disable */
2
+ var addSorting = (function() {
3
+ 'use strict';
4
+ var cols,
5
+ currentSort = {
6
+ index: 0,
7
+ desc: false
8
+ };
9
+
10
+ // returns the summary table element
11
+ function getTable() {
12
+ return document.querySelector('.coverage-summary');
13
+ }
14
+ // returns the thead element of the summary table
15
+ function getTableHeader() {
16
+ return getTable().querySelector('thead tr');
17
+ }
18
+ // returns the tbody element of the summary table
19
+ function getTableBody() {
20
+ return getTable().querySelector('tbody');
21
+ }
22
+ // returns the th element for nth column
23
+ function getNthColumn(n) {
24
+ return getTableHeader().querySelectorAll('th')[n];
25
+ }
26
+
27
+ function onFilterInput() {
28
+ const searchValue = document.getElementById('fileSearch').value;
29
+ const rows = document.getElementsByTagName('tbody')[0].children;
30
+
31
+ // Try to create a RegExp from the searchValue. If it fails (invalid regex),
32
+ // it will be treated as a plain text search
33
+ let searchRegex;
34
+ try {
35
+ searchRegex = new RegExp(searchValue, 'i'); // 'i' for case-insensitive
36
+ } catch (error) {
37
+ searchRegex = null;
38
+ }
39
+
40
+ for (let i = 0; i < rows.length; i++) {
41
+ const row = rows[i];
42
+ let isMatch = false;
43
+
44
+ if (searchRegex) {
45
+ // If a valid regex was created, use it for matching
46
+ isMatch = searchRegex.test(row.textContent);
47
+ } else {
48
+ // Otherwise, fall back to the original plain text search
49
+ isMatch = row.textContent
50
+ .toLowerCase()
51
+ .includes(searchValue.toLowerCase());
52
+ }
53
+
54
+ row.style.display = isMatch ? '' : 'none';
55
+ }
56
+ }
57
+
58
+ // loads the search box
59
+ function addSearchBox() {
60
+ var template = document.getElementById('filterTemplate');
61
+ var templateClone = template.content.cloneNode(true);
62
+ templateClone.getElementById('fileSearch').oninput = onFilterInput;
63
+ template.parentElement.appendChild(templateClone);
64
+ }
65
+
66
+ // loads all columns
67
+ function loadColumns() {
68
+ var colNodes = getTableHeader().querySelectorAll('th'),
69
+ colNode,
70
+ cols = [],
71
+ col,
72
+ i;
73
+
74
+ for (i = 0; i < colNodes.length; i += 1) {
75
+ colNode = colNodes[i];
76
+ col = {
77
+ key: colNode.getAttribute('data-col'),
78
+ sortable: !colNode.getAttribute('data-nosort'),
79
+ type: colNode.getAttribute('data-type') || 'string'
80
+ };
81
+ cols.push(col);
82
+ if (col.sortable) {
83
+ col.defaultDescSort = col.type === 'number';
84
+ colNode.innerHTML =
85
+ colNode.innerHTML + '<span class="sorter"></span>';
86
+ }
87
+ }
88
+ return cols;
89
+ }
90
+ // attaches a data attribute to every tr element with an object
91
+ // of data values keyed by column name
92
+ function loadRowData(tableRow) {
93
+ var tableCols = tableRow.querySelectorAll('td'),
94
+ colNode,
95
+ col,
96
+ data = {},
97
+ i,
98
+ val;
99
+ for (i = 0; i < tableCols.length; i += 1) {
100
+ colNode = tableCols[i];
101
+ col = cols[i];
102
+ val = colNode.getAttribute('data-value');
103
+ if (col.type === 'number') {
104
+ val = Number(val);
105
+ }
106
+ data[col.key] = val;
107
+ }
108
+ return data;
109
+ }
110
+ // loads all row data
111
+ function loadData() {
112
+ var rows = getTableBody().querySelectorAll('tr'),
113
+ i;
114
+
115
+ for (i = 0; i < rows.length; i += 1) {
116
+ rows[i].data = loadRowData(rows[i]);
117
+ }
118
+ }
119
+ // sorts the table using the data for the ith column
120
+ function sortByIndex(index, desc) {
121
+ var key = cols[index].key,
122
+ sorter = function(a, b) {
123
+ a = a.data[key];
124
+ b = b.data[key];
125
+ return a < b ? -1 : a > b ? 1 : 0;
126
+ },
127
+ finalSorter = sorter,
128
+ tableBody = document.querySelector('.coverage-summary tbody'),
129
+ rowNodes = tableBody.querySelectorAll('tr'),
130
+ rows = [],
131
+ i;
132
+
133
+ if (desc) {
134
+ finalSorter = function(a, b) {
135
+ return -1 * sorter(a, b);
136
+ };
137
+ }
138
+
139
+ for (i = 0; i < rowNodes.length; i += 1) {
140
+ rows.push(rowNodes[i]);
141
+ tableBody.removeChild(rowNodes[i]);
142
+ }
143
+
144
+ rows.sort(finalSorter);
145
+
146
+ for (i = 0; i < rows.length; i += 1) {
147
+ tableBody.appendChild(rows[i]);
148
+ }
149
+ }
150
+ // removes sort indicators for current column being sorted
151
+ function removeSortIndicators() {
152
+ var col = getNthColumn(currentSort.index),
153
+ cls = col.className;
154
+
155
+ cls = cls.replace(/ sorted$/, '').replace(/ sorted-desc$/, '');
156
+ col.className = cls;
157
+ }
158
+ // adds sort indicators for current column being sorted
159
+ function addSortIndicators() {
160
+ getNthColumn(currentSort.index).className += currentSort.desc
161
+ ? ' sorted-desc'
162
+ : ' sorted';
163
+ }
164
+ // adds event listeners for all sorter widgets
165
+ function enableUI() {
166
+ var i,
167
+ el,
168
+ ithSorter = function ithSorter(i) {
169
+ var col = cols[i];
170
+
171
+ return function() {
172
+ var desc = col.defaultDescSort;
173
+
174
+ if (currentSort.index === i) {
175
+ desc = !currentSort.desc;
176
+ }
177
+ sortByIndex(i, desc);
178
+ removeSortIndicators();
179
+ currentSort.index = i;
180
+ currentSort.desc = desc;
181
+ addSortIndicators();
182
+ };
183
+ };
184
+ for (i = 0; i < cols.length; i += 1) {
185
+ if (cols[i].sortable) {
186
+ // add the click event handler on the th so users
187
+ // dont have to click on those tiny arrows
188
+ el = getNthColumn(i).querySelector('.sorter').parentElement;
189
+ if (el.addEventListener) {
190
+ el.addEventListener('click', ithSorter(i));
191
+ } else {
192
+ el.attachEvent('onclick', ithSorter(i));
193
+ }
194
+ }
195
+ }
196
+ }
197
+ // adds sorting functionality to the UI
198
+ return function() {
199
+ if (!getTable()) {
200
+ return;
201
+ }
202
+ cols = loadColumns();
203
+ loadData();
204
+ addSearchBox();
205
+ addSortIndicators();
206
+ enableUI();
207
+ };
208
+ })();
209
+
210
+ window.addEventListener('load', addSorting);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiready/testability",
3
- "version": "0.4.18",
3
+ "version": "0.5.0",
4
4
  "description": "Measures how safely and verifiably AI-generated changes can be made to your codebase",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -40,7 +40,7 @@
40
40
  "chalk": "^5.3.0",
41
41
  "commander": "^14.0.0",
42
42
  "glob": "^13.0.0",
43
- "@aiready/core": "0.21.18"
43
+ "@aiready/core": "0.22.0"
44
44
  },
45
45
  "devDependencies": {
46
46
  "@types/node": "^24.0.0",
@@ -5,9 +5,10 @@ import { tmpdir } from 'os';
5
5
  import { describe, it, expect, beforeAll, afterAll } from 'vitest';
6
6
 
7
7
  describe('Testability Analyzer', () => {
8
- const tmpDir = join(tmpdir(), 'aiready-testability-tests');
8
+ let tmpDir: string;
9
9
 
10
10
  beforeAll(() => {
11
+ tmpDir = join(tmpdir(), `aiready-testability-complex-${Date.now()}`);
11
12
  mkdirSync(tmpDir, { recursive: true });
12
13
  });
13
14
 
@@ -23,74 +24,82 @@ describe('Testability Analyzer', () => {
23
24
  return filePath;
24
25
  }
25
26
 
26
- describe('Test Coverage Ratio', () => {
27
- it('should calculate ratio of test files to source files', async () => {
28
- createTestFile('src/math.ts', 'export const add = (a, b) => a + b;');
29
- createTestFile(
30
- 'src/math.test.ts',
31
- 'import { add } from "./math"; test("add", () => {});'
32
- );
33
- createTestFile(
34
- 'src/string.ts',
35
- 'export const upper = (s) => s.toUpperCase();'
36
- );
27
+ it('detects test frameworks in multiple languages', async () => {
28
+ const pyDir = join(tmpDir, 'python-project');
29
+ mkdirSync(pyDir);
30
+ writeFileSync(join(pyDir, 'requirements.txt'), 'pytest==7.0.0');
31
+ writeFileSync(join(pyDir, 'app.py'), 'def add(a, b): return a + b');
32
+ writeFileSync(join(pyDir, 'test_app.py'), 'import pytest');
37
33
 
38
- const report = await analyzeTestability({ rootDir: tmpDir });
34
+ const javaDir = join(tmpDir, 'java-project');
35
+ mkdirSync(javaDir);
36
+ writeFileSync(
37
+ join(javaDir, 'pom.xml'),
38
+ '<project><dependencies><dependency><artifactId>junit</artifactId></dependency></dependencies></project>'
39
+ );
40
+ writeFileSync(join(javaDir, 'App.java'), 'public class App {}');
39
41
 
40
- expect(report.rawData.sourceFiles).toBeGreaterThanOrEqual(2);
41
- expect(report.rawData.testFiles).toBeGreaterThanOrEqual(1);
42
- });
43
- });
42
+ const goDir = join(tmpDir, 'go-project');
43
+ mkdirSync(goDir);
44
+ writeFileSync(join(goDir, 'go.mod'), 'module test');
45
+ writeFileSync(join(goDir, 'main.go'), 'package main');
44
46
 
45
- describe('Pure Functions and State Mutations', () => {
46
- it('should detect state mutations inside functions', async () => {
47
- createTestFile(
48
- 'src/mutations.ts',
49
- `
50
- const globalState = { value: 0 };
51
-
52
- export function impureAdd(a: number) {
53
- globalState.value += a; // mutation here
54
- return globalState.value;
55
- }
47
+ // Test Python detection
48
+ const pyReport = await analyzeTestability({ rootDir: pyDir });
49
+ expect(pyReport.rawData.hasTestFramework).toBe(true);
56
50
 
57
- export function pureAdd(a: number, b: number) {
58
- return a + b;
59
- }
60
- `
61
- );
51
+ // Test Java detection
52
+ const javaReport = await analyzeTestability({ rootDir: javaDir });
53
+ expect(javaReport.rawData.hasTestFramework).toBe(true);
54
+
55
+ // Test Go detection (built-in)
56
+ const goReport = await analyzeTestability({ rootDir: goDir });
57
+ expect(goReport.rawData.hasTestFramework).toBe(true);
58
+ });
62
59
 
63
- const report = await analyzeTestability({ rootDir: tmpDir });
60
+ it('flags missing test framework as critical', async () => {
61
+ const emptyDir = join(tmpDir, 'no-tests');
62
+ mkdirSync(emptyDir);
63
+ writeFileSync(join(emptyDir, 'app.ts'), 'export const x = 1;');
64
64
 
65
- expect(report.rawData.externalStateMutations).toBeGreaterThanOrEqual(1);
66
- expect(report.rawData.pureFunctions).toBeGreaterThanOrEqual(1);
67
- });
65
+ const report = await analyzeTestability({ rootDir: emptyDir });
66
+ expect(report.rawData.hasTestFramework).toBe(false);
67
+ expect(
68
+ report.issues.some(
69
+ (i) => i.dimension === 'framework' && i.severity === 'critical'
70
+ )
71
+ ).toBe(true);
68
72
  });
69
73
 
70
- describe('Bloated Interfaces', () => {
71
- it('should detect interfaces with too many methods', async () => {
72
- createTestFile(
73
- 'src/interfaces.ts',
74
- `
75
- export interface BloatedService {
76
- m1(): void;
77
- m2(): void;
78
- m3(): void;
79
- m4(): void;
80
- m5(): void;
81
- m6(): void;
82
- m7(): void;
83
- m8(): void;
84
- m9(): void;
85
- m10(): void;
86
- m11(): void;
87
- }
74
+ it('detects injection patterns in classes', async () => {
75
+ createTestFile(
76
+ 'src/di.ts',
88
77
  `
89
- );
78
+ export class Service {
79
+ constructor(public db: any) {}
80
+ }
81
+ `
82
+ );
83
+ const report = await analyzeTestability({ rootDir: tmpDir });
84
+ expect(report.rawData.injectionPatterns).toBeGreaterThanOrEqual(1);
85
+ });
90
86
 
91
- const report = await analyzeTestability({ rootDir: tmpDir });
87
+ it('detects bloated interfaces', async () => {
88
+ createTestFile(
89
+ 'src/bloated.ts',
90
+ `
91
+ export interface Massive {
92
+ a(): void; b(): void; c(): void; d(): void; e(): void; f(): void; g(): void;
93
+ }
94
+ `
95
+ );
96
+ const report = await analyzeTestability({ rootDir: tmpDir });
97
+ expect(report.rawData.bloatedInterfaces).toBeGreaterThanOrEqual(1);
98
+ });
92
99
 
93
- expect(report.rawData.bloatedInterfaces).toBeGreaterThanOrEqual(1);
94
- });
100
+ it('gracefully handles missing parser or read errors', async () => {
101
+ createTestFile('src/config.json', '{"test": true}');
102
+ const report = await analyzeTestability({ rootDir: tmpDir });
103
+ expect(report.summary.sourceFiles).toBeDefined();
95
104
  });
96
105
  });
@@ -0,0 +1,36 @@
1
+ import { describe, it, expect, vi } from 'vitest';
2
+ import { TestabilityProvider } from '../provider';
3
+ import * as analyzer from '../analyzer';
4
+
5
+ vi.mock('../analyzer', () => ({
6
+ analyzeTestability: vi.fn(),
7
+ }));
8
+
9
+ describe('Testability Provider', () => {
10
+ it('should analyze and return SpokeOutput', async () => {
11
+ vi.mocked(analyzer.analyzeTestability).mockResolvedValue({
12
+ summary: { score: 90, dimensions: {} } as any,
13
+ issues: [],
14
+ rawData: { sourceFiles: 10, testFiles: 5 } as any,
15
+ recommendations: [],
16
+ });
17
+
18
+ const output = await TestabilityProvider.analyze({ rootDir: '.' });
19
+
20
+ expect(output.summary.score).toBe(90);
21
+ expect(output.metadata.toolName).toBe('testability-index');
22
+ });
23
+
24
+ it('should score an output', () => {
25
+ const mockOutput = {
26
+ summary: { score: 80, dimensions: {} } as any,
27
+ metadata: { rawData: {} },
28
+ results: [],
29
+ };
30
+
31
+ const scoring = TestabilityProvider.score(mockOutput as any, {
32
+ rootDir: '.',
33
+ });
34
+ expect(scoring.score).toBe(80);
35
+ });
36
+ });
@@ -0,0 +1,81 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { calculateTestabilityScore } from '../scoring';
3
+ import { TestabilityReport } from '../types';
4
+ import { ToolName } from '@aiready/core';
5
+
6
+ describe('Testability Scoring', () => {
7
+ const mockReport: TestabilityReport = {
8
+ summary: {
9
+ sourceFiles: 10,
10
+ testFiles: 5,
11
+ coverageRatio: 0.5,
12
+ score: 75,
13
+ rating: 'good',
14
+ aiChangeSafetyRating: 'safe',
15
+ dimensions: {
16
+ testCoverageRatio: 80,
17
+ purityScore: 70,
18
+ dependencyInjectionScore: 60,
19
+ interfaceFocusScore: 90,
20
+ observabilityScore: 80,
21
+ },
22
+ },
23
+ issues: [],
24
+ rawData: {
25
+ sourceFiles: 10,
26
+ testFiles: 5,
27
+ pureFunctions: 7,
28
+ totalFunctions: 10,
29
+ injectionPatterns: 3,
30
+ totalClasses: 5,
31
+ bloatedInterfaces: 0,
32
+ totalInterfaces: 2,
33
+ externalStateMutations: 2,
34
+ hasTestFramework: true,
35
+ },
36
+ recommendations: ['Add more tests'],
37
+ };
38
+
39
+ it('should map report to ToolScoringOutput correctly', () => {
40
+ const scoring = calculateTestabilityScore(mockReport);
41
+
42
+ expect(scoring.toolName).toBe(ToolName.TestabilityIndex);
43
+ expect(scoring.score).toBe(75);
44
+ expect(scoring.factors.length).toBe(5);
45
+
46
+ const coverageFactor = scoring.factors.find(
47
+ (f) => f.name === 'Test Coverage'
48
+ );
49
+ expect(coverageFactor?.impact).toBe(30); // 80 - 50
50
+ expect(coverageFactor?.description).toContain(
51
+ '5 test files / 10 source files'
52
+ );
53
+ });
54
+
55
+ it('should set high priority for high-risk recommendations', () => {
56
+ const highRiskReport: TestabilityReport = {
57
+ ...mockReport,
58
+ summary: {
59
+ ...mockReport.summary,
60
+ aiChangeSafetyRating: 'high-risk',
61
+ },
62
+ };
63
+
64
+ const scoring = calculateTestabilityScore(highRiskReport);
65
+ expect(scoring.recommendations[0].priority).toBe('high');
66
+ });
67
+
68
+ it('should set blind-risk impact correctly', () => {
69
+ const blindRiskReport: TestabilityReport = {
70
+ ...mockReport,
71
+ summary: {
72
+ ...mockReport.summary,
73
+ aiChangeSafetyRating: 'blind-risk',
74
+ },
75
+ };
76
+
77
+ const scoring = calculateTestabilityScore(blindRiskReport);
78
+ expect(scoring.recommendations[0].estimatedImpact).toBe(15);
79
+ expect(scoring.recommendations[0].priority).toBe('high');
80
+ });
81
+ });