-
Notifications
You must be signed in to change notification settings - Fork 697
Expand file tree
/
Copy pathTestHelper.ts
More file actions
300 lines (263 loc) · 11 KB
/
Copy pathTestHelper.ts
File metadata and controls
300 lines (263 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import * as path from 'node:path';
import type * as child_process from 'node:child_process';
import {
FileSystem,
Executable,
JsonFile,
type FileSystemStats,
type JsonObject
} from '@rushstack/node-core-library';
import type { ITerminal } from '@rushstack/terminal';
/**
* Helper class for running integration tests with Rush package managers
*/
export class TestHelper {
private readonly _rushBinPath: string;
private readonly _terminal: ITerminal;
public constructor(terminal: ITerminal) {
this._terminal = terminal;
// Resolve rush bin path from @microsoft/rush dependency
this._rushBinPath = require.resolve('@microsoft/rush/lib/start-dev');
}
/**
* Execute a Rush command using the locally-built Rush
*/
public async executeRushAsync(
args: string[],
workingDirectory: string,
environment?: NodeJS.ProcessEnv
): Promise<void> {
this._terminal.writeLine(`Executing: ${process.argv0} ${this._rushBinPath} ${args.join(' ')}`);
const childProcess: child_process.ChildProcess = Executable.spawn(
process.argv0,
[this._rushBinPath, ...args],
{
currentWorkingDirectory: workingDirectory,
environment,
stdio: 'inherit'
}
);
await Executable.waitForExitAsync(childProcess, {
throwOnNonZeroExitCode: true
});
}
/**
* Create a test Rush repository with the specified package manager
*/
public async createTestRepoAsync(
testRepoPath: string,
packageManagerType: 'npm' | 'pnpm' | 'yarn',
packageManagerVersion: string
): Promise<void> {
// Clean up previous test run and create empty test repo directory
this._terminal.writeLine(`Creating test repository at ${testRepoPath}...`);
await FileSystem.ensureEmptyFolderAsync(testRepoPath);
// Initialize Rush repo
this._terminal.writeLine('Initializing Rush repo...');
await this.executeRushAsync(['init'], testRepoPath);
// Configure rush.json for the specified package manager
this._terminal.writeLine(`Configuring rush.json for ${packageManagerType} mode...`);
const rushJsonPath: string = path.join(testRepoPath, 'rush.json');
const rushJson: JsonObject = await JsonFile.loadAsync(rushJsonPath);
// Update package manager configuration
if (packageManagerType === 'npm') {
delete rushJson.pnpmVersion;
delete rushJson.yarnVersion;
rushJson.npmVersion = packageManagerVersion;
} else if (packageManagerType === 'pnpm') {
delete rushJson.npmVersion;
delete rushJson.yarnVersion;
rushJson.pnpmVersion = packageManagerVersion;
} else if (packageManagerType === 'yarn') {
delete rushJson.pnpmVersion;
delete rushJson.npmVersion;
rushJson.yarnVersion = packageManagerVersion;
}
// Add test projects
rushJson.projects = [
{
packageName: 'test-project-a',
projectFolder: 'projects/test-project-a'
},
{
packageName: 'test-project-b',
projectFolder: 'projects/test-project-b'
}
];
// Update nodeSupportedVersionRange to match current environment
rushJson.nodeSupportedVersionRange = '>=18.0.0';
await JsonFile.saveAsync(rushJson, rushJsonPath, { updateExistingFile: true });
}
/**
* Create a test project with the specified configuration
*/
public async createTestProjectAsync(
testRepoPath: string,
projectName: string,
version: string,
dependencies: Record<string, string>,
buildScript: string
): Promise<void> {
const projectPath: string = path.join(testRepoPath, 'projects', projectName);
await FileSystem.ensureFolderAsync(projectPath);
const packageJson: JsonObject = {
name: projectName,
version: version,
main: 'lib/index.js',
scripts: {
build: buildScript
},
dependencies: dependencies
};
await JsonFile.saveAsync(packageJson, path.join(projectPath, 'package.json'));
}
/**
* Verify that temp project tarballs were created
*/
public async verifyTempTarballsAsync(testRepoPath: string, projectNames: string[]): Promise<void> {
this._terminal.writeLine('\nVerifying temp project tarballs were created...');
for (const projectName of projectNames) {
const tarballPath: string = path.join(testRepoPath, 'common/temp/projects', `${projectName}.tgz`);
if (!(await FileSystem.existsAsync(tarballPath))) {
throw new Error(`ERROR: ${projectName}.tgz was not created!`);
}
}
this._terminal.writeLine('✓ Temp project tarballs created successfully');
}
/**
* Verify that dependencies are installed correctly
*/
public async verifyDependenciesAsync(
testRepoPath: string,
projectName: string,
expectedDependencies: string[]
): Promise<void> {
this._terminal.writeLine('\nVerifying node_modules structure...');
const projectPath: string = path.join(testRepoPath, 'projects', projectName);
const projectNodeModules: string = path.join(projectPath, 'node_modules');
for (const dep of expectedDependencies) {
const depPath: string = path.join(projectNodeModules, dep);
if (!(await FileSystem.existsAsync(depPath))) {
throw new Error(`ERROR: ${dep} not found in ${projectName}!`);
}
// Verify symlinks resolve correctly for local dependencies
if (dep.startsWith('test-project-')) {
const depRealPath: string = await FileSystem.getRealPathAsync(depPath);
const expectedPath: string = path.join(testRepoPath, 'projects', dep);
const expectedRealPath: string = await FileSystem.getRealPathAsync(expectedPath);
if (!(await this._doPathsReferToSameObjectAsync(depPath, expectedPath))) {
throw new Error(
`ERROR: Symlink for ${dep} does not resolve correctly!\n` +
`Expected: ${expectedRealPath}\n` +
`Actual: ${depRealPath}`
);
}
}
}
this._terminal.writeLine('✓ Dependencies installed correctly');
}
private async _doPathsReferToSameObjectAsync(path1: string, path2: string): Promise<boolean> {
const path1Stats: FileSystemStats = await FileSystem.getStatisticsAsync(path1);
const path2Stats: FileSystemStats = await FileSystem.getStatisticsAsync(path2);
return path1Stats.dev === path2Stats.dev && path1Stats.ino === path2Stats.ino;
}
/**
* Verify that PNPM's global virtual store was enabled and moved out of the workspace node_modules folder.
*/
public async verifyPnpmGlobalVirtualStoreAsync(
testRepoPath: string,
sharedStorePath: string
): Promise<void> {
this._terminal.writeLine('\nVerifying PNPM global virtual store structure...');
const workspaceFilePath: string = path.join(testRepoPath, 'common/temp/pnpm-workspace.yaml');
const workspaceFileContents: string = await FileSystem.readFileAsync(workspaceFilePath);
if (!workspaceFileContents.includes('enableGlobalVirtualStore: true')) {
throw new Error(`ERROR: enableGlobalVirtualStore was not written to ${workspaceFilePath}`);
}
const localVirtualStorePath: string = path.join(testRepoPath, 'common/temp/node_modules/.pnpm');
if (await FileSystem.existsAsync(localVirtualStorePath)) {
const localVirtualStoreItemNames: string[] =
await FileSystem.readFolderItemNamesAsync(localVirtualStorePath);
const unexpectedLocalPackageFolders: string[] = localVirtualStoreItemNames.filter(
(itemName) => itemName !== 'lock.yaml' && itemName !== 'node_modules'
);
if (unexpectedLocalPackageFolders.length > 0) {
throw new Error(
`ERROR: Expected ${localVirtualStorePath} to omit package instance folders, but found: ` +
unexpectedLocalPackageFolders.join(', ')
);
}
}
if (!(await FileSystem.existsAsync(sharedStorePath))) {
throw new Error(`ERROR: Shared PNPM store was not created at ${sharedStorePath}`);
}
const sharedStoreItemNames: string[] = await FileSystem.readFolderItemNamesAsync(sharedStorePath);
if (sharedStoreItemNames.length === 0) {
throw new Error(`ERROR: Shared PNPM store is empty at ${sharedStorePath}`);
}
const globalVirtualStorePath: string = await this._findPnpmGlobalVirtualStorePathAsync(sharedStorePath);
if (!(await FileSystem.existsAsync(globalVirtualStorePath))) {
throw new Error(
`ERROR: Expected PNPM global virtual store package links under ${sharedStorePath}, ` +
`but ${globalVirtualStorePath} was not found.`
);
}
const globalVirtualStoreItemNames: string[] =
await FileSystem.readFolderItemNamesAsync(globalVirtualStorePath);
if (globalVirtualStoreItemNames.length === 0) {
throw new Error(
`ERROR: PNPM global virtual store package links folder is empty at ${globalVirtualStorePath}`
);
}
this._terminal.writeLine('✓ PNPM global virtual store structure verified');
}
private async _findPnpmGlobalVirtualStorePathAsync(sharedStorePath: string): Promise<string> {
const sharedStoreVersionFolderNames: string[] =
await FileSystem.readFolderItemNamesAsync(sharedStorePath);
for (const folderName of sharedStoreVersionFolderNames) {
if (folderName.startsWith('v')) {
const linksPath: string = path.join(sharedStorePath, folderName, 'links');
if (await FileSystem.existsAsync(linksPath)) {
return linksPath;
}
}
}
return path.join(sharedStorePath, '<version>', 'links');
}
/**
* Verify that build outputs were created
*/
public async verifyBuildOutputsAsync(testRepoPath: string, projectNames: string[]): Promise<void> {
this._terminal.writeLine('\nVerifying build outputs...');
for (const projectName of projectNames) {
const outputPath: string = path.join(testRepoPath, 'projects', projectName, 'lib/index.js');
if (!(await FileSystem.existsAsync(outputPath))) {
throw new Error(`ERROR: ${projectName} build output not found!`);
}
}
this._terminal.writeLine('✓ Build completed successfully');
}
/**
* Test that the built code executes correctly
*/
public async testBuiltCodeAsync(testRepoPath: string, projectName: string): Promise<void> {
this._terminal.writeLine('\nTesting built code...');
const projectLib: string = path.join(testRepoPath, 'projects', projectName, 'lib/index.js');
// Use forward slashes for require() path on all platforms
const projectLibPosix: string = projectLib.split(path.sep).join(path.posix.sep);
// Use Executable.spawnSync to capture output
const result: string = Executable.spawnSync(
process.argv0,
['-e', `const b = require('${projectLibPosix}'); console.log(b.test());`],
{
currentWorkingDirectory: testRepoPath
}
).stdout.toString();
if (!result.includes('Using: Hello from A')) {
throw new Error('ERROR: Built code did not execute as expected!');
}
this._terminal.writeLine('✓ Built code executes correctly');
}
}