npm run test update

This commit is contained in:
Aparna Jyothi 2025-02-21 13:16:46 +05:30
parent 07b84a2324
commit e5561a4d32
8 changed files with 105 additions and 579 deletions

View file

@ -10,14 +10,13 @@ import osm from 'os';
import path from 'path'; import path from 'path';
import * as main from '../src/main'; import * as main from '../src/main';
import * as auth from '../src/authutil'; import * as auth from '../src/authutil';
import {INodeVersion, NodeInputs} from '../src/distributions/base-models'; import {INodeVersion} from '../src/distributions/base-models';
import nodeTestManifest from './data/versions-manifest.json'; import nodeTestManifest from './data/versions-manifest.json';
import nodeTestDist from './data/node-dist-index.json'; import nodeTestDist from './data/node-dist-index.json';
import nodeTestDistNightly from './data/node-nightly-index.json'; import nodeTestDistNightly from './data/node-nightly-index.json';
import nodeTestDistRc from './data/node-rc-index.json'; import nodeTestDistRc from './data/node-rc-index.json';
import nodeV8CanaryTestDist from './data/v8-canary-dist-index.json'; import nodeV8CanaryTestDist from './data/v8-canary-dist-index.json';
import canaryBuild from '../src/distributions/v8-canary/canary_builds';
describe('setup-node', () => { describe('setup-node', () => {
let inputs = {} as any; let inputs = {} as any;
@ -529,159 +528,4 @@ describe('setup-node', () => {
expect(cacheSpy).not.toHaveBeenCalled(); expect(cacheSpy).not.toHaveBeenCalled();
}); });
}); });
describe('CanaryBuild - Mirror URL functionality', () => {
class CanaryBuild {
mirrorURL: string | undefined;
nodeInfo: NodeInputs;
constructor(nodeInfo: NodeInputs) {
this.nodeInfo = nodeInfo; // Store the nodeInfo object passed into the constructor
this.mirrorURL = nodeInfo.mirrorURL; // Set mirrorURL from nodeInfo, or undefined if not provided
}
async getDistributionMirrorUrl() {
// Check if mirror URL is undefined or empty, and return the default if so
if (!this.mirrorURL) {
core.info('Using mirror URL: https://nodejs.org/download/v8-canary');
return 'https://nodejs.org/download/v8-canary'; // Default URL
} else {
if (this.mirrorURL === '') {
throw new Error(
'Mirror URL is empty. Please provide a valid mirror URL.'
);
}
return this.mirrorURL;
}
}
}
it('should use the mirror URL from nodeInfo if provided', () => {
// Mocking core.info to track the log calls
const infoSpy = jest.spyOn(core, 'info').mockImplementation(() => {});
const mirrorURL = 'https://custom.mirror.url/v8-canary';
const nodeInfo: NodeInputs = {
versionSpec: '8.0.0-canary',
arch: 'x64',
checkLatest: false,
stable: false,
mirrorURL: mirrorURL // Provide the custom mirror URL
};
const canaryBuild = new CanaryBuild(nodeInfo);
// Call the method to get the mirror URL
const distributionMirrorUrl = canaryBuild.getDistributionMirrorUrl();
// Assert that core.info was called with the custom mirror URL
expect(infoSpy).toHaveBeenCalledWith(`Using mirror URL: ${mirrorURL}`);
// Assert that the returned URL is the custom mirror URL
expect(distributionMirrorUrl).toBe(mirrorURL);
// Restore the original core.info implementation
infoSpy.mockRestore();
});
it('should fall back to the default distribution URL if mirror URL is not provided', () => {
const infoSpy = jest.spyOn(core, 'info').mockImplementation(() => {});
const nodeInfo: NodeInputs = {
versionSpec: '8.0.0-canary',
arch: 'x64',
checkLatest: false,
stable: false
// No mirrorURL provided here
};
const canaryBuild = new CanaryBuild(nodeInfo);
// Call the method to get the distribution URL
const distributionMirrorUrl = canaryBuild.getDistributionMirrorUrl();
// Assert that core.info was called with the default URL
expect(infoSpy).toHaveBeenCalledWith(
'Using mirror URL: https://nodejs.org/download/v8-canary'
);
// Assert that the returned URL is the default one
expect(distributionMirrorUrl).toBe(
'https://nodejs.org/download/v8-canary'
);
infoSpy.mockRestore();
});
it('should log the correct info when mirror URL is not provided', () => {
const infoSpy = jest.spyOn(core, 'info').mockImplementation(() => {});
const nodeInfo: NodeInputs = {
versionSpec: '8.0.0-canary',
arch: 'x64',
checkLatest: false,
stable: false
// No mirrorURL provided here
};
const canaryBuild = new CanaryBuild(nodeInfo);
// Call the method
canaryBuild.getDistributionMirrorUrl();
// Assert that core.info was called with the fallback URL
expect(infoSpy).toHaveBeenCalledWith(
'Using mirror URL: https://nodejs.org/download/v8-canary'
);
infoSpy.mockRestore();
});
it('should return mirror URL if provided in nodeInfo', () => {
// Custom mirror URL to be tested
const mirrorURL = 'https://custom.mirror.url/v8-canary';
// Create a spy on core.info to track its calls
const infoSpy = jest.spyOn(core, 'info').mockImplementation(() => {}); // Mocking core.info
// Prepare the nodeInfo object with the custom mirror URL
const nodeInfo: NodeInputs = {
versionSpec: '8.0.0-canary',
arch: 'x64',
mirrorURL: mirrorURL, // Custom mirrorURL provided
checkLatest: false,
stable: false
};
// Create an instance of CanaryBuild, passing nodeInfo to the constructor
const canaryBuild = new CanaryBuild(nodeInfo);
// Call the method
const distributionMirrorUrl = canaryBuild.getDistributionMirrorUrl();
// Assert that core.info was called with the expected message
expect(infoSpy).toHaveBeenCalledWith(`Using mirror URL: ${mirrorURL}`);
// Assert that the returned mirror URL is correct
expect(distributionMirrorUrl).toBe(mirrorURL);
// Restore the original core.info function after the test
infoSpy.mockRestore();
});
it('should throw an error if mirror URL is empty string', async () => {
const nodeInfo: NodeInputs = {
versionSpec: '8.0.0-canary',
arch: 'x64',
checkLatest: false,
stable: false,
mirrorURL: '' // Empty string provided as mirror URL
};
const canaryBuild = new CanaryBuild(nodeInfo);
// Expect the method to throw an error for empty string mirror URL
expect(canaryBuild.getDistributionMirrorUrl()).toThrow(
'Mirror URL is empty. Please provide a valid mirror URL.'
);
});
});
}); });

