Compare commits

..

1 Commits

Author SHA1 Message Date
aparnajyothi-y
bd85b1cc02
Merge 19df1001b0 into 802632921f 2025-01-31 07:46:19 +00:00
9 changed files with 92 additions and 305 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;
@ -530,84 +529,3 @@ describe('setup-node', () => {
}); });
}); });
}); });
describe('CanaryBuild - Mirror URL functionality', () => {
const nodeInfo: NodeInputs = {
versionSpec: '18.0.0-rc', arch: 'x64', mirrorURL: '',
checkLatest: false,
stable: false
};
it('should return the default distribution URL if no mirror URL is provided', () => {
const canaryBuild = new CanaryBuild(nodeInfo);
// @ts-ignore: Accessing protected method for testing purposes
const distributionMirrorUrl = canaryBuild.getDistributionMirrorUrl();
expect(distributionMirrorUrl).toBe('https://nodejs.org/download/v8-canary');
});
it('should use the mirror URL from nodeInfo if provided', () => {
const mirrorURL = 'https://custom.mirror.url/v8-canary';
nodeInfo.mirrorURL = mirrorURL;
const canaryBuild = new CanaryBuild(nodeInfo);
// @ts-ignore: Accessing protected method for testing purposes
const distributionMirrorUrl = canaryBuild.getDistributionMirrorUrl();
expect(core.info).toHaveBeenCalledWith(`Using mirror URL: ${mirrorURL}`);
expect(distributionMirrorUrl).toBe(mirrorURL);
});
it('should fall back to the default distribution URL if mirror URL is not provided', () => {
nodeInfo.mirrorURL = ''; // No mirror URL
const canaryBuild = new CanaryBuild(nodeInfo);
// @ts-ignore: Accessing protected method for testing purposes
const distributionMirrorUrl = canaryBuild.getDistributionMirrorUrl();
expect(core.info).toHaveBeenCalledWith('Using mirror URL: https://nodejs.org/download/v8-canary');
expect(distributionMirrorUrl).toBe('https://nodejs.org/download/v8-canary');
});
it('should log the correct info when mirror URL is not provided', () => {
nodeInfo.mirrorURL = ''; // No mirror URL
const canaryBuild = new CanaryBuild(nodeInfo);
// @ts-ignore: Accessing protected method for testing purposes
canaryBuild.getDistributionMirrorUrl();
expect(core.info).toHaveBeenCalledWith('Using mirror URL: https://nodejs.org/download/v8-canary');
});
it('should return mirror URL if provided in nodeInfo', () => {
const mirrorURL = 'https://custom.mirror.url/v8-canary';
nodeInfo.mirrorURL = mirrorURL;
const canaryBuild = new CanaryBuild(nodeInfo);
// @ts-ignore: Accessing protected method for testing purposes
const distributionMirrorUrl = canaryBuild.getDistributionMirrorUrl();
expect(core.info).toHaveBeenCalledWith(`Using mirror URL: ${mirrorURL}`);
expect(distributionMirrorUrl).toBe(mirrorURL);
});
it('should use the default URL if mirror URL is empty string', () => {
nodeInfo.mirrorURL = ''; // Empty string for mirror URL
const canaryBuild = new CanaryBuild(nodeInfo);
// @ts-ignore: Accessing protected method for testing purposes
const distributionMirrorUrl = canaryBuild.getDistributionMirrorUrl();
expect(core.info).toHaveBeenCalledWith('Using mirror URL: https://nodejs.org/download/v8-canary');
expect(distributionMirrorUrl).toBe('https://nodejs.org/download/v8-canary');
});
it('should return the default URL if mirror URL is undefined', async () => {
// Create a spy on core.info
const infoSpy = jest.spyOn(core, 'info').mockImplementation(() => {}); // Mocking with empty implementation
// @ts-ignore: Accessing protected method for testing purposes
const distributionMirrorUrl = await canaryBuild.getDistributionMirrorUrl(); // Use await here
// Assert that core.info was called with the expected message
expect(infoSpy).toHaveBeenCalledWith('Using mirror URL: https://nodejs.org/download/v8-canary');
expect(distributionMirrorUrl).toBe('https://nodejs.org/download/v8-canary');
// Optional: Restore the original function after the test
infoSpy.mockRestore();
});
});

View File

