-
-
Notifications
You must be signed in to change notification settings - Fork 279
Expand file tree
/
Copy pathfoundryup.test.ts
More file actions
563 lines (488 loc) · 15.6 KB
/
foundryup.test.ts
File metadata and controls
563 lines (488 loc) · 15.6 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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
import type { Dir } from 'fs';
import { readFileSync } from 'fs';
import fs from 'fs/promises';
import nock, { cleanAll } from 'nock';
import { join, relative } from 'path';
import { parse as parseYaml } from 'yaml';
import {
checkAndDownloadBinaries,
getBinaryArchiveUrl,
getCacheDirectory,
} from '.';
import { parseArgs } from './options';
import type { Binary, Checksums } from './types';
import { Architecture, Platform } from './types';
import { isCodedError } from './utils';
type OperationDetails = {
path?: string;
repo?: string;
tag?: string;
version?: string;
platform?: Platform;
arch?: Architecture;
binaries?: string[];
binDir?: string;
cachePath?: string;
url?: URL;
checksums?: Checksums;
};
jest.mock('fs/promises', () => {
console.log('Mocking fs/promises');
const actualFs = jest.requireActual('fs/promises');
return {
...actualFs,
opendir: jest.fn().mockImplementation((path) => {
console.log('Mock opendir called with path:', path);
// Simulate ENOENT error for the first call
const error = new Error(
`ENOENT: no such file or directory, opendir '${path}`,
);
(error as NodeJS.ErrnoException).code = 'ENOENT';
throw error;
}),
mkdir: jest.fn().mockResolvedValue(undefined),
access: jest.fn().mockResolvedValue(undefined),
symlink: jest.fn(),
unlink: jest.fn(),
copyFile: jest.fn(),
rm: jest.fn(),
};
});
jest.mock('fs');
jest.mock('yaml');
jest.mock('os', () => ({
homedir: jest.fn().mockReturnValue('/home/user'),
}));
jest.mock('./options', () => ({
...jest.requireActual('./options'),
parseArgs: jest.fn(),
printBanner: jest.fn(),
say: jest.fn(),
getVersion: jest.fn().mockReturnValue('0.1.0'),
extractFrom: jest.fn().mockResolvedValue(['mock/path/to/binary']),
}));
const mockInstallBinaries = async (
downloadedBinaries: Dir,
BIN_DIR: string,
cachePath: string,
): Promise<{ operation: string; source?: string; target?: string }[]> => {
const mockOperations: {
operation: string;
source?: string;
target?: string;
}[] = [];
for await (const file of downloadedBinaries) {
if (!file.isFile()) {
continue;
}
const target = join(file.parentPath, file.name);
const path = join(BIN_DIR, relative(cachePath, target));
mockOperations.push({ operation: 'unlink', target: path });
try {
await fs.symlink(target, path);
mockOperations.push({
operation: 'symlink',
source: target,
target: path,
});
} catch (e) {
if (!(isCodedError(e) && ['EPERM', 'EXDEV'].includes(e.code))) {
throw e;
}
mockOperations.push({
operation: 'copyFile',
source: target,
target: path,
});
}
mockOperations.push({ operation: 'getVersion', target: path });
}
return mockOperations;
};
const mockDownloadAndInstallFoundryBinaries = async (): Promise<
{ operation: string; details?: OperationDetails }[]
> => {
const operations: { operation: string; details?: OperationDetails }[] = [];
const parsedArgs = parseArgs();
operations.push({ operation: 'getCacheDirectory' });
const CACHE_DIR = getCacheDirectory();
if (parsedArgs.command === 'cache clean') {
await fs.rm(CACHE_DIR, { recursive: true, force: true });
operations.push({ operation: 'cleanCache', details: { path: CACHE_DIR } });
return operations;
}
const {
repo,
version: { version, tag },
arch,
platform,
binaries,
} = parsedArgs.options;
operations.push({
operation: 'getBinaryArchiveUrl',
details: { repo, tag, version, platform, arch },
});
const BIN_ARCHIVE_URL = getBinaryArchiveUrl(
repo,
tag,
version,
platform,
arch,
);
const url = new URL(BIN_ARCHIVE_URL);
operations.push({
operation: 'checkAndDownloadBinaries',
details: { url, binaries, cachePath: CACHE_DIR, platform, arch },
});
operations.push({
operation: 'installBinaries',
details: {
binaries,
binDir: 'node_modules/.bin',
cachePath: CACHE_DIR,
},
});
return operations;
};
describe('foundryup', () => {
describe('getCacheDirectory', () => {
it('uses global cache when enabled in .yarnrc.yml', () => {
(parseYaml as jest.Mock).mockReturnValue({ enableGlobalCache: true });
(readFileSync as jest.Mock).mockReturnValue('dummy yaml content');
const result = getCacheDirectory();
expect(result).toMatch(/\/(home|Users)\/.*\/\.cache\/metamask$/u);
});
it('uses local cache when global cache is disabled', () => {
(parseYaml as jest.Mock).mockReturnValue({ enableGlobalCache: false });
(readFileSync as jest.Mock).mockReturnValue('dummy yaml content');
const result = getCacheDirectory();
expect(result).toContain('.metamask/cache');
});
});
describe('getBinaryArchiveUrl', () => {
it('generates correct download URL for Linux', () => {
const result = getBinaryArchiveUrl(
'foundry-rs/foundry',
'v1.0.0',
'1.0.0',
Platform.Linux,
Architecture.Amd64,
);
expect(result).toMatch(/^https:\/\/github.com\/.*\.tar\.gz$/u);
});
it('generates correct download URL for Windows', () => {
const result = getBinaryArchiveUrl(
'foundry-rs/foundry',
'v1.0.0',
'1.0.0',
Platform.Windows,
Architecture.Amd64,
);
expect(result).toMatch(/^https:\/\/github.com\/.*\.zip$/u);
});
});
describe('checkAndDownloadBinaries', () => {
const mockUrl = new URL('https://example.com/binaries.zip');
const mockBinaries = ['forge'] as Binary[];
const mockCachePath = './test-cache-path';
beforeEach(() => {
jest.clearAllMocks();
cleanAll();
});
it('handles download errors gracefully', async () => {
(fs.opendir as jest.Mock).mockRejectedValue({ code: 'ENOENT' });
cleanAll();
nock('https://example.com')
.head('/binaries.zip')
.reply(500, 'Internal Server Error')
.get('/binaries.zip')
.reply(500, 'Internal Server Error');
const result = checkAndDownloadBinaries(
mockUrl,
mockBinaries,
mockCachePath,
Platform.Linux,
Architecture.Amd64,
);
await expect(result).rejects.toThrow(
'Request to https://example.com/binaries.zip failed. Status Code: 500 - Internal Server Error',
);
});
});
describe('installBinaries', () => {
const mockBinDir = '/mock/bin/dir';
const mockCachePath = '/mock/cache/path';
const mockDir = {
async *[Symbol.asyncIterator]() {
yield {
name: 'forge',
isFile: () => true,
parentPath: mockCachePath,
};
},
} as unknown as Dir;
it('should correctly install binaries and create symlinks', async () => {
const operations = await mockInstallBinaries(
mockDir,
mockBinDir,
mockCachePath,
);
expect(operations).toStrictEqual([
{ operation: 'unlink', target: `${mockBinDir}/forge` },
{
operation: 'symlink',
source: `${mockCachePath}/forge`,
target: `${mockBinDir}/forge`,
},
{ operation: 'getVersion', target: `${mockBinDir}/forge` },
]);
});
it('should fall back to copying files when symlink fails with EPERM', async () => {
const epermError = new Error('EPERM') as NodeJS.ErrnoException;
epermError.code = 'EPERM';
// Mock symlink to fail
(fs.symlink as jest.Mock).mockRejectedValueOnce(epermError);
const operations = await mockInstallBinaries(
mockDir,
mockBinDir,
mockCachePath,
);
expect(operations).toStrictEqual([
{ operation: 'unlink', target: `${mockBinDir}/forge` },
{
operation: 'copyFile',
source: `${mockCachePath}/forge`,
target: `${mockBinDir}/forge`,
},
{ operation: 'getVersion', target: `${mockBinDir}/forge` },
]);
});
it('should throw error for non-permission-related symlink failures', async () => {
const otherError = new Error('Other error');
// Mock symlink to fail with other error
jest.spyOn(fs, 'symlink').mockRejectedValue(otherError);
await expect(
mockInstallBinaries(mockDir, mockBinDir, mockCachePath),
).rejects.toThrow('Other error');
});
});
describe('downloadAndInstallFoundryBinaries', () => {
const mockArgs = {
command: '',
options: {
repo: 'foundry-rs/foundry',
version: {
version: '1.0.0',
tag: 'v1.0.0',
},
arch: Architecture.Amd64,
platform: Platform.Linux,
binaries: ['forge', 'anvil'],
checksums: {
algorithm: 'sha256',
binaries: {
forge: {
'linux-amd64': 'mock-checksum',
'linux-arm64': 'mock-checksum',
'darwin-amd64': 'mock-checksum',
'darwin-arm64': 'mock-checksum',
'win32-amd64': 'mock-checksum',
'win32-arm64': 'mock-checksum',
},
anvil: {
'linux-amd64': 'mock-checksum',
'linux-arm64': 'mock-checksum',
'darwin-amd64': 'mock-checksum',
'darwin-arm64': 'mock-checksum',
'win32-amd64': 'mock-checksum',
'win32-arm64': 'mock-checksum',
},
},
},
},
};
beforeEach(() => {
jest.clearAllMocks();
const mockedOptions = jest.requireMock('./options');
mockedOptions.parseArgs.mockReturnValue(mockArgs);
mockedOptions.printBanner.mockImplementation(() => {
// Intentionally empty - used to suppress test output
});
mockedOptions.say.mockImplementation(jest.fn());
});
it('should execute all operations in correct order', async () => {
const operations = await mockDownloadAndInstallFoundryBinaries();
expect(operations).toStrictEqual([
{ operation: 'getCacheDirectory' },
{
operation: 'getBinaryArchiveUrl',
details: {
repo: 'foundry-rs/foundry',
tag: 'v1.0.0',
version: '1.0.0',
platform: Platform.Linux,
arch: Architecture.Amd64,
},
},
{
operation: 'checkAndDownloadBinaries',
details: expect.objectContaining({
binaries: ['forge', 'anvil'],
platform: Platform.Linux,
arch: Architecture.Amd64,
}),
},
{
operation: 'installBinaries',
details: {
binaries: ['forge', 'anvil'],
binDir: 'node_modules/.bin',
cachePath: expect.stringContaining('metamask'),
},
},
]);
});
it('should handle cache clean command', async () => {
const mockCleanArgs = {
...mockArgs,
command: 'cache clean',
};
(parseArgs as jest.Mock).mockReturnValue(mockCleanArgs);
const rmSpy = jest.spyOn(fs, 'rm').mockResolvedValue();
const operations = await mockDownloadAndInstallFoundryBinaries();
expect(operations).toStrictEqual([
{ operation: 'getCacheDirectory' },
{
operation: 'cleanCache',
details: {
path: expect.stringContaining('metamask'),
},
},
]);
expect(rmSpy).toHaveBeenCalled();
});
it('should handle errors gracefully', async () => {
jest.spyOn(fs, 'rm').mockRejectedValue(new Error('Mock error'));
const consoleSpy = jest.spyOn(console, 'error').mockImplementation();
const mockCleanArgs = {
...mockArgs,
command: 'cache clean',
};
(parseArgs as jest.Mock).mockReturnValue(mockCleanArgs);
await expect(mockDownloadAndInstallFoundryBinaries()).rejects.toThrow(
'Mock error',
);
consoleSpy.mockRestore();
});
});
describe('printBanner', () => {
it('should print the banner to the console', () => {
const { printBanner } = jest.requireActual('./options');
const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {
// Intentionally empty - used to suppress test output
});
printBanner();
expect(consoleSpy).toHaveBeenCalled();
expect(consoleSpy.mock.calls[0][0]).toContain(
'Portable and modular toolkit',
);
consoleSpy.mockRestore();
});
});
describe('parseArgs', () => {
let actualParseArgs: (args?: string[]) => {
command: string;
options: {
binaries: string[];
repo: string;
version: { version: string; tag: string };
arch: string;
platform: string;
checksums?: Checksums;
};
};
beforeEach(() => {
jest.unmock('./options');
const optionsModule = jest.requireActual('./options');
actualParseArgs = optionsModule.parseArgs;
});
afterEach(() => {
// Re-mock after each test
jest.doMock('./options', () => ({
...jest.requireActual('./options'),
parseArgs: jest.fn(),
printBanner: jest.fn(),
}));
});
describe('checksums option', () => {
it('should parse checksums from JSON string', () => {
const checksums = {
algorithm: 'sha256',
binaries: {
forge: {
'linux-amd64': 'abc123',
},
},
};
const result = actualParseArgs([
'--checksums',
JSON.stringify(checksums),
]);
expect(result.command).toBe('install');
expect(result.options.checksums).toStrictEqual(checksums);
});
it('should parse checksums with short flag -c', () => {
const checksums = { algorithm: 'sha256', binaries: {} };
const result = actualParseArgs(['-c', JSON.stringify(checksums)]);
expect(result.command).toBe('install');
expect(result.options.checksums).toStrictEqual(checksums);
});
});
describe('repo option', () => {
it('should parse custom repo with --repo flag', () => {
const result = actualParseArgs(['--repo', 'custom/repo']);
expect(result.command).toBe('install');
expect(result.options.repo).toBe('custom/repo');
});
it('should parse repo with short flag -r', () => {
const result = actualParseArgs(['-r', 'another/repo']);
expect(result.command).toBe('install');
expect(result.options.repo).toBe('another/repo');
});
});
describe('version option', () => {
it('should parse nightly version', () => {
const result = actualParseArgs(['--version', 'nightly']);
expect(result.command).toBe('install');
expect(result.options.version).toStrictEqual({
version: 'nightly',
tag: 'nightly',
});
});
it('should parse nightly with date suffix', () => {
const result = actualParseArgs(['--version', 'nightly-2024-01-01']);
expect(result.command).toBe('install');
expect(result.options.version).toStrictEqual({
version: 'nightly',
tag: 'nightly-2024-01-01',
});
});
it('should parse semantic version', () => {
const result = actualParseArgs(['--version', 'v1.2.3']);
expect(result.command).toBe('install');
expect(result.options.version).toStrictEqual({
version: 'v1.2.3',
tag: 'v1.2.3',
});
});
it('should parse version with short flag -v', () => {
const result = actualParseArgs(['-v', 'v2.0.0']);
expect(result.command).toBe('install');
expect(result.options.version).toStrictEqual({
version: 'v2.0.0',
tag: 'v2.0.0',
});
});
});
});
});