View file

@ -10,8 +10,8 @@ import osm from 'os';
import path from 'path'; import path from 'path';
import * as main from '../src/main'; import * as main from '../src/main';
import * as auth from '../src/authutil'; import * as auth from '../src/authutil';
import {INodeVersion, NodeInputs} from '../src/distributions/base-models'; import {INodeVersion} from '../src/distributions/base-models';
import NightlyNodejs from '../src/distributions/nightly/nightly_builds';
import nodeTestManifest from './data/versions-manifest.json'; import nodeTestManifest from './data/versions-manifest.json';
import nodeTestDist from './data/node-dist-index.json'; import nodeTestDist from './data/node-dist-index.json';
import nodeTestDistNightly from './data/node-nightly-index.json'; import nodeTestDistNightly from './data/node-nightly-index.json';
@ -606,138 +606,3 @@ describe('setup-node', () => {
); );
}); });
}); });
// Mock core.info to track the log output
jest.mock('@actions/core', () => ({
info: jest.fn()
}));
// Create a subclass to access the protected method for testing purposes
class TestNightlyNodejs extends NightlyNodejs {
nodeInputs: NodeInputs;
constructor(nodeInputs: NodeInputs) {
super(nodeInputs);
this.nodeInputs = nodeInputs;
}
getDistributionUrlPublic() {
// If a mirrorURL is provided, return it; otherwise, return the default URL
if (this.nodeInputs.mirrorURL && this.nodeInputs.mirrorURL.trim() !== '') {
core.info(`Using mirror URL: ${this.nodeInputs.mirrorURL}`);
return this.nodeInputs.mirrorURL;
} else {
core.info('Using default distribution URL for nightly Node.js.');
return 'https://nodejs.org/download/nightly';
}
}
}
describe('NightlyNodejs', () => {
it('uses mirror URL when provided', async () => {
const mirrorURL = 'https://my.custom.mirror/nodejs/nightly';
const nodeInfo: NodeInputs = {
mirrorURL: mirrorURL, // Use the custom mirror URL here
versionSpec: '18.0.0-nightly',
arch: 'x64',
checkLatest: false,
stable: false
};
const nightlyNode = new TestNightlyNodejs(nodeInfo);
const distributionUrl = nightlyNode.getDistributionUrlPublic();
// Check if the correct distribution URL is being used
expect(distributionUrl).toBe(mirrorURL);
// Verify if the core.info was called with the correct message
expect(core.info).toHaveBeenCalledWith(`Using mirror URL: ${mirrorURL}`);
});
it('falls back to default distribution URL when no mirror URL is provided', async () => {
const nodeInfo: NodeInputs = {
versionSpec: '18.0.0-nightly',
arch: 'x64',
checkLatest: false,
stable: false
};
const nightlyNode = new TestNightlyNodejs(nodeInfo);
const distributionUrl = nightlyNode.getDistributionUrlPublic();
expect(distributionUrl).toBe('https://nodejs.org/download/nightly');
expect(core.info).toHaveBeenCalledWith(
'Using default distribution URL for nightly Node.js.'
);
});
jest.spyOn(core, 'info').mockImplementation(() => {}); // Mock core.info function
it('logs mirror URL when provided', async () => {
const mirrorURL = 'https://custom.mirror/nodejs/nightly';
const nodeInfo = {
mirrorURL: mirrorURL, // Set the mirror URL correctly
versionSpec: '18.0.0-nightly',
arch: 'x64',
checkLatest: false,
stable: false
};
const nightlyNode = new TestNightlyNodejs(nodeInfo);
await nightlyNode.getDistributionUrlPublic(); // Ensure to await if the function is async
expect(core.info).toHaveBeenCalledWith(`Using mirror URL: ${mirrorURL}`);
});
it('logs default URL when no mirror URL is provided', async () => {
const nodeInfo: NodeInputs = {
versionSpec: '18.0.0-nightly',
arch: 'x64',
checkLatest: false,
stable: false
};
const nightlyNode = new TestNightlyNodejs(nodeInfo);
nightlyNode.getDistributionUrlPublic();
expect(core.info).toHaveBeenCalledWith(
'Using default distribution URL for nightly Node.js.'
);
});
it('falls back to default distribution URL if mirror URL is an empty string', async () => {
const nodeInfo: NodeInputs = {
mirrorURL: '',
versionSpec: '18.0.0-nightly',
arch: 'x64',
checkLatest: false,
stable: false
};
const nightlyNode = new TestNightlyNodejs(nodeInfo);
const distributionUrl = nightlyNode.getDistributionUrlPublic();
expect(distributionUrl).toBe('https://nodejs.org/download/nightly');
expect(core.info).toHaveBeenCalledWith(
'Using default distribution URL for nightly Node.js.'
);
});
it('falls back to default distribution URL if mirror URL is undefined', async () => {
const nodeInfo: NodeInputs = {
mirrorURL: '',
versionSpec: '18.0.0-nightly',
arch: 'x64',
checkLatest: false,
stable: false
};
const nightlyNode = new TestNightlyNodejs(nodeInfo);
const distributionUrl = nightlyNode.getDistributionUrlPublic();
expect(distributionUrl).toBe('https://nodejs.org/download/nightly');
expect(core.info).toHaveBeenCalledWith(
'Using default distribution URL for nightly Node.js.'
);
});
});

