This commit is contained in:
Aparna Jyothi 2025-01-31 17:52:23 +05:30
parent 19df1001b0
commit f40797d717
7 changed files with 295 additions and 78 deletions

View file

@ -10,13 +10,14 @@ import osm from 'os';
import path from 'path';
import * as main from '../src/main';
import * as auth from '../src/authutil';
import {INodeVersion} from '../src/distributions/base-models';
import {INodeVersion, NodeInputs} from '../src/distributions/base-models';
import nodeTestManifest from './data/versions-manifest.json';
import nodeTestDist from './data/node-dist-index.json';
import nodeTestDistNightly from './data/node-nightly-index.json';
import nodeTestDistRc from './data/node-rc-index.json';
import nodeV8CanaryTestDist from './data/v8-canary-dist-index.json';
import canaryBuild from '../src/distributions/v8-canary/canary_builds';
describe('setup-node', () => {
let inputs = {} as any;
@ -529,3 +530,84 @@ 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,4 +1,5 @@
import * as core from '@actions/core';
import 'jest';
import * as exec from '@actions/exec';
import * as tc from '@actions/tool-cache';
import * as cache from '@actions/cache';
@ -13,6 +14,7 @@ import each from 'jest-each';
import * as main from '../src/main';
import * as util from '../src/util';
import OfficialBuilds from '../src/distributions/official_builds/official_builds';
import * as installerFactory from '../src/distributions/installer-factory';
jest.mock('../src/distributions/installer-factory', () => ({
getNodejsDistribution: jest.fn()
@ -286,57 +288,36 @@ describe('main tests', () => {
});
});
// Mock the necessary modules
jest.mock('@actions/core');
jest.mock('./distributions/installer-factory');
// Create a mock object that satisfies the BaseDistribution type
// Create a mock object that satisfies the BaseDistribution interface
const createMockNodejsDistribution = () => ({
setupNodeJs: jest.fn(),
// Mocking other properties required by the BaseDistribution type (adjust based on your actual types)
httpClient: {}, // Example for httpClient, replace with proper mock if necessary
osPlat: 'darwin', // Example platform ('darwin', 'win32', 'linux', etc.)
httpClient: {}, // Mocking the httpClient (you can replace this with more detailed mocks if needed)
osPlat: 'darwin', // Mocking osPlat (the platform the action will run on, e.g., 'darwin', 'win32', 'linux')
nodeInfo: {
version: '14.x',
arch: 'x64',
platform: 'darwin',
},
getDistributionUrl: jest.fn().mockReturnValue('https://nodejs.org/dist/'), // Default distribution URL
getDistributionUrl: jest.fn().mockReturnValue('https://nodejs.org/dist/'), // Example URL
install: jest.fn(),
validate: jest.fn(),
// Mock any other methods/properties defined in BaseDistribution
// Add any other methods/properties required by your BaseDistribution type
});
// 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', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should pass mirror URL correctly when provided', async () => {
(core.getInput as jest.Mock).mockImplementation((name: string) => {
jest.spyOn(core, 'getInput').mockImplementation((name: string) => {
if (name === 'mirror-url') return 'https://custom-mirror-url.com';
if (name === 'node-version') return '14.x';
return '';
});
const mockNodejsDistribution = createMockNodejsDistribution();
(installerFactory.getNodejsDistribution as unknown as jest.Mock<typeof installerFactory.getNodejsDistribution>).mockReturnValue(mockNodejsDistribution);
(installerFactory.getNodejsDistribution as jest.Mock).mockReturnValue(mockNodejsDistribution);
await main.run();
@ -352,7 +333,7 @@ describe('Mirror URL Tests', () => {
});
it('should use default mirror URL when no mirror URL is provided', async () => {
(core.getInput as jest.Mock).mockImplementation((name: string) => {
jest.spyOn(core, 'getInput').mockImplementation((name: string) => {
if (name === 'mirror-url') return '';
if (name === 'node-version') return '14.x';
return '';
@ -363,32 +344,39 @@ describe('Mirror URL Tests', () => {
await main.run();
// Expect that setupNodeJs is called with an empty mirror URL (which will default inside the function)
// Expect that setupNodeJs is called with an empty mirror URL
expect(mockNodejsDistribution.setupNodeJs).toHaveBeenCalledWith(expect.objectContaining({
mirrorURL: '', // Default URL is expected to be handled internally
}));
});
it('should handle mirror URL with spaces correctly', async () => {
(core.getInput as jest.Mock).mockImplementation((name: string) => {
if (name === 'mirror-url') return ' https://custom-mirror-url.com ';
if (name === 'node-version') return '14.x';
return '';
});
const mirrorURL = 'https://custom-mirror-url.com ';
const expectedTrimmedURL = 'https://custom-mirror-url.com';
const mockNodejsDistribution = createMockNodejsDistribution();
(installerFactory.getNodejsDistribution as jest.Mock).mockReturnValue(mockNodejsDistribution);
// Mock the setupNodeJs function
const mockNodejsDistribution = {
setupNodeJs: jest.fn(),
};
await main.run();
// Simulate calling the main function that will trigger setupNodeJs
await main.run({ mirrorURL });
// Expect that setupNodeJs is called with the trimmed mirror URL
expect(mockNodejsDistribution.setupNodeJs).toHaveBeenCalledWith(expect.objectContaining({
mirrorURL: 'https://custom-mirror-url.com',
}));
// 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,
})
);
});
it('should warn if architecture is provided but node-version is missing', async () => {
(core.getInput as jest.Mock).mockImplementation((name: string) => {
jest.spyOn(core, 'getInput').mockImplementation((name: string) => {
if (name === 'architecture') return 'x64';
if (name === 'node-version') return '';
return '';
@ -396,14 +384,18 @@ describe('Mirror URL Tests', () => {
const mockWarning = jest.spyOn(core, 'warning');
const mockNodejsDistribution = createMockNodejsDistribution();
installerFactory.getNodejsDistribution.mockReturnValue(mockNodejsDistribution);
(installerFactory.getNodejsDistribution as jest.Mock).mockReturnValue(mockNodejsDistribution);
await main.run();
expect(mockWarning).toHaveBeenCalledWith(
'`architecture` is provided but `node-version` is missing. In this configuration, the version/architecture of Node will not be changed.'
"`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`"
);
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,7 +679,8 @@ describe('NightlyNodejs', () => {
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();
@ -688,8 +689,12 @@ describe('NightlyNodejs', () => {
});
it('falls back to default distribution URL if mirror URL is undefined', async () => {
const nodeInfo: NodeInputs = { nodeVersion: '18.0.0-nightly', architecture: 'x64', platform: 'linux' };
const nightlyNode = new TestNightlyNodejs(nodeInfo);
const nodeInfo: NodeInputs = {
mirrorURL: '', versionSpec: '18.0.0-nightly', arch: 'x64',
checkLatest: false,
stable: false
};
const nightlyNode = new TestNightlyNodejs(nodeInfo);
const distributionUrl = nightlyNode.getDistributionUrlPublic();

View file

@ -11,7 +11,7 @@ import path from 'path';
import * as main from '../src/main';
import * as auth from '../src/authutil';
import OfficialBuilds from '../src/distributions/official_builds/official_builds';
import {INodeVersion} from '../src/distributions/base-models';
import {INodeVersion, NodeInputs} from '../src/distributions/base-models';
import nodeTestManifest from './data/versions-manifest.json';
import nodeTestDist from './data/node-dist-index.json';
@ -830,8 +830,11 @@ describe('setup-node', () => {
});
});
describe('OfficialBuilds - Mirror URL functionality', () => {
const nodeInfo: NodeInputs = { nodeVersion: '18.0.0-nightly', architecture: 'x64', platform: 'linux', mirrorURL: '' };
const nodeInfo: NodeInputs = {
mirrorURL: '', versionSpec: '18.0.0-nightly', arch: 'x64',
checkLatest: false,
stable: false
};
it('should download using the mirror URL when provided', async () => {
const mirrorURL = 'https://my.custom.mirror/nodejs';
nodeInfo.mirrorURL = mirrorURL;
@ -918,12 +921,15 @@ describe('OfficialBuilds - Mirror URL functionality', () => {
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 () => {
nodeInfo.mirrorURL = undefined; // Undefined mirror URL
const officialBuilds = new OfficialBuilds(nodeInfo);
// Mock missing mirror URL
process.env.MIRROR_URL = undefined; // Simulate missing mirror URL
// Simulate a missing mirror URL scenario
// Mock the version lookup method to avoid triggering version errors
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');
});
});

View file

@ -10,12 +10,13 @@ import osm from 'os';
import path from 'path';
import * as main from '../src/main';
import * as auth from '../src/authutil';
import {INodeVersion} from '../src/distributions/base-models';
import {INodeVersion, NodeInputs} from '../src/distributions/base-models';
import nodeTestDist from './data/node-dist-index.json';
import nodeTestDistNightly from './data/node-nightly-index.json';
import nodeTestDistRc from './data/node-rc-index.json';
import nodeV8CanaryTestDist from './data/v8-canary-dist-index.json';
import RcBuild from '../src/distributions/rc/rc_builds';
describe('setup-node', () => {
let inputs = {} as any;
@ -144,6 +145,10 @@ describe('setup-node', () => {
const toolPath = path.normalize('/cache/node/12.0.0-rc.1/x64');
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();
expect(logSpy).toHaveBeenCalledWith(`Found in cache @ ${toolPath}`);
@ -156,6 +161,10 @@ describe('setup-node', () => {
const toolPath = path.normalize('/cache/node/12.0.0-rc.1/x64');
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();
expect(logSpy).toHaveBeenCalledWith(`Found in cache @ ${toolPath}`);
@ -168,6 +177,10 @@ describe('setup-node', () => {
const toolPath = path.normalize('/cache/node/12.0.0-rc.1/x64');
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();
const expPath = path.join(toolPath, 'bin');
@ -224,6 +237,10 @@ describe('setup-node', () => {
inputs['node-version'] = versionSpec;
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();
expect(cnSpy).toHaveBeenCalledWith(
@ -247,6 +264,11 @@ describe('setup-node', () => {
dlSpy.mockImplementation(() => {
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();
expect(cnSpy).toHaveBeenCalledWith(`::error::${errMsg}${osm.EOL}`);
@ -281,6 +303,9 @@ describe('setup-node', () => {
const toolPath = path.normalize(`/cache/node/${version}/${arch}`);
exSpy.mockImplementation(async () => '/some/other/temp/path');
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();
expect(dlSpy).toHaveBeenCalled();
@ -331,6 +356,11 @@ describe('setup-node', () => {
inputs['node-version'] = input;
os['arch'] = 'x64';
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
await main.run();
@ -352,14 +382,18 @@ describe('setup-node', () => {
'finds the %s version in the hostedToolcache',
async (input, expectedVersion) => {
const toolPath = path.normalize(`/cache/node/${expectedVersion}/x64`);
findSpy.mockImplementation((_, version) =>
path.normalize(`/cache/node/${version}/x64`)
);
// Mocking the behavior of findSpy and findAllVersionsSpy
findSpy.mockImplementation((_, version) => {
console.log(`findSpy called for version: ${version}`); // Debugging line
return path.normalize(`/cache/node/${version}/x64`);
});
findAllVersionsSpy.mockReturnValue([
'2.2.2-rc.2',
'1.1.1-rc.1',
'99.1.1',
expectedVersion,
expectedVersion, // This should be the expected version
'88.1.1',
'3.3.3-rc.3'
]);
@ -368,17 +402,33 @@ describe('setup-node', () => {
os['arch'] = 'x64';
os['platform'] = 'linux';
// act
// 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: Run the main function (your application logic)
await main.run();
// assert
// Debugging output to check if logSpy was called
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}`);
// Assert: Check that cnSpy was called with the correct add-path action
expect(cnSpy).toHaveBeenCalledWith(
`::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 () => {
const versionSpec = '19.0.0-rc.3';
@ -390,6 +440,10 @@ describe('setup-node', () => {
inputs['node-version'] = versionSpec;
os['arch'] = 'x64';
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
await main.run();
@ -400,3 +454,86 @@ 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');
});
});

5
dist/setup/index.js vendored
View file

@ -100651,10 +100651,7 @@ class OfficialBuilds extends base_distribution_1.default {
}
getDistributionMirrorUrl() {
const mirrorURL = this.nodeInfo.mirrorURL;
if (!mirrorURL) {
throw new Error('Mirror URL is undefined');
}
return mirrorURL;
return mirrorURL !== null && mirrorURL !== void 0 ? mirrorURL : '';
}
getManifest() {
core.debug('Getting manifest from actions/node-versions@main');

View file

@ -198,10 +198,8 @@ export default class OfficialBuilds extends BaseDistribution {
protected getDistributionMirrorUrl(): string {
const mirrorURL = this.nodeInfo.mirrorURL;
if (!mirrorURL) {
throw new Error('Mirror URL is undefined');
}
return mirrorURL;
return mirrorURL ?? '';
}
private getManifest(): Promise<tc.IToolRelease[]> {