updated test cases

pull/1232/head
Aparna Jyothi 2025-02-24 12:40:37 +05:30
parent e5561a4d32
commit 7a5031f96f
9 changed files with 172 additions and 272 deletions

View File

@ -1,5 +1,4 @@
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';
@ -19,6 +18,7 @@ import * as installerFactory from '../src/distributions/installer-factory';
jest.mock('../src/distributions/installer-factory', () => ({
getNodejsDistribution: jest.fn()
}));
import {validateMirrorURL} from '../src/util';
describe('main tests', () => {
let inputs = {} as any;
@ -44,6 +44,8 @@ describe('main tests', () => {
let setupNodeJsSpy: jest.SpyInstance;
let validateMirrorUrlSpy: jest.SpyInstance;
beforeEach(() => {
inputs = {};
@ -171,6 +173,45 @@ describe('main tests', () => {
});
});
describe('getNodeVersionFromFile', () => {
each`
contents | expected
${'12'} | ${'12'}
${'12.3'} | ${'12.3'}
${'12.3.4'} | ${'12.3.4'}
${'v12.3.4'} | ${'12.3.4'}
${'lts/erbium'} | ${'lts/erbium'}
${'lts/*'} | ${'lts/*'}
${'nodejs 12.3.4'} | ${'12.3.4'}
${'ruby 2.3.4\nnodejs 12.3.4\npython 3.4.5'} | ${'12.3.4'}
${''} | ${''}
${'unknown format'} | ${'unknown format'}
${' 14.1.0 '} | ${'14.1.0'}
${'{"volta": {"node": ">=14.0.0 <=17.0.0"}}'}| ${'>=14.0.0 <=17.0.0'}
${'{"volta": {"extends": "./package.json"}}'}| ${'18.0.0'}
${'{"engines": {"node": "17.0.0"}}'} | ${'17.0.0'}
${'{}'} | ${null}
`.it('parses "$contents"', ({contents, expected}) => {
const existsSpy = jest.spyOn(fs, 'existsSync');
existsSpy.mockImplementation(() => true);
const readFileSpy = jest.spyOn(fs, 'readFileSync');
readFileSpy.mockImplementation(filePath => {
if (
typeof filePath === 'string' &&
path.basename(filePath) === 'package.json'
) {
// Special case for volta.extends
return '{"volta": {"node": "18.0.0"}}';
}
return contents;
});
expect(util.getNodeVersionFromFile('file')).toBe(expected);
});
});
describe('node-version-file flag', () => {
beforeEach(() => {
delete inputs['node-version'];
@ -287,91 +328,39 @@ describe('main tests', () => {
});
});
// Create a mock object that satisfies the BaseDistribution interface
const createMockNodejsDistribution = () => ({
setupNodeJs: jest.fn(),
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/'), // Example URL
install: jest.fn(),
validate: jest.fn()
// Add any other methods/properties required by your BaseDistribution type
});
describe('Mirror URL Tests', () => {
describe('mirror-url parameter', () => {
beforeEach(() => {
jest.clearAllMocks();
inputs['mirror-url'] = 'https://custom-mirror-url.com';
validateMirrorUrlSpy = jest.spyOn(main, 'run');
validateMirrorUrlSpy.mockImplementation(() => {});
});
it('should pass mirror URL correctly when provided', async () => {
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 jest.Mock).mockReturnValue(
mockNodejsDistribution
);
await main.run();
// Ensure setupNodeJs is called with the correct parameters, including the mirror URL
expect(mockNodejsDistribution.setupNodeJs).toHaveBeenCalledWith({
versionSpec: '14.x',
checkLatest: false,
auth: undefined,
stable: true,
arch: 'x64',
mirrorURL: 'https://custom-mirror-url.com' // Ensure this matches
});
afterEach(() => {
validateMirrorUrlSpy.mockRestore();
});
it('should use default mirror URL when no mirror URL is provided', async () => {
jest.spyOn(core, 'getInput').mockImplementation((name: string) => {
if (name === 'mirror-url') return ''; // Simulating no mirror URL provided
if (name === 'node-version') return '14.x';
return '';
});
const mockNodejsDistribution = createMockNodejsDistribution();
(installerFactory.getNodejsDistribution as jest.Mock).mockReturnValue(
mockNodejsDistribution
);
it('Read mirror-url if mirror-url is provided', async () => {
// Arrange
inputs['mirror-url'] = 'https://custom-mirror-url.com';
// Act
await main.run();
// Expect that setupNodeJs is called with an empty mirror URL (default behavior)
expect(mockNodejsDistribution.setupNodeJs).toHaveBeenCalledWith(
expect.objectContaining({
mirrorURL: '' // Default URL is expected to be handled internally
})
);
// Assert
expect(inputs['mirror-url']).toBeDefined();
});
it('should handle mirror URL with spaces correctly', async () => {
const mirrorURL = 'https://custom-mirror-url.com ';
const expectedTrimmedURL = 'https://custom-mirror-url.com';
it('should throw an error if mirror-url is empty', async () => {
// Arrange
inputs['mirror-url'] = ' ';
// Mock the setupNodeJs function
const mockNodejsDistribution = {
setupNodeJs: jest.fn()
};
// Mock log and setFailed
const logSpy = jest.spyOn(console, 'log').mockImplementation(() => {}); // Mock the log function
// Simulate calling the main function that will trigger setupNodeJs
await main.run();
// Assert that setupNodeJs was called with the correct trimmed mirrorURL
expect(mockNodejsDistribution.setupNodeJs).toHaveBeenCalledWith(
expect.objectContaining({
mirrorURL: expectedTrimmedURL // Ensure the URL is trimmed properly
})
// Act & Assert
expect(() => validateMirrorURL(inputs['mirror-url'])).toThrowError(
'Mirror URL is empty. Please provide a valid mirror URL.'
);
});
});

View File

@ -9,10 +9,11 @@ import cp from 'child_process';
import osm from 'os';
import path from 'path';
import * as main from '../src/main';
import isLtsAlias from '../src/distributions/official_builds/official_builds';
import * as auth from '../src/authutil';
import isLtsAlias 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 nodeTestDist from './data/node-dist-index.json';
@ -829,99 +830,80 @@ describe('setup-node', () => {
}
);
});
describe('mirror-url parameter', () => {
it('Download mirror url if mirror-url is provided', async () => {
// Set up test inputs and environment
os.platform = 'linux';
os.arch = 'x64';
inputs['check-latest'] = 'true';
const mirrorURL = (inputs['mirror-url'] =
'https://custom-mirror-url.com');
inputs['token'] = 'faketoken';
describe('OfficialBuilds - Mirror URL functionality', () => {
let officialBuilds: OfficialBuilds;
// Mock that the version is not in cache (simulate a fresh download)
findSpy.mockImplementation(() => '');
beforeEach(() => {
const mockNodeInfo = {
versionSpec: '16.x',
mirrorURL: 'https://my.custom.mirror/nodejs',
arch: 'x64',
stable: true,
checkLatest: false,
osPlat: 'linux' // Mock OS platform to avoid "undefined" error
};
// Mock implementations for other dependencies
const toolPath = path.normalize('/cache/node/11.11.0/x64');
exSpy.mockImplementation(async () => '/some/other/temp/path');
cacheSpy.mockImplementation(async () => toolPath);
const dlmirrorSpy = jest.fn(); // Create a spy to track the download logic
const mockDownloadNodejs = jest
.spyOn(OfficialBuilds.prototype as any, 'downloadFromMirrorURL')
.mockImplementation(async () => {
dlmirrorSpy();
});
// Run the main method or your logic that invokes `downloadFromMirrorURL`
await main.run(); // This should internally call `downloadFromMirrorURL`
// Prepare the expected path after download
const expPath = path.join(toolPath, 'bin');
// Assert that the spy was called, meaning the download logic was triggered
expect(dlmirrorSpy).toHaveBeenCalled(); // This verifies that the download occurred
// Other assertions to verify the flow
expect(exSpy).toHaveBeenCalled();
expect(logSpy).toHaveBeenCalledWith(
`Attempting to download from ${mirrorURL}...`
);
expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`);
// Clean up mocks after the test
mockDownloadNodejs.mockRestore(); // Ensure to restore the original method after the test
});
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
};
it('fallback to default if mirror url is not provided', async () => {
os.platform = 'linux';
os.arch = 'x64';
// Mock the core.info function to capture logs
const logSpy = jest.spyOn(core, 'info').mockImplementation(() => {});
inputs['node-version'] = '11';
inputs['check-latest'] = 'true';
inputs['always-auth'] = false;
inputs['token'] = 'faketoken';
// Mock the tc.downloadTool to simulate downloading
const mockDownloadPath = '/some/temp/path';
const mockDownloadTool = jest
.spyOn(tc, 'downloadTool')
.mockResolvedValue(mockDownloadPath);
dlSpy.mockImplementation(async () => '/some/temp/path');
const toolPath = path.normalize('/cache/node/12.11.0/x64');
exSpy.mockImplementation(async () => '/some/other/temp/path');
cacheSpy.mockImplementation(async () => toolPath);
// Mock core.addPath to avoid actual path changes
const mockAddPath = jest
.spyOn(core, 'addPath')
.mockImplementation(() => {});
// Mock the findSpy or any other necessary logic
findSpy.mockImplementation(() => nodeInfo);
// Call the function that will use the mirror URL and log the message
const dlmirrorSpy = jest.fn();
dlmirrorSpy.mockImplementation(async () => 'mocked-download-path');
await main.run();
// Ensure downloadTool was called with the mirror URL
expect(mockDownloadTool).toHaveBeenCalledWith(
'https://my.custom.mirror/nodejs'
const expPath = path.join(toolPath, 'bin');
expect(dlSpy).toHaveBeenCalled();
expect(exSpy).toHaveBeenCalled();
expect(logSpy).toHaveBeenCalledWith(
'Attempt to resolve the latest version from manifest...'
);
// Optionally, check that the download path was logged
expect(core.info).toHaveBeenCalledWith(
'downloadPath from downloadFromMirrorURL() /some/temp/path'
);
// Ensure the download path was added to the path
expect(mockAddPath).toHaveBeenCalledWith(mockDownloadPath);
expect(cnSpy).toHaveBeenCalledWith('https://my.custom.mirror/nodejs');
});
it('should log an error and handle failure during mirror URL download', async () => {
const errorMessage = 'Network error';
try {
// Act: Run the main function
await main.run();
} catch (error) {
// Expect core.error to be called with the error message
expect(core.error).toHaveBeenCalledWith(errorMessage);
expect(core.debug).toHaveBeenCalledWith(
expect.stringContaining('empty stack')
);
}
});
it('should log an error message if downloading from the mirror URL fails', async () => {
// Spy on core.setFailed
const setFailedSpy = jest
.spyOn(core, 'setFailed')
.mockImplementation(() => {});
// Mocking downloadFromMirrorURL to reject the promise and simulate a failure
dlSpy.mockImplementation(() =>
Promise.reject(new Error('Download failed'))
);
try {
// Call the function with the mirror URL
await main.run();
} catch (e) {
// Verifying if core.setFailed was called with the error message 'Download failed'
expect(setFailedSpy).toHaveBeenCalledWith('Download failed');
}
expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`);
});
});
});

View File

@ -91098,7 +91098,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.unique = exports.printEnvDetailsAndSetOutput = exports.getNodeVersionFromFile = void 0;
exports.unique = exports.validateMirrorURL = exports.printEnvDetailsAndSetOutput = exports.getNodeVersionFromFile = void 0;
const core = __importStar(__nccwpck_require__(2186));
const exec = __importStar(__nccwpck_require__(1514));
const io = __importStar(__nccwpck_require__(7436));
@ -91186,6 +91186,15 @@ function getToolVersion(tool, options) {
}
});
}
function validateMirrorURL(mirrorURL) {
if (mirrorURL === ' ' || mirrorURL.trim() === 'undefined') {
throw new Error('Mirror URL is empty. Please provide a valid mirror URL.');
}
else {
return mirrorURL;
}
}
exports.validateMirrorURL = validateMirrorURL;
const unique = () => {
const encountered = new Set();
return (value) => {

85
dist/setup/index.js vendored
View File

@ -100438,35 +100438,11 @@ exports.getNodejsDistribution = getNodejsDistribution;
"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) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const base_distribution_prerelease_1 = __importDefault(__nccwpck_require__(957));
const core = __importStar(__nccwpck_require__(2186));
class NightlyNodejs extends base_distribution_prerelease_1.default {
constructor(nodeInfo) {
super(nodeInfo);
@ -100474,21 +100450,9 @@ class NightlyNodejs extends base_distribution_prerelease_1.default {
}
getDistributionUrl() {
if (this.nodeInfo.mirrorURL) {
if (this.nodeInfo.mirrorURL != '') {
core.info('Download using Using mirror URL for nightly Node.js.');
return this.nodeInfo.mirrorURL;
}
else {
if (this.nodeInfo.mirrorURL === '') {
throw new Error('Mirror URL is empty. Please provide a valid mirror URL.');
}
else {
throw new Error('Mirror URL is not a valid');
}
}
return this.nodeInfo.mirrorURL;
}
else {
core.info('Using default distribution URL for nightly Node.js.');
return 'https://nodejs.org/download/nightly';
}
}
@ -100796,17 +100760,7 @@ class RcBuild extends base_distribution_1.default {
}
getDistributionUrl() {
if (this.nodeInfo.mirrorURL) {
if (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 {
throw new Error('Mirror URL is not a valid');
}
}
return this.nodeInfo.mirrorURL;
}
else {
return 'https://nodejs.org/download/rc';
@ -100835,17 +100789,7 @@ class CanaryBuild extends base_distribution_prerelease_1.default {
}
getDistributionUrl() {
if (this.nodeInfo.mirrorURL) {
if (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 {
throw new Error('Mirror URL is not a valid');
}
}
return this.nodeInfo.mirrorURL;
}
else {
return 'https://nodejs.org/download/v8-canary';
@ -100898,7 +100842,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.setupNodeJs = exports.run = void 0;
exports.run = void 0;
const core = __importStar(__nccwpck_require__(2186));
const os_1 = __importDefault(__nccwpck_require__(2037));
const auth = __importStar(__nccwpck_require__(7573));
@ -100926,10 +100870,8 @@ function run() {
if (!arch) {
arch = os_1.default.arch();
}
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.');
}
const mirrorurl = core.getInput('mirror-url');
const mirrorURL = (0, util_1.validateMirrorURL)(mirrorurl);
if (version) {
const token = core.getInput('token');
const auth = !token ? undefined : `token ${token}`;
@ -100990,10 +100932,6 @@ function resolveVersionInput() {
}
return version;
}
function setupNodeJs(mirrorURL) {
throw new Error('Function not implemented.');
}
exports.setupNodeJs = setupNodeJs;
/***/ }),
@ -101039,7 +100977,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.unique = exports.printEnvDetailsAndSetOutput = exports.getNodeVersionFromFile = void 0;
exports.unique = exports.validateMirrorURL = exports.printEnvDetailsAndSetOutput = exports.getNodeVersionFromFile = void 0;
const core = __importStar(__nccwpck_require__(2186));
const exec = __importStar(__nccwpck_require__(1514));
const io = __importStar(__nccwpck_require__(7436));
@ -101127,6 +101065,15 @@ function getToolVersion(tool, options) {
}
});
}
function validateMirrorURL(mirrorURL) {
if (mirrorURL === ' ' || mirrorURL.trim() === 'undefined') {
throw new Error('Mirror URL is empty. Please provide a valid mirror URL.');
}
else {
return mirrorURL;
}
}
exports.validateMirrorURL = validateMirrorURL;
const unique = () => {
const encountered = new Set();
return (value) => {

View File

@ -10,17 +10,7 @@ export default class NightlyNodejs extends BasePrereleaseNodejs {
protected getDistributionUrl(): string {
if (this.nodeInfo.mirrorURL) {
if (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 {
throw new Error('Mirror URL is not a valid');
}
}
return this.nodeInfo.mirrorURL;
} else {
return 'https://nodejs.org/download/nightly';
}

View File

@ -7,17 +7,7 @@ export default class RcBuild extends BaseDistribution {
}
protected getDistributionUrl(): string {
if (this.nodeInfo.mirrorURL) {
if (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 {
throw new Error('Mirror URL is not a valid');
}
}
return this.nodeInfo.mirrorURL;
} else {
return 'https://nodejs.org/download/rc';
}

View File

@ -8,17 +8,7 @@ export default class CanaryBuild extends BasePrereleaseNodejs {
protected getDistributionUrl(): string {
if (this.nodeInfo.mirrorURL) {
if (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 {
throw new Error('Mirror URL is not a valid');
}
}
return this.nodeInfo.mirrorURL;
} else {
return 'https://nodejs.org/download/v8-canary';
}

View File

@ -7,7 +7,11 @@ import * as path from 'path';
import {restoreCache} from './cache-restore';
import {isCacheFeatureAvailable} from './cache-utils';
import {getNodejsDistribution} from './distributions/installer-factory';
import {getNodeVersionFromFile, printEnvDetailsAndSetOutput} from './util';
import {
getNodeVersionFromFile,
printEnvDetailsAndSetOutput,
validateMirrorURL
} from './util';
import {State} from './constants';
export async function run() {
@ -33,12 +37,8 @@ export async function run() {
arch = os.arch();
}
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.'
);
}
const mirrorurl = core.getInput('mirror-url');
const mirrorURL = validateMirrorURL(mirrorurl);
if (version) {
const token = core.getInput('token');
@ -121,6 +121,3 @@ function resolveVersionInput(): string {
return version;
}
export function setupNodeJs(mirrorURL: string) {
throw new Error('Function not implemented.');
}

View File

@ -97,7 +97,13 @@ async function getToolVersion(tool: string, options: string[]) {
return '';
}
}
export function validateMirrorURL(mirrorURL) {
if (mirrorURL === ' ' || mirrorURL.trim() === 'undefined') {
throw new Error('Mirror URL is empty. Please provide a valid mirror URL.');
} else {
return mirrorURL;
}
}
export const unique = () => {
const encountered = new Set();
return (value: unknown): boolean => {