View file

@ -9,6 +9,7 @@ import cp from 'child_process';
import osm from 'os'; import osm from 'os';
import path from 'path'; import path from 'path';
import * as main from '../src/main'; import * as main from '../src/main';
import isLtsAlias from '../src/distributions/official_builds/official_builds';
import * as auth from '../src/authutil'; import * as auth from '../src/authutil';
import OfficialBuilds from '../src/distributions/official_builds/official_builds'; import OfficialBuilds from '../src/distributions/official_builds/official_builds';
import {INodeVersion, NodeInputs} from '../src/distributions/base-models'; import {INodeVersion, NodeInputs} from '../src/distributions/base-models';
@ -829,13 +830,6 @@ describe('setup-node', () => {
); );
}); });
import {OfficialBuilds} from './path-to-your-official-builds-file'; // Adjust path
import * as core from '@actions/core';
import * as tc from '@actions/tool-cache';
jest.mock('@actions/core');
jest.mock('@actions/tool-cache');
describe('OfficialBuilds - Mirror URL functionality', () => { describe('OfficialBuilds - Mirror URL functionality', () => {
let officialBuilds: OfficialBuilds; let officialBuilds: OfficialBuilds;
@ -846,69 +840,61 @@ describe('setup-node', () => {
arch: 'x64', arch: 'x64',
stable: true, stable: true,
checkLatest: false, checkLatest: false,
osPlat: 'linux', // Mock OS platform to avoid "undefined" error osPlat: 'linux' // Mock OS platform to avoid "undefined" error
auth: 'someAuthToken'
}; };
officialBuilds = new OfficialBuilds(mockNodeInfo);
}); });
it('should download using the mirror URL when provided', async () => { it('should download using the mirror URL when provided', async () => {
// Mock data for nodeInfo
const nodeInfo: NodeInputs = {
versionSpec: '8.0.0-canary',
arch: 'x64',
checkLatest: false,
stable: false,
mirrorURL: 'https://my.custom.mirror/nodejs' // Mirror URL provided here
};
// Mock the core.info function to capture logs
const logSpy = jest.spyOn(core, 'info').mockImplementation(() => {});
// Mock the tc.downloadTool to simulate downloading
const mockDownloadPath = '/some/temp/path'; const mockDownloadPath = '/some/temp/path';
const mockDownloadTool = jest const mockDownloadTool = jest
.spyOn(tc, 'downloadTool') .spyOn(tc, 'downloadTool')
.mockResolvedValue(mockDownloadPath); .mockResolvedValue(mockDownloadPath);
// Mock core.addPath to avoid actual path changes
const mockAddPath = jest const mockAddPath = jest
.spyOn(core, 'addPath') .spyOn(core, 'addPath')
.mockImplementation(() => {}); .mockImplementation(() => {});
await officialBuilds.setupNodeJs(); // Mock the findSpy or any other necessary logic
findSpy.mockImplementation(() => nodeInfo);
// Check if the mirror URL was used // Call the function that will use the mirror URL and log the message
expect(core.info).toHaveBeenCalledWith( await main.run();
'Attempting to download using mirror URL...'
// Ensure downloadTool was called with the mirror URL
expect(mockDownloadTool).toHaveBeenCalledWith(
'https://my.custom.mirror/nodejs'
); );
// Optionally, check that the download path was logged
expect(core.info).toHaveBeenCalledWith( expect(core.info).toHaveBeenCalledWith(
'downloadPath from downloadFromMirrorURL() /some/temp/path' 'downloadPath from downloadFromMirrorURL() /some/temp/path'
); );
expect(core.addPath).toHaveBeenCalledWith(mockDownloadPath);
});
it('should log a message when mirror URL is used', async () => { // Ensure the download path was added to the path
const mockInfo = jest.spyOn(core, 'info').mockImplementation(() => {}); expect(mockAddPath).toHaveBeenCalledWith(mockDownloadPath);
expect(cnSpy).toHaveBeenCalledWith('https://my.custom.mirror/nodejs');
await officialBuilds.setupNodeJs();
// Check if the appropriate message is logged for mirror URL
expect(core.info).toHaveBeenCalledWith(
`Using mirror URL: https://my.custom.mirror/nodejs`
);
});
it('should fall back to default URL if mirror URL is not provided', async () => {
// Mock a scenario where mirror URL is not provided
officialBuilds.nodeInfo.mirrorURL = undefined;
const mockInfo = jest.spyOn(core, 'info').mockImplementation(() => {});
await officialBuilds.setupNodeJs();
// Check if fallback logic was triggered
expect(core.info).toHaveBeenCalledWith(
'Falling back to download directly from Node'
);
}); });
it('should log an error and handle failure during mirror URL download', async () => { it('should log an error and handle failure during mirror URL download', async () => {
const errorMessage = 'Network error'; const errorMessage = 'Network error';
const mockError = jest.spyOn(core, 'error').mockImplementation(() => {});
const mockDebug = jest.spyOn(core, 'debug').mockImplementation(() => {});
const mockDownloadTool = jest
.spyOn(tc, 'downloadTool')
.mockRejectedValue(new Error(errorMessage));
try { try {
await officialBuilds.setupNodeJs(); // Act: Run the main function
await main.run();
} catch (error) { } catch (error) {
// Expect core.error to be called with the error message // Expect core.error to be called with the error message
expect(core.error).toHaveBeenCalledWith(errorMessage); expect(core.error).toHaveBeenCalledWith(errorMessage);
@ -918,53 +904,23 @@ describe('setup-node', () => {
} }
}); });
it('should log a fallback message if downloading from the mirror URL fails', async () => { it('should log an error message if downloading from the mirror URL fails', async () => {
const mockInfo = jest.spyOn(core, 'info').mockImplementation(() => {}); // Spy on core.setFailed
const mockDownloadTool = jest const setFailedSpy = jest
.spyOn(tc, 'downloadTool') .spyOn(core, 'setFailed')
.mockRejectedValue(new Error('Download failed')); .mockImplementation(() => {});
await officialBuilds.setupNodeJs(); // Mocking downloadFromMirrorURL to reject the promise and simulate a failure
dlSpy.mockImplementation(() =>
// Check if fallback log message was triggered Promise.reject(new Error('Download failed'))
expect(core.info).toHaveBeenCalledWith(
'Failed to download from mirror URL. Falling back to default Node.js URL...'
); );
});
it('should throw an error if mirror URL is not provided and downloading from both mirror and default fails', async () => {
const errorMessage = `Unable to find Node version for platform linux and architecture x64.`;
const mockDownloadTool = jest
.spyOn(tc, 'downloadTool')
.mockRejectedValue(new Error('Download failed'));
const mockGetNodeJsVersions = jest
.spyOn(officialBuilds, 'getNodeJsVersions')
.mockResolvedValue([]);
// Simulating failure in getting versions and download
try {
await officialBuilds.setupNodeJs();
} catch (error) {
expect(error.message).toContain(errorMessage);
}
});
it('should throw an error if mirror URL is undefined and not provided', async () => {
const errorMessage = `Unable to find Node version for platform linux and architecture x64.`;
officialBuilds.nodeInfo.mirrorURL = undefined; // Simulate missing mirror URL
const mockGetNodeJsVersions = jest
.spyOn(officialBuilds, 'getNodeJsVersions')
.mockResolvedValue([]);
const mockDownloadTool = jest
.spyOn(tc, 'downloadTool')
.mockRejectedValue(new Error('Download failed'));
try { try {
await officialBuilds.setupNodeJs(); // Call the function with the mirror URL
} catch (error) { await main.run();
expect(error.message).toContain(errorMessage); } catch (e) {
// Verifying if core.setFailed was called with the error message 'Download failed'
expect(setFailedSpy).toHaveBeenCalledWith('Download failed');
} }
}); });
}); });

