Skip to content

Commit 689f7b7

Browse files
committed
fix(@angular/build): resolve unit-test include patterns from the project root
The `include` option is documented by the builder schema as relative to the project root, but patterns were only ever resolved from the project source root. A library that keeps a secondary entry point beside `src` had no supported spelling that reached its specs, and the run still reported success. A pattern that matches nothing under the source root is now retried from the project root. A pattern that already matches is not retried, so an existing pattern keeps matching exactly what it matches today. A project rooted at the workspace root is never retried, since that would search every project. Closes #33467
1 parent 9b7a14a commit 689f7b7

4 files changed

Lines changed: 180 additions & 25 deletions

File tree

‎packages/angular/build/src/builders/unit-test/builder.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,7 @@ export async function* execute(
210210
normalizedOptions.exclude ?? [],
211211
normalizedOptions.workspaceRoot,
212212
normalizedOptions.projectSourceRoot,
213+
normalizedOptions.projectRoot,
213214
);
214215

215216
context.logger.info('Discovered test files:');

‎packages/angular/build/src/builders/unit-test/runners/vitest/build-options.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,7 @@ export async function getVitestBuildOptions(
185185
const {
186186
workspaceRoot,
187187
projectSourceRoot,
188+
projectRoot,
188189
include,
189190
polyfills,
190191
exclude = [],
@@ -194,7 +195,13 @@ export async function getVitestBuildOptions(
194195
} = options;
195196

196197
// Find test files
197-
const testFiles = await findTests(include, exclude, workspaceRoot, projectSourceRoot);
198+
const testFiles = await findTests(
199+
include,
200+
exclude,
201+
workspaceRoot,
202+
projectSourceRoot,
203+
projectRoot,
204+
);
198205
if (testFiles.length === 0) {
199206
throw new Error(
200207
'No tests found matching the following patterns:\n' +

‎packages/angular/build/src/builders/unit-test/test-discovery.ts‎

Lines changed: 76 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -29,53 +29,106 @@ const MAX_FILENAME_LENGTH = 128;
2929
* test file. If a user provides a path to a directory, it will find all test
3030
* files within that directory.
3131
*
32+
* A pattern that matches nothing under the project source root is retried from the
33+
* project root, which is what the builder's schema documents patterns to be relative
34+
* to. A pattern that already matches keeps matching exactly what it matches today, and
35+
* a project rooted at the workspace root is never retried, so a search never widens to
36+
* the whole workspace.
37+
*
3238
* @param include Glob patterns of files to include.
3339
* @param exclude Glob patterns of files to exclude.
3440
* @param workspaceRoot The absolute path to the workspace root.
3541
* @param projectSourceRoot The absolute path to the project's source root.
42+
* @param projectRoot The absolute path to the project root. Defaults to the source root.
3643
* @returns A unique set of absolute paths to all test files.
3744
*/
3845
export async function findTests(
3946
include: string[],
4047
exclude: string[],
4148
workspaceRoot: string,
4249
projectSourceRoot: string,
50+
projectRoot = projectSourceRoot,
4351
): Promise<string[]> {
4452
await initializeHash();
4553
const resolvedTestFiles = new Set<string>();
46-
const dynamicPatterns: string[] = [];
4754

48-
const projectRootPrefix = toPosixPath(relative(workspaceRoot, projectSourceRoot) + '/');
49-
const normalizedExcludes = exclude.map((p) => normalizePattern(p, projectRootPrefix));
55+
const unmatched = await collectTests(
56+
projectSourceRoot,
57+
include,
58+
exclude,
59+
workspaceRoot,
60+
resolvedTestFiles,
61+
);
62+
63+
// Retrying from the workspace root would search every project, so it is skipped.
64+
if (unmatched.length > 0 && projectRoot !== projectSourceRoot && projectRoot !== workspaceRoot) {
65+
await collectTests(projectRoot, unmatched, exclude, workspaceRoot, resolvedTestFiles);
66+
}
67+
68+
return [...resolvedTestFiles];
69+
}
70+
71+
/**
72+
* Resolves include patterns against a single root, adding every match to `found`.
73+
*
74+
* @param searchRoot The absolute path the patterns are resolved against.
75+
* @param include Glob patterns of files to include.
76+
* @param exclude Glob patterns of files to exclude.
77+
* @param workspaceRoot The absolute path to the workspace root.
78+
* @param found Accumulates the absolute path of every matched file.
79+
* @returns The patterns that matched nothing, so a caller can retry them elsewhere.
80+
*/
81+
async function collectTests(
82+
searchRoot: string,
83+
include: string[],
84+
exclude: string[],
85+
workspaceRoot: string,
86+
found: Set<string>,
87+
): Promise<string[]> {
88+
const relativeRoot = relative(workspaceRoot, searchRoot);
89+
const searchRootPrefix = relativeRoot ? toPosixPath(relativeRoot + '/') : '';
90+
const normalizedExcludes = exclude.map((p) => normalizePattern(p, searchRootPrefix));
91+
const unmatched: string[] = [];
5092

51-
// 1. Separate static and dynamic patterns
5293
for (const pattern of include) {
53-
const normalized = normalizePattern(pattern, projectRootPrefix);
94+
const normalized = normalizePattern(pattern, searchRootPrefix);
95+
const dynamicPatterns: string[] = [];
96+
97+
// 1. Separate static and dynamic patterns
5498
if (isDynamicPattern(pattern)) {
5599
dynamicPatterns.push(normalized);
56100
} else {
57-
const { resolved, unresolved } = await resolveStaticPattern(normalized, projectSourceRoot);
58-
resolved.forEach((file) => resolvedTestFiles.add(file));
59-
unresolved.forEach((p) => dynamicPatterns.push(p));
101+
const { resolved, unresolved } = await resolveStaticPattern(normalized, searchRoot);
102+
if (resolved.length > 0) {
103+
resolved.forEach((file) => found.add(file));
104+
continue;
105+
}
106+
dynamicPatterns.push(...unresolved);
60107
}
61-
}
62108

63-
// 2. Execute a single glob for all dynamic patterns
64-
if (dynamicPatterns.length > 0) {
65-
const globMatches = await glob(dynamicPatterns, {
66-
cwd: projectSourceRoot,
67-
absolute: true,
68-
expandDirectories: false,
69-
ignore: ['**/node_modules/**', ...normalizedExcludes],
70-
});
109+
// 2. Execute a glob for the pattern, so that a pattern which matches nothing here
110+
// can be told apart from one that does and retried against another root.
111+
const globMatches = dynamicPatterns.length
112+
? await glob(dynamicPatterns, {
113+
cwd: searchRoot,
114+
absolute: true,
115+
expandDirectories: false,
116+
ignore: ['**/node_modules/**', ...normalizedExcludes],
117+
})
118+
: [];
119+
120+
if (globMatches.length === 0) {
121+
unmatched.push(pattern);
122+
continue;
123+
}
71124

125+
// 3. Combine and de-duplicate results
72126
for (const match of globMatches) {
73-
resolvedTestFiles.add(toPosixPath(match));
127+
found.add(toPosixPath(match));
74128
}
75129
}
76130

77-
// 3. Combine and de-duplicate results
78-
return [...resolvedTestFiles];
131+
return unmatched;
79132
}
80133

81134
interface TestEntrypointsOptions {
@@ -255,7 +308,7 @@ function removeRoots(path: string, roots: string[]): string {
255308
* slashes, and making it relative to the project source root.
256309
*
257310
* @param pattern The glob pattern to normalize.
258-
* @param projectRootPrefix The POSIX-formatted prefix of the project's source root relative to the workspace root.
311+
* @param projectRootPrefix The POSIX-formatted prefix of the search root relative to the workspace root.
259312
* @returns A normalized glob pattern.
260313
*/
261314
function normalizePattern(pattern: string, projectRootPrefix: string): string {
@@ -266,8 +319,8 @@ function normalizePattern(pattern: string, projectRootPrefix: string): string {
266319
return posixPattern;
267320
}
268321

269-
// For relative paths, ensure they are correctly relative to the project source root.
270-
// This involves removing the project root prefix if the user provided a workspace-relative path.
322+
// For relative paths, ensure they are correctly relative to the search root.
323+
// This involves removing the root prefix if the user provided a workspace-relative path.
271324
const normalizedRelative = removePrefix(posixPattern, projectRootPrefix);
272325

273326
return normalizedRelative;

‎packages/angular/build/src/builders/unit-test/test-discovery_spec.ts‎

Lines changed: 95 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,11 @@
66
* found in the LICENSE file at https://angular.dev/license
77
*/
88

9+
import fs from 'node:fs';
10+
import os from 'node:os';
11+
import path from 'node:path';
912
import { initializeHash } from '../../utils/hash';
10-
import { generateNameFromPath, getTestEntrypoints } from './test-discovery';
13+
import { findTests, generateNameFromPath, getTestEntrypoints } from './test-discovery';
1114

1215
describe('getTestEntrypoints', () => {
1316
beforeAll(async () => {
@@ -170,3 +173,94 @@ describe('generateNameFromPath', () => {
170173
expect(result).toBe(name);
171174
});
172175
});
176+
177+
describe('findTests', () => {
178+
let workspaceRoot: string;
179+
let projectRoot: string;
180+
let projectSourceRoot: string;
181+
let insideSourceRoot: string;
182+
let outsideSourceRoot: string;
183+
184+
beforeAll(async () => {
185+
await initializeHash();
186+
187+
// The macOS temporary directory is a symlink, and the globber does not resolve one.
188+
workspaceRoot = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'find-tests-')));
189+
projectRoot = path.join(workspaceRoot, 'projects', 'my-lib');
190+
projectSourceRoot = path.join(projectRoot, 'src');
191+
insideSourceRoot = path.join(projectSourceRoot, 'lib', 'inside.spec.ts');
192+
outsideSourceRoot = path.join(projectRoot, 'secondary', 'outside.spec.ts');
193+
194+
for (const file of [insideSourceRoot, outsideSourceRoot]) {
195+
fs.mkdirSync(path.dirname(file), { recursive: true });
196+
fs.writeFileSync(file, '');
197+
}
198+
});
199+
200+
afterAll(() => {
201+
fs.rmSync(workspaceRoot, { recursive: true, force: true });
202+
});
203+
204+
it('should find a spec below the source root', async () => {
205+
const found = await findTests(
206+
['**/*.spec.ts'],
207+
[],
208+
workspaceRoot,
209+
projectSourceRoot,
210+
projectRoot,
211+
);
212+
213+
expect(found).toEqual([insideSourceRoot]);
214+
});
215+
216+
it('should find a spec below the project root but outside the source root', async () => {
217+
const found = await findTests(
218+
['secondary/**/*.spec.ts'],
219+
[],
220+
workspaceRoot,
221+
projectSourceRoot,
222+
projectRoot,
223+
);
224+
225+
expect(found).toEqual([outsideSourceRoot]);
226+
});
227+
228+
it('should find a static path below the project root', async () => {
229+
const found = await findTests(
230+
['secondary/outside.spec.ts'],
231+
[],
232+
workspaceRoot,
233+
projectSourceRoot,
234+
projectRoot,
235+
);
236+
237+
expect(found).toEqual([outsideSourceRoot]);
238+
});
239+
240+
it('should not widen a pattern that already matches below the source root', async () => {
241+
const found = await findTests(
242+
['**/*.spec.ts', 'secondary/**/*.spec.ts'],
243+
[],
244+
workspaceRoot,
245+
projectSourceRoot,
246+
projectRoot,
247+
);
248+
249+
// The first pattern stays anchored at the source root, so it must not also
250+
// collect the file the second pattern is there to reach.
251+
expect(found).toEqual([insideSourceRoot, outsideSourceRoot]);
252+
});
253+
254+
it('should not retry from a project root that is the workspace root', async () => {
255+
// Retrying there would search every project in the workspace.
256+
const found = await findTests(
257+
['projects/my-lib/secondary/**/*.spec.ts'],
258+
[],
259+
workspaceRoot,
260+
path.join(workspaceRoot, 'src'),
261+
workspaceRoot,
262+
);
263+
264+
expect(found).toEqual([]);
265+
});
266+
});

0 commit comments

Comments
 (0)