@ -1,5 +1,4 @@
import * as core from '@actions/core'; import * as core from '@actions/core';
import 'jest';
import * as exec from '@actions/exec'; import * as exec from '@actions/exec';
import * as tc from '@actions/tool-cache'; import * as tc from '@actions/tool-cache';
import * as cache from '@actions/cache'; import * as cache from '@actions/cache';
@ -14,7 +13,6 @@ import each from 'jest-each';
import * as main from '../src/main'; import * as main from '../src/main';
import * as util from '../src/util'; import * as util from '../src/util';
import OfficialBuilds from '../src/distributions/official_builds/official_builds'; import OfficialBuilds from '../src/distributions/official_builds/official_builds';
import * as installerFactory from '../src/distributions/installer-factory'; import * as installerFactory from '../src/distributions/installer-factory';
jest.mock('../src/distributions/installer-factory', () => ({ jest.mock('../src/distributions/installer-factory', () => ({
getNodejsDistribution: jest.fn() getNodejsDistribution: jest.fn()
@ -288,36 +286,57 @@ describe('main tests', () => {
}); });
}); });
// Create a mock object that satisfies the BaseDistribution interface
// Mock the necessary modules
jest.mock('@actions/core');
jest.mock('./distributions/installer-factory');
// Create a mock object that satisfies the BaseDistribution type
const createMockNodejsDistribution = () => ({ const createMockNodejsDistribution = () => ({
setupNodeJs: jest.fn(), setupNodeJs: jest.fn(),
httpClient: {}, // Mocking the httpClient (you can replace this with more detailed mocks if needed) // Mocking other properties required by the BaseDistribution type (adjust based on your actual types)
osPlat: 'darwin', // Mocking osPlat (the platform the action will run on, e.g., 'darwin', 'win32', 'linux') httpClient: {}, // Example for httpClient, replace with proper mock if necessary
osPlat: 'darwin', // Example platform ('darwin', 'win32', 'linux', etc.)
nodeInfo: { nodeInfo: {
version: '14.x', version: '14.x',
arch: 'x64', arch: 'x64',
platform: 'darwin', platform: 'darwin',
}, },
getDistributionUrl: jest.fn().mockReturnValue('https://nodejs.org/dist/'), // Example URL getDistributionUrl: jest.fn().mockReturnValue('https://nodejs.org/dist/'), // Default distribution URL
install: jest.fn(), install: jest.fn(),
validate: jest.fn(), validate: jest.fn(),
// Add any other methods/properties required by your BaseDistribution type // Mock any other methods/properties defined in BaseDistribution
}); });
// Define the mock structure for BaseDistribution type (adjust to your actual type)
interface BaseDistribution {
setupNodeJs: jest.Mock;
httpClient: object;
osPlat: string;
nodeInfo: {
version: string;
arch: string;
platform: string;
};
getDistributionUrl: jest.Mock;
install: jest.Mock;
validate: jest.Mock;
}
describe('Mirror URL Tests', () => { describe('Mirror URL Tests', () => {
beforeEach(() => { beforeEach(() => {
jest.clearAllMocks(); jest.clearAllMocks();
}); });
it('should pass mirror URL correctly when provided', async () => { it('should pass mirror URL correctly when provided', async () => {
jest.spyOn(core, 'getInput').mockImplementation((name: string) => { (core.getInput as jest.Mock).mockImplementation((name: string) => {
if (name === 'mirror-url') return 'https://custom-mirror-url.com'; if (name === 'mirror-url') return 'https://custom-mirror-url.com';
if (name === 'node-version') return '14.x'; if (name === 'node-version') return '14.x';
return ''; return '';
}); });
const mockNodejsDistribution = createMockNodejsDistribution(); const mockNodejsDistribution = createMockNodejsDistribution();
(installerFactory.getNodejsDistribution as jest.Mock).mockReturnValue(mockNodejsDistribution); (installerFactory.getNodejsDistribution as unknown as jest.Mock<typeof installerFactory.getNodejsDistribution>).mockReturnValue(mockNodejsDistribution);
await main.run(); await main.run();
@ -333,7 +352,7 @@ describe('Mirror URL Tests', () => {
}); });
it('should use default mirror URL when no mirror URL is provided', async () => { it('should use default mirror URL when no mirror URL is provided', async () => {
jest.spyOn(core, 'getInput').mockImplementation((name: string) => { (core.getInput as jest.Mock).mockImplementation((name: string) => {
if (name === 'mirror-url') return ''; if (name === 'mirror-url') return '';
if (name === 'node-version') return '14.x'; if (name === 'node-version') return '14.x';
return ''; return '';
@ -344,39 +363,32 @@ describe('Mirror URL Tests', () => {
await main.run(); await main.run();
// Expect that setupNodeJs is called with an empty mirror URL // Expect that setupNodeJs is called with an empty mirror URL (which will default inside the function)
expect(mockNodejsDistribution.setupNodeJs).toHaveBeenCalledWith(expect.objectContaining({ expect(mockNodejsDistribution.setupNodeJs).toHaveBeenCalledWith(expect.objectContaining({
mirrorURL: '', // Default URL is expected to be handled internally mirrorURL: '', // Default URL is expected to be handled internally
})); }));
}); });
it('should handle mirror URL with spaces correctly', async () => { it('should handle mirror URL with spaces correctly', async () => {
const mirrorURL = 'https://custom-mirror-url.com '; (core.getInput as jest.Mock).mockImplementation((name: string) => {
const expectedTrimmedURL = 'https://custom-mirror-url.com'; if (name === 'mirror-url') return ' https://custom-mirror-url.com ';
if (name === 'node-version') return '14.x';
// Mock the setupNodeJs function return '';
const mockNodejsDistribution = {
setupNodeJs: jest.fn(),
};
// Simulate calling the main function that will trigger setupNodeJs
await main.run({ mirrorURL });
// Debugging: Log the arguments that setupNodeJs was called with
console.log('setupNodeJs calls:', mockNodejsDistribution.setupNodeJs.mock.calls);
// Assert that setupNodeJs was called with the correct trimmed mirrorURL
expect(mockNodejsDistribution.setupNodeJs).toHaveBeenCalledWith(
expect.objectContaining({
mirrorURL: expectedTrimmedURL,
})
);
}); });
const mockNodejsDistribution = createMockNodejsDistribution();
(installerFactory.getNodejsDistribution as jest.Mock).mockReturnValue(mockNodejsDistribution);
await main.run();
// Expect that setupNodeJs is called with the trimmed mirror URL
expect(mockNodejsDistribution.setupNodeJs).toHaveBeenCalledWith(expect.objectContaining({
mirrorURL: 'https://custom-mirror-url.com',
}));
});
it('should warn if architecture is provided but node-version is missing', async () => { it('should warn if architecture is provided but node-version is missing', async () => {
jest.spyOn(core, 'getInput').mockImplementation((name: string) => { (core.getInput as jest.Mock).mockImplementation((name: string) => {
if (name === 'architecture') return 'x64'; if (name === 'architecture') return 'x64';
if (name === 'node-version') return ''; if (name === 'node-version') return '';
return ''; return '';
@ -384,18 +396,14 @@ describe('Mirror URL Tests', () => {
const mockWarning = jest.spyOn(core, 'warning'); const mockWarning = jest.spyOn(core, 'warning');
const mockNodejsDistribution = createMockNodejsDistribution(); const mockNodejsDistribution = createMockNodejsDistribution();
(installerFactory.getNodejsDistribution as jest.Mock).mockReturnValue(mockNodejsDistribution); installerFactory.getNodejsDistribution.mockReturnValue(mockNodejsDistribution);
await main.run(); await main.run();
expect(mockWarning).toHaveBeenCalledWith( expect(mockWarning).toHaveBeenCalledWith(
"`architecture` is provided but `node-version` is missing. In this configuration, the version/architecture of Node will not be changed. To fix this, provide `architecture` in combination with `node-version`" '`architecture` is provided but `node-version` is missing. In this configuration, the version/architecture of Node will not be changed.'
); );
expect(mockNodejsDistribution.setupNodeJs).not.toHaveBeenCalled(); // Setup Node should not be called expect(mockNodejsDistribution.setupNodeJs).not.toHaveBeenCalled(); // Setup Node should not be called
}); });
}); });
function someFunctionThatCallsSetupNodeJs(arg0: { mirrorURL: string; }) {
throw new Error('Function not implemented.');
}

View File

@ -679,8 +679,7 @@ describe('NightlyNodejs', () => {
mirrorURL: '', versionSpec: '18.0.0-nightly', arch: 'x64', mirrorURL: '', versionSpec: '18.0.0-nightly', arch: 'x64',
checkLatest: false, checkLatest: false,
stable: false stable: false
}; }; const nightlyNode = new TestNightlyNodejs(nodeInfo);
const nightlyNode = new TestNightlyNodejs(nodeInfo);
const distributionUrl = nightlyNode.getDistributionUrlPublic(); const distributionUrl = nightlyNode.getDistributionUrlPublic();
@ -689,11 +688,7 @@ describe('NightlyNodejs', () => {
}); });
it('falls back to default distribution URL if mirror URL is undefined', async () => { it('falls back to default distribution URL if mirror URL is undefined', async () => {
const nodeInfo: NodeInputs = { const nodeInfo: NodeInputs = { nodeVersion: '18.0.0-nightly', architecture: 'x64', platform: 'linux' };
mirrorURL: '', versionSpec: '18.0.0-nightly', arch: 'x64',
checkLatest: false,
stable: false
};
const nightlyNode = new TestNightlyNodejs(nodeInfo); const nightlyNode = new TestNightlyNodejs(nodeInfo);
const distributionUrl = nightlyNode.getDistributionUrlPublic(); const distributionUrl = nightlyNode.getDistributionUrlPublic();

View File

@ -11,7 +11,7 @@ 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 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} 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';
@ -830,11 +830,8 @@ describe('setup-node', () => {
}); });
}); });
describe('OfficialBuilds - Mirror URL functionality', () => { describe('OfficialBuilds - Mirror URL functionality', () => {
const nodeInfo: NodeInputs = { const nodeInfo: NodeInputs = { nodeVersion: '18.0.0-nightly', architecture: 'x64', platform: 'linux', mirrorURL: '' };
mirrorURL: '', versionSpec: '18.0.0-nightly', arch: 'x64',
checkLatest: false,
stable: false
};
it('should download using the mirror URL when provided', async () => { it('should download using the mirror URL when provided', async () => {
const mirrorURL = 'https://my.custom.mirror/nodejs'; const mirrorURL = 'https://my.custom.mirror/nodejs';
nodeInfo.mirrorURL = mirrorURL; nodeInfo.mirrorURL = mirrorURL;
@ -921,15 +918,12 @@ const nodeInfo: NodeInputs = {
await expect(officialBuilds.setupNodeJs()).rejects.toThrowError(new Error('Unable to find Node version for platform linux and architecture x64.')); await expect(officialBuilds.setupNodeJs()).rejects.toThrowError(new Error('Unable to find Node version for platform linux and architecture x64.'));
}); });
it('should throw an error if mirror URL is undefined and not provided', async () => { it('should throw an error if mirror URL is undefined and not provided', async () => {
// Mock missing mirror URL nodeInfo.mirrorURL = undefined; // Undefined mirror URL
process.env.MIRROR_URL = undefined; // Simulate missing mirror URL const officialBuilds = new OfficialBuilds(nodeInfo);
// Mock the version lookup method to avoid triggering version errors // Simulate a missing mirror URL scenario
jest.spyOn(OfficialBuilds, 'findVersionInHostedToolCacheDirectory').mockResolvedValue(null); // Simulate "not found"
// Now we expect the function to throw the "Mirror URL is undefined" error
await expect(officialBuilds.setupNodeJs()).rejects.toThrowError('Mirror URL is undefined'); await expect(officialBuilds.setupNodeJs()).rejects.toThrowError('Mirror URL is undefined');
}); });
}); });

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,33 +368,17 @@ 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();
} }
); );
it('throws an error if version is not found', async () => { it('throws an error if version is not found', async () => {
const versionSpec = '19.0.0-rc.3'; const versionSpec = '19.0.0-rc.3';
@ -440,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();
@ -454,86 +400,3 @@ describe('setup-node', () => {
}); });
}); });
}); });
describe('RcBuild - Mirror URL functionality', () => {
const nodeInfo: NodeInputs = {
versionSpec: '18.0.0-rc', arch: 'x64', mirrorURL: '',
checkLatest: false,
stable: false
};
it('should return the default distribution URL if no mirror URL is provided', () => {
const rcBuild = new RcBuild(nodeInfo);
const distributionUrl = rcBuild.getDistributionUrl();
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';
nodeInfo.mirrorURL = mirrorURL;
const rcBuild = new RcBuild(nodeInfo);
// @ts-ignore: Accessing protected method for testing purposes
const distributionMirrorUrl = rcBuild.getDistributionMirrorUrl();
expect(core.info).toHaveBeenCalledWith(`Using mirror URL: ${mirrorURL}`);
expect(distributionMirrorUrl).toBe(mirrorURL);
});
it('should fall back to the default distribution URL if mirror URL is not provided', () => {
nodeInfo.mirrorURL = ''; // No mirror URL
const rcBuild = new RcBuild(nodeInfo);
// @ts-ignore: Accessing protected method for testing purposes
const distributionMirrorUrl = rcBuild.getDistributionMirrorUrl();
expect(core.info).toHaveBeenCalledWith(`Using mirror URL: https://nodejs.org/download/rc`);
expect(distributionMirrorUrl).toBe('https://nodejs.org/download/rc');
});
it('should log the correct info when mirror URL is not provided', () => {
nodeInfo.mirrorURL = ''; // No mirror URL
const rcBuild = new RcBuild(nodeInfo);
// @ts-ignore: Accessing protected method for testing purposes
const distributionMirrorUrl = rcBuild.getDistributionMirrorUrl();
expect(core.info).toHaveBeenCalledWith('Using mirror URL: https://nodejs.org/download/rc');
});
it('should throw an error if mirror URL is undefined and not provided', async () => {
nodeInfo.mirrorURL = undefined; // Undefined mirror URL
const rcBuild = new RcBuild(nodeInfo);
// @ts-ignore: Accessing protected method for testing purposes
await expect(rcBuild['getDistributionMirrorUrl']()).resolves.toBe('https://nodejs.org/download/rc');
});
it('should return mirror URL if provided in nodeInfo', () => {
const mirrorURL = 'https://custom.mirror.url';
nodeInfo.mirrorURL = mirrorURL;
const rcBuild = new RcBuild(nodeInfo);
// @ts-ignore: Accessing protected method for testing purposes
// @ts-ignore: Accessing protected method for testing purposes
const url = rcBuild['getDistributionMirrorUrl']();
expect(core.info).toHaveBeenCalledWith(`Using mirror URL: ${mirrorURL}`);
expect(url).toBe(mirrorURL);
});
it('should use the default URL if mirror URL is empty string', () => {
nodeInfo.mirrorURL = ''; // Empty string for mirror URL
const rcBuild = new RcBuild(nodeInfo);
// @ts-ignore: Accessing protected method for testing purposes
const url = rcBuild['getDistributionMirrorUrl']();
expect(core.info).toHaveBeenCalledWith('Using mirror URL: https://nodejs.org/download/rc');
expect(url).toBe('https://nodejs.org/download/rc');
});
});

16
dist/setup/index.js vendored
View File

@ -100156,7 +100156,7 @@ class BaseDistribution {
} }
getMirrorUrlVersions() { getMirrorUrlVersions() {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const initialUrl = this.getDistributionUrl(); const initialUrl = this.getDistributionMirrorUrl();
const dataUrl = `${initialUrl}/index.json`; const dataUrl = `${initialUrl}/index.json`;
const response = yield this.httpClient.getJson(dataUrl); const response = yield this.httpClient.getJson(dataUrl);
return response.result || []; return response.result || [];
@ -100173,7 +100173,7 @@ class BaseDistribution {
? `${fileName}.zip` ? `${fileName}.zip`
: `${fileName}.7z` : `${fileName}.7z`
: `${fileName}.tar.gz`; : `${fileName}.tar.gz`;
const initialUrl = this.getDistributionUrl(); const initialUrl = this.getDistributionMirrorUrl();
const url = `${initialUrl}/v${version}/${urlFileName}`; const url = `${initialUrl}/v${version}/${urlFileName}`;
return { return {
downloadUrl: url, downloadUrl: url,
@ -100457,7 +100457,7 @@ class NightlyNodejs extends base_distribution_prerelease_1.default {
// Check if mirrorUrl exists in the nodeInfo and return it if available // Check if mirrorUrl exists in the nodeInfo and return it if available
const mirrorUrl = this.nodeInfo.mirrorURL; const mirrorUrl = this.nodeInfo.mirrorURL;
if (mirrorUrl) { if (mirrorUrl) {
core.info(`Downloding Using mirror URL: ${mirrorUrl}`); core.info(`Using mirror URL: ${mirrorUrl}`);
return mirrorUrl; return mirrorUrl;
} }
// Default to the official Node.js nightly distribution URL if no mirror URL is provided // Default to the official Node.js nightly distribution URL if no mirror URL is provided
@ -100647,11 +100647,15 @@ class OfficialBuilds extends base_distribution_1.default {
return version; return version;
} }
getDistributionUrl() { getDistributionUrl() {
if (this.nodeInfo.mirrorURL) {
return this.nodeInfo.mirrorURL;
}
return `https://nodejs.org/dist`; return `https://nodejs.org/dist`;
} }
getDistributionMirrorUrl() {
const mirrorURL = this.nodeInfo.mirrorURL;
if (!mirrorURL) {
throw new Error('Mirror URL is undefined');
}
return mirrorURL;
}
getManifest() { getManifest() {
core.debug('Getting manifest from actions/node-versions@main'); core.debug('Getting manifest from actions/node-versions@main');
return tc.getManifestFromRepo('actions', 'node-versions', this.nodeInfo.auth, 'main'); return tc.getManifestFromRepo('actions', 'node-versions', this.nodeInfo.auth, 'main');

View File

@ -25,6 +25,7 @@ export default abstract class BaseDistribution {
} }
protected abstract getDistributionUrl(): string; protected abstract getDistributionUrl(): string;
protected abstract getDistributionMirrorUrl(): string;
public async setupNodeJs() { public async setupNodeJs() {
let nodeJsVersions: INodeVersion[] | undefined; let nodeJsVersions: INodeVersion[] | undefined;
@ -105,7 +106,7 @@ export default abstract class BaseDistribution {
} }
protected async getMirrorUrlVersions(): Promise<INodeVersion[]> { protected async getMirrorUrlVersions(): Promise<INodeVersion[]> {
const initialUrl = this.getDistributionUrl(); const initialUrl = this.getDistributionMirrorUrl();
const dataUrl = `${initialUrl}/index.json`; const dataUrl = `${initialUrl}/index.json`;
@ -126,7 +127,7 @@ export default abstract class BaseDistribution {
? `${fileName}.zip` ? `${fileName}.zip`
: `${fileName}.7z` : `${fileName}.7z`
: `${fileName}.tar.gz`; : `${fileName}.tar.gz`;
const initialUrl = this.getDistributionUrl(); const initialUrl = this.getDistributionMirrorUrl();
const url = `${initialUrl}/v${version}/${urlFileName}`; const url = `${initialUrl}/v${version}/${urlFileName}`;
return <INodeVersionInfo>{ return <INodeVersionInfo>{

View File

@ -20,7 +20,7 @@ export default class NightlyNodejs extends BasePrereleaseNodejs {
// Check if mirrorUrl exists in the nodeInfo and return it if available // Check if mirrorUrl exists in the nodeInfo and return it if available
const mirrorUrl = this.nodeInfo.mirrorURL; const mirrorUrl = this.nodeInfo.mirrorURL;
if (mirrorUrl) { if (mirrorUrl) {
core.info(`Downloding Using mirror URL: ${mirrorUrl}`); core.info(`Using mirror URL: ${mirrorUrl}`);
return mirrorUrl; return mirrorUrl;
} }

View File

@ -193,12 +193,16 @@ export default class OfficialBuilds extends BaseDistribution {
} }
protected getDistributionUrl(): string { protected getDistributionUrl(): string {
if (this.nodeInfo.mirrorURL) {
return this.nodeInfo.mirrorURL;
}
return `https://nodejs.org/dist`; return `https://nodejs.org/dist`;
} }
protected getDistributionMirrorUrl(): string {
const mirrorURL = this.nodeInfo.mirrorURL;
if (!mirrorURL) {
throw new Error('Mirror URL is undefined');
}
return mirrorURL;
}
private getManifest(): Promise<tc.IToolRelease[]> { private getManifest(): Promise<tc.IToolRelease[]> {
core.debug('Getting manifest from actions/node-versions@main'); core.debug('Getting manifest from actions/node-versions@main');