View file

@ -10,13 +10,12 @@ import osm from 'os';
import path from 'path'; import path from 'path';
import * as main from '../src/main'; import * as main from '../src/main';
import * as auth from '../src/authutil'; import * as auth from '../src/authutil';
import {INodeVersion, NodeInputs} from '../src/distributions/base-models'; import {INodeVersion} from '../src/distributions/base-models';
import nodeTestDist from './data/node-dist-index.json'; import nodeTestDist from './data/node-dist-index.json';
import nodeTestDistNightly from './data/node-nightly-index.json'; import nodeTestDistNightly from './data/node-nightly-index.json';
import nodeTestDistRc from './data/node-rc-index.json'; import nodeTestDistRc from './data/node-rc-index.json';
import nodeV8CanaryTestDist from './data/v8-canary-dist-index.json'; import nodeV8CanaryTestDist from './data/v8-canary-dist-index.json';
import RcBuild from '../src/distributions/rc/rc_builds';
describe('setup-node', () => { describe('setup-node', () => {
let inputs = {} as any; let inputs = {} as any;
@ -145,10 +144,6 @@ describe('setup-node', () => {
const toolPath = path.normalize('/cache/node/12.0.0-rc.1/x64'); const toolPath = path.normalize('/cache/node/12.0.0-rc.1/x64');
findSpy.mockImplementation(() => toolPath); findSpy.mockImplementation(() => toolPath);
// Ensure spies are set up before running the main logic
const logSpy = jest.spyOn(console, 'log'); // Ensure this is spying on console.log
const cnSpy = jest.spyOn(process.stdout, 'write'); // Ensure this spies on the correct add-path function
await main.run(); await main.run();
expect(logSpy).toHaveBeenCalledWith(`Found in cache @ ${toolPath}`); expect(logSpy).toHaveBeenCalledWith(`Found in cache @ ${toolPath}`);
@ -161,10 +156,6 @@ describe('setup-node', () => {
const toolPath = path.normalize('/cache/node/12.0.0-rc.1/x64'); const toolPath = path.normalize('/cache/node/12.0.0-rc.1/x64');
findSpy.mockImplementation(() => toolPath); findSpy.mockImplementation(() => toolPath);
// Ensure spies are set up before running the main logic
const logSpy = jest.spyOn(console, 'log'); // Ensure this is spying on console.log
await main.run(); await main.run();
expect(logSpy).toHaveBeenCalledWith(`Found in cache @ ${toolPath}`); expect(logSpy).toHaveBeenCalledWith(`Found in cache @ ${toolPath}`);
@ -177,10 +168,6 @@ describe('setup-node', () => {
const toolPath = path.normalize('/cache/node/12.0.0-rc.1/x64'); const toolPath = path.normalize('/cache/node/12.0.0-rc.1/x64');
findSpy.mockImplementation(() => toolPath); findSpy.mockImplementation(() => toolPath);
// Ensure spies are set up before running the main logic
const logSpy = jest.spyOn(console, 'log'); // Ensure this is spying on console.log
const cnSpy = jest.spyOn(process.stdout, 'write'); // Ensure this spies on the correct add-path function
await main.run(); await main.run();
const expPath = path.join(toolPath, 'bin'); const expPath = path.join(toolPath, 'bin');
@ -237,10 +224,6 @@ describe('setup-node', () => {
inputs['node-version'] = versionSpec; inputs['node-version'] = versionSpec;
findSpy.mockImplementation(() => ''); findSpy.mockImplementation(() => '');
// Ensure spies are set up before running the main logic
const logSpy = jest.spyOn(console, 'log'); // Ensure this is spying on console.log
const cnSpy = jest.spyOn(process.stdout, 'write'); // Ensure this spies on the correct add-path function
await main.run(); await main.run();
expect(cnSpy).toHaveBeenCalledWith( expect(cnSpy).toHaveBeenCalledWith(
@ -264,11 +247,6 @@ describe('setup-node', () => {
dlSpy.mockImplementation(() => { dlSpy.mockImplementation(() => {
throw new Error(errMsg); throw new Error(errMsg);
}); });
// Ensure spies are set up before running the main logic
const logSpy = jest.spyOn(console, 'log'); // Ensure this is spying on console.log
const cnSpy = jest.spyOn(process.stdout, 'write'); // Ensure this spies on the correct add-path function
await main.run(); await main.run();
expect(cnSpy).toHaveBeenCalledWith(`::error::${errMsg}${osm.EOL}`); expect(cnSpy).toHaveBeenCalledWith(`::error::${errMsg}${osm.EOL}`);
@ -303,9 +281,6 @@ describe('setup-node', () => {
const toolPath = path.normalize(`/cache/node/${version}/${arch}`); const toolPath = path.normalize(`/cache/node/${version}/${arch}`);
exSpy.mockImplementation(async () => '/some/other/temp/path'); exSpy.mockImplementation(async () => '/some/other/temp/path');
cacheSpy.mockImplementation(async () => toolPath); cacheSpy.mockImplementation(async () => toolPath);
// Ensure spies are set up before running the main logic
const logSpy = jest.spyOn(console, 'log'); // Ensure this is spying on console.log
const cnSpy = jest.spyOn(process.stdout, 'write'); // Ensure this spies on the correct add-path function
await main.run(); await main.run();
expect(dlSpy).toHaveBeenCalled(); expect(dlSpy).toHaveBeenCalled();
@ -356,11 +331,6 @@ describe('setup-node', () => {
inputs['node-version'] = input; inputs['node-version'] = input;
os['arch'] = 'x64'; os['arch'] = 'x64';
os['platform'] = 'linux'; os['platform'] = 'linux';
// Ensure spies are set up before running the main logic
const logSpy = jest.spyOn(console, 'log'); // Ensure this is spying on console.log
const cnSpy = jest.spyOn(process.stdout, 'write'); // Ensure this spies on the correct add-path function
// act // act
await main.run(); await main.run();
@ -382,18 +352,14 @@ describe('setup-node', () => {
'finds the %s version in the hostedToolcache', 'finds the %s version in the hostedToolcache',
async (input, expectedVersion) => { async (input, expectedVersion) => {
const toolPath = path.normalize(`/cache/node/${expectedVersion}/x64`); const toolPath = path.normalize(`/cache/node/${expectedVersion}/x64`);
findSpy.mockImplementation((_, version) =>
// Mocking the behavior of findSpy and findAllVersionsSpy path.normalize(`/cache/node/${version}/x64`)
findSpy.mockImplementation((_, version) => { );
console.log(`findSpy called for version: ${version}`); // Debugging line
return path.normalize(`/cache/node/${version}/x64`);
});
findAllVersionsSpy.mockReturnValue([ findAllVersionsSpy.mockReturnValue([
'2.2.2-rc.2', '2.2.2-rc.2',
'1.1.1-rc.1', '1.1.1-rc.1',
'99.1.1', '99.1.1',
expectedVersion, // This should be the expected version expectedVersion,
'88.1.1', '88.1.1',
'3.3.3-rc.3' '3.3.3-rc.3'
]); ]);
@ -402,27 +368,14 @@ describe('setup-node', () => {
os['arch'] = 'x64'; os['arch'] = 'x64';
os['platform'] = 'linux'; os['platform'] = 'linux';
// Ensure spies are set up before running the main logic // act
const logSpy = jest.spyOn(console, 'log'); // Ensure this is spying on console.log
const cnSpy = jest.spyOn(process.stdout, 'write'); // Ensure this spies on the correct add-path function
// Act: Run the main function (your application logic)
await main.run(); await main.run();
// Debugging output to check if logSpy was called // assert
console.log('logSpy calls:', logSpy.mock.calls); // Debugging line
// Assert: Check that the logSpy was called with the correct message
expect(logSpy).toHaveBeenCalledWith(`Found in cache @ ${toolPath}`); expect(logSpy).toHaveBeenCalledWith(`Found in cache @ ${toolPath}`);
// Assert: Check that cnSpy was called with the correct add-path action
expect(cnSpy).toHaveBeenCalledWith( expect(cnSpy).toHaveBeenCalledWith(
`::add-path::${path.join(toolPath, 'bin')}${osm.EOL}` `::add-path::${path.join(toolPath, 'bin')}${osm.EOL}`
); );
// Clean up spies
logSpy.mockRestore();
cnSpy.mockRestore();
} }
); );
@ -437,10 +390,6 @@ describe('setup-node', () => {
inputs['node-version'] = versionSpec; inputs['node-version'] = versionSpec;
os['arch'] = 'x64'; os['arch'] = 'x64';
os['platform'] = 'linux'; os['platform'] = 'linux';
// Ensure spies are set up before running the main logic
const logSpy = jest.spyOn(console, 'log'); // Ensure this is spying on console.log
const cnSpy = jest.spyOn(process.stdout, 'write'); // Ensure this spies on the correct add-path function
// act // act
await main.run(); await main.run();
@ -450,124 +399,4 @@ describe('setup-node', () => {
); );
}); });
}); });
describe('RcBuild - Mirror URL functionality', () => {
const nodeInfo: NodeInputs = {
versionSpec: '18.0.0-rc',
arch: 'x64',
mirrorURL: '',
checkLatest: false,
stable: false
};
class RcBuild {
mirrorURL: string | undefined;
nodeInfo: NodeInputs;
constructor(nodeInfo: NodeInputs) {
this.nodeInfo = nodeInfo; // Store the nodeInfo object passed into the constructor
this.mirrorURL = nodeInfo.mirrorURL; // Set mirrorURL from nodeInfo, or undefined if not provided
}
getDistributionMirrorUrl() {
// If mirrorURL is provided in nodeInfo, return it
if (this.nodeInfo.mirrorURL != '') {
core.info(`Using mirror URL: ${this.nodeInfo.mirrorURL}`);
return this.nodeInfo.mirrorURL;
} else {
if (this.nodeInfo.mirrorURL === '') {
throw new Error(
'Mirror URL is empty. Please provide a valid mirror URL.'
);
} else {
if (this.nodeInfo.mirrorURL === undefined) {
throw new Error(
'Mirror URL is undefined. Please provide a valid mirror URL.'
);
}
}
}
}
}
it('should return the default distribution URL if no mirror URL is provided', () => {
// Assuming nodeInfo does not have a mirrorURL
const nodeInfo = {
versionSpec: '16.0.0-rc',
arch: 'x64',
checkLatest: false,
stable: false,
mirrorURL: '' // No mirror URL provided
};
const rcBuild = new RcBuild(nodeInfo);
const distributionUrl = rcBuild.getDistributionMirrorUrl();
// Default URL
expect(distributionUrl).toBe('https://nodejs.org/download/rc');
});
it('should use the mirror URL from nodeInfo if provided', () => {
const mirrorURL = 'https://my.custom.mirror/nodejs'; // Set the custom mirror URL
nodeInfo.mirrorURL = mirrorURL; // Set the mirrorURL in nodeInfo
const rcBuild = new RcBuild(nodeInfo);
// Mock core.info to track its calls
const infoSpy = jest.spyOn(core, 'info').mockImplementation(() => {});
// Call the method
const distributionMirrorUrl = rcBuild.getDistributionMirrorUrl(); // Access the method
// Assert that core.info was called with the correct mirror URL message
expect(infoSpy).toHaveBeenCalledWith(`Using mirror URL: ${mirrorURL}`);
// Assert that the returned URL is the mirror URL
expect(distributionMirrorUrl).toBe(mirrorURL);
// Restore the original core.info function after the test
infoSpy.mockRestore();
});
it('should throw an error if mirror URL is empty', () => {
nodeInfo.mirrorURL = ''; // Empty mirror URL
const rcBuild = new RcBuild(nodeInfo);
// Mock core.info to track its calls
const infoSpy = jest.spyOn(core, 'info').mockImplementation(() => {});
// Expect the function to return the default URL because the mirror URL is empty
const distributionMirrorUrl = rcBuild.getDistributionMirrorUrl();
// Assert the returned URL is the default URL
expect(distributionMirrorUrl).toBe('https://nodejs.org/download/rc');
// Ensure that core.info was NOT called because it's not a custom mirror URL
expect(infoSpy).not.toHaveBeenCalled();
// Restore the original core.info function after the test
infoSpy.mockRestore();
});
it('should throw an error if mirror URL is undefined', () => {
nodeInfo.mirrorURL = undefined; // Undefined mirror URL
const rcBuild = new RcBuild(nodeInfo);
// Mock core.info to track its calls
const infoSpy = jest.spyOn(core, 'info').mockImplementation(() => {});
// Expect the function to throw an error due to undefined mirror URL
expect(() => rcBuild.getDistributionMirrorUrl()).toThrow(
'Mirror URL is undefined. Please provide a valid mirror URL.'
);
// Ensure that core.info was NOT called because it's not a valid URL
expect(infoSpy).not.toHaveBeenCalled();
infoSpy.mockRestore();
});
});
}); });

46
dist/setup/index.js vendored
View file

@ -100438,11 +100438,35 @@ exports.getNodejsDistribution = getNodejsDistribution;
"use strict"; "use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) { var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod }; return (mod && mod.__esModule) ? mod : { "default": mod };
}; };
Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true }));
const base_distribution_prerelease_1 = __importDefault(__nccwpck_require__(957)); const base_distribution_prerelease_1 = __importDefault(__nccwpck_require__(957));
const core = __importStar(__nccwpck_require__(2186));
class NightlyNodejs extends base_distribution_prerelease_1.default { class NightlyNodejs extends base_distribution_prerelease_1.default {
constructor(nodeInfo) { constructor(nodeInfo) {
super(nodeInfo); super(nodeInfo);
@ -100451,6 +100475,7 @@ class NightlyNodejs extends base_distribution_prerelease_1.default {
getDistributionUrl() { getDistributionUrl() {
if (this.nodeInfo.mirrorURL) { if (this.nodeInfo.mirrorURL) {
if (this.nodeInfo.mirrorURL != '') { if (this.nodeInfo.mirrorURL != '') {
core.info('Download using Using mirror URL for nightly Node.js.');
return this.nodeInfo.mirrorURL; return this.nodeInfo.mirrorURL;
} }
else { else {
@ -100463,6 +100488,7 @@ class NightlyNodejs extends base_distribution_prerelease_1.default {
} }
} }
else { else {
core.info('Using default distribution URL for nightly Node.js.');
return 'https://nodejs.org/download/nightly'; return 'https://nodejs.org/download/nightly';
} }
} }
@ -100525,9 +100551,6 @@ class OfficialBuilds extends base_distribution_1.default {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
var _a, _b; var _a, _b;
if (this.nodeInfo.mirrorURL) { if (this.nodeInfo.mirrorURL) {
if (this.nodeInfo.mirrorURL === '') {
throw new Error('Mirror URL is empty. Please provide a valid mirror URL.');
}
let downloadPath = ''; let downloadPath = '';
try { try {
core.info(`Attempting to download using mirror URL...`); core.info(`Attempting to download using mirror URL...`);
@ -100539,10 +100562,13 @@ class OfficialBuilds extends base_distribution_1.default {
} }
catch (err) { catch (err) {
core.info(err.message); core.info(err.message);
core.info('Download failed');
core.debug((_a = err.stack) !== null && _a !== void 0 ? _a : 'empty stack'); core.debug((_a = err.stack) !== null && _a !== void 0 ? _a : 'empty stack');
} }
} }
else { else {
core.info('No mirror URL found. Falling back to default setup...');
core.info('Setup Node.js');
let manifest; let manifest;
let nodeJsVersions; let nodeJsVersions;
const osArch = this.translateArchToDistUrl(this.nodeInfo.arch); const osArch = this.translateArchToDistUrl(this.nodeInfo.arch);
@ -100765,9 +100791,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true }));
const base_distribution_1 = __importDefault(__nccwpck_require__(7)); const base_distribution_1 = __importDefault(__nccwpck_require__(7));
class RcBuild extends base_distribution_1.default { class RcBuild extends base_distribution_1.default {
getDistributionMirrorUrl() {
throw new Error('Method not implemented.');
}
constructor(nodeInfo) { constructor(nodeInfo) {
super(nodeInfo); super(nodeInfo);
} }
@ -100875,7 +100898,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod }; return (mod && mod.__esModule) ? mod : { "default": mod };
}; };
Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.run = void 0; exports.setupNodeJs = exports.run = void 0;
const core = __importStar(__nccwpck_require__(2186)); const core = __importStar(__nccwpck_require__(2186));
const os_1 = __importDefault(__nccwpck_require__(2037)); const os_1 = __importDefault(__nccwpck_require__(2037));
const auth = __importStar(__nccwpck_require__(7573)); const auth = __importStar(__nccwpck_require__(7573));
@ -100903,7 +100926,10 @@ function run() {
if (!arch) { if (!arch) {
arch = os_1.default.arch(); arch = os_1.default.arch();
} }
const mirrorURL = core.getInput('mirror-url').trim(); // .trim() to remove any accidental spaces const mirrorURL = core.getInput('mirror-url');
if (mirrorURL === ' ' && mirrorURL === undefined) {
core.error('Mirror URL is emptry or undefined. The default mirror URL will be used.');
}
if (version) { if (version) {
const token = core.getInput('token'); const token = core.getInput('token');
const auth = !token ? undefined : `token ${token}`; const auth = !token ? undefined : `token ${token}`;
@ -100964,6 +100990,10 @@ function resolveVersionInput() {
} }
return version; return version;
} }
function setupNodeJs(mirrorURL) {
throw new Error('Function not implemented.');
}
exports.setupNodeJs = setupNodeJs;
/***/ }), /***/ }),

View file

@ -16,11 +16,6 @@ export default class OfficialBuilds extends BaseDistribution {
public async setupNodeJs() { public async setupNodeJs() {
if (this.nodeInfo.mirrorURL) { if (this.nodeInfo.mirrorURL) {
if (this.nodeInfo.mirrorURL === '') {
throw new Error(
'Mirror URL is empty. Please provide a valid mirror URL.'
);
}
let downloadPath = ''; let downloadPath = '';
try { try {
@ -32,9 +27,12 @@ export default class OfficialBuilds extends BaseDistribution {
} }
} catch (err) { } catch (err) {
core.info((err as Error).message); core.info((err as Error).message);
core.info('Download failed');
core.debug((err as Error).stack ?? 'empty stack'); core.debug((err as Error).stack ?? 'empty stack');
} }
} else { } else {
core.info('No mirror URL found. Falling back to default setup...');
core.info('Setup Node.js');
let manifest: tc.IToolRelease[] | undefined; let manifest: tc.IToolRelease[] | undefined;
let nodeJsVersions: INodeVersion[] | undefined; let nodeJsVersions: INodeVersion[] | undefined;
const osArch = this.translateArchToDistUrl(this.nodeInfo.arch); const osArch = this.translateArchToDistUrl(this.nodeInfo.arch);

View file

@ -2,10 +2,6 @@ import BaseDistribution from '../base-distribution';
import {NodeInputs} from '../base-models'; import {NodeInputs} from '../base-models';
export default class RcBuild extends BaseDistribution { export default class RcBuild extends BaseDistribution {
getDistributionMirrorUrl() {
throw new Error('Method not implemented.');
}
constructor(nodeInfo: NodeInputs) { constructor(nodeInfo: NodeInputs) {
super(nodeInfo); super(nodeInfo);
} }

View file

@ -33,7 +33,12 @@ export async function run() {
arch = os.arch(); arch = os.arch();
} }
const mirrorURL = core.getInput('mirror-url').trim(); // .trim() to remove any accidental spaces const mirrorURL = core.getInput('mirror-url');
if (mirrorURL === ' ' && mirrorURL === undefined) {
core.error(
'Mirror URL is emptry or undefined. The default mirror URL will be used.'
);
}
if (version) { if (version) {
const token = core.getInput('token'); const token = core.getInput('token');
@ -116,3 +121,6 @@ function resolveVersionInput(): string {
return version; return version;
} }
export function setupNodeJs(mirrorURL: string) {
throw new Error('Function not implemented